blob: 2b6b165837bf3463b59251f85cb91a263e80ffd5 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000016#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/Operator.h"
24#include "llvm/IR/ValueSymbolTable.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;
Michael Ilseman407a6162012-11-15 22:34:00 +000055
Chris Lattner449c3102010-04-01 05:14:45 +000056 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman407a6162012-11-15 22:34:00 +000058
Chris Lattner449c3102010-04-01 05:14:45 +000059 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 }
Michael Ilseman407a6162012-11-15 22:34:00 +000067
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]);
Michael Ilseman407a6162012-11-15 22:34:00 +000079
Chris Lattner09d9ef42009-10-28 03:39:23 +000080 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +000082
Chris Lattner09d9ef42009-10-28 03:39:23 +000083 // Resolve all these references.
Michael Ilseman407a6162012-11-15 22:34:00 +000084 if (ResolveForwardRefBlockAddresses(TheFn,
Chris Lattner09d9ef42009-10-28 03:39:23 +000085 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +000088
Chris Lattner09d9ef42009-10-28 03:39:23 +000089 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
Michael Ilseman407a6162012-11-15 22:34:00 +000091
Chris Lattner1afcace2011-07-09 17:41:24 +000092 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
96
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
106 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Chris Lattnerdf986172009-01-02 07:01:27 +0000108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000111 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patel1c7eea62009-07-08 19:23:54 +0000113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000116 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Devang Patel1c7eea62009-07-08 19:23:54 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 return false;
124}
125
Michael Ilseman407a6162012-11-15 22:34:00 +0000126bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
131 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000132 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000135 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000139 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000140 } else {
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
143 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000144
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +0000148
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
153 }
154 return false;
155}
156
157
Chris Lattnerdf986172009-01-02 07:01:27 +0000158//===----------------------------------------------------------------------===//
159// Top-Level Entities
160//===----------------------------------------------------------------------===//
161
162bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000163 while (1) {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling3defc0b2012-11-28 08:41:48 +0000171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000178
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000187 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
Bill Wendling5e721d72010-07-01 21:55:59 +0000188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000193 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000194 case lltok::kw_appending: // OptionalLinkage
195 case lltok::kw_dllexport: // OptionalLinkage
196 case lltok::kw_common: // OptionalLinkage
197 case lltok::kw_dllimport: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000200 unsigned Linkage, Visibility;
201 if (ParseOptionalLinkage(Linkage) ||
202 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000203 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return true;
205 break;
206 }
207 case lltok::kw_default: // OptionalVisibility
208 case lltok::kw_hidden: // OptionalVisibility
209 case lltok::kw_protected: { // OptionalVisibility
210 unsigned Visibility;
211 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000212 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 return true;
214 break;
215 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 case lltok::kw_thread_local: // OptionalThreadLocal
218 case lltok::kw_addrspace: // OptionalAddrSpace
219 case lltok::kw_constant: // GlobalType
220 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000222 break;
223 }
224 }
225}
226
227
228/// toplevelentity
229/// ::= 'module' 'asm' STRINGCONSTANT
230bool LLParser::ParseModuleAsm() {
231 assert(Lex.getKind() == lltok::kw_module);
232 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000233
234 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
236 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Rafael Espindola38c4e532011-03-02 04:14:42 +0000238 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000239 return false;
240}
241
242/// toplevelentity
243/// ::= 'target' 'triple' '=' STRINGCONSTANT
244/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
245bool LLParser::ParseTargetDefinition() {
246 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000248 switch (Lex.Lex()) {
249 default: return TokError("unknown target property");
250 case lltok::kw_triple:
251 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000252 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
253 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000255 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return false;
257 case lltok::kw_datalayout:
258 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
260 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000261 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000263 return false;
264 }
265}
266
Bill Wendling3defc0b2012-11-28 08:41:48 +0000267/// toplevelentity
268/// ::= 'deplibs' '=' '[' ']'
269/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
270/// FIXME: Remove in 4.0. Currently parse, but ignore.
271bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
273 Lex.Lex();
274 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;
280
281 do {
282 std::string Str;
283 if (ParseStringConstant(Str)) return true;
284 } while (EatIfPresent(lltok::comma));
285
286 return ParseToken(lltok::rsquare, "expected ']' at end of list");
287}
288
Dan Gohman3845e502009-08-12 23:32:33 +0000289/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000290/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000291bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000292 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000293 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000294 Lex.Lex(); // eat LocalVarID;
295
296 if (ParseToken(lltok::equal, "expected '=' after name") ||
297 ParseToken(lltok::kw_type, "expected 'type' after '='"))
298 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000299
Chris Lattner1afcace2011-07-09 17:41:24 +0000300 if (TypeID >= NumberedTypes.size())
301 NumberedTypes.resize(TypeID+1);
Michael Ilseman407a6162012-11-15 22:34:00 +0000302
Chris Lattner1afcace2011-07-09 17:41:24 +0000303 Type *Result = 0;
304 if (ParseStructDefinition(TypeLoc, "",
305 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000306
Chris Lattner1afcace2011-07-09 17:41:24 +0000307 if (!isa<StructType>(Result)) {
308 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
309 if (Entry.first)
310 return Error(TypeLoc, "non-struct types may not be recursive");
311 Entry.first = Result;
312 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000313 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000314
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 return false;
316}
317
Chris Lattner1afcace2011-07-09 17:41:24 +0000318
Chris Lattnerdf986172009-01-02 07:01:27 +0000319/// toplevelentity
320/// ::= LocalVar '=' 'type' type
321bool LLParser::ParseNamedType() {
322 std::string Name = Lex.getStrVal();
323 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000324 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000325
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000326 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000327 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000328 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000329
Chris Lattner1afcace2011-07-09 17:41:24 +0000330 Type *Result = 0;
331 if (ParseStructDefinition(NameLoc, Name,
332 NamedTypes[Name], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000333
Chris Lattner1afcace2011-07-09 17:41:24 +0000334 if (!isa<StructType>(Result)) {
335 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
336 if (Entry.first)
337 return Error(NameLoc, "non-struct types may not be recursive");
338 Entry.first = Result;
339 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000341
Chris Lattner1afcace2011-07-09 17:41:24 +0000342 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000343}
344
345
346/// toplevelentity
347/// ::= 'declare' FunctionHeader
348bool LLParser::ParseDeclare() {
349 assert(Lex.getKind() == lltok::kw_declare);
350 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000351
Chris Lattnerdf986172009-01-02 07:01:27 +0000352 Function *F;
353 return ParseFunctionHeader(F, false);
354}
355
356/// toplevelentity
357/// ::= 'define' FunctionHeader '{' ...
358bool LLParser::ParseDefine() {
359 assert(Lex.getKind() == lltok::kw_define);
360 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000361
Chris Lattnerdf986172009-01-02 07:01:27 +0000362 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000363 return ParseFunctionHeader(F, true) ||
364 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000365}
366
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000367/// ParseGlobalType
368/// ::= 'constant'
369/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000370bool LLParser::ParseGlobalType(bool &IsConstant) {
371 if (Lex.getKind() == lltok::kw_constant)
372 IsConstant = true;
373 else if (Lex.getKind() == lltok::kw_global)
374 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000375 else {
376 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000377 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000378 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000379 Lex.Lex();
380 return false;
381}
382
Dan Gohman3845e502009-08-12 23:32:33 +0000383/// ParseUnnamedGlobal:
384/// OptionalVisibility ALIAS ...
385/// OptionalLinkage OptionalVisibility ... -> global variable
386/// GlobalID '=' OptionalVisibility ALIAS ...
387/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
388bool LLParser::ParseUnnamedGlobal() {
389 unsigned VarID = NumberedVals.size();
390 std::string Name;
391 LocTy NameLoc = Lex.getLoc();
392
393 // Handle the GlobalID form.
394 if (Lex.getKind() == lltok::GlobalID) {
395 if (Lex.getUIntVal() != VarID)
396 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000397 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000398 Lex.Lex(); // eat GlobalID;
399
400 if (ParseToken(lltok::equal, "expected '=' after name"))
401 return true;
402 }
403
404 bool HasLinkage;
405 unsigned Linkage, Visibility;
406 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
407 ParseOptionalVisibility(Visibility))
408 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000409
Dan Gohman3845e502009-08-12 23:32:33 +0000410 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
411 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
412 return ParseAlias(Name, NameLoc, Visibility);
413}
414
Chris Lattnerdf986172009-01-02 07:01:27 +0000415/// ParseNamedGlobal:
416/// GlobalVar '=' OptionalVisibility ALIAS ...
417/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
418bool LLParser::ParseNamedGlobal() {
419 assert(Lex.getKind() == lltok::GlobalVar);
420 LocTy NameLoc = Lex.getLoc();
421 std::string Name = Lex.getStrVal();
422 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000423
Chris Lattnerdf986172009-01-02 07:01:27 +0000424 bool HasLinkage;
425 unsigned Linkage, Visibility;
426 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
427 ParseOptionalLinkage(Linkage, HasLinkage) ||
428 ParseOptionalVisibility(Visibility))
429 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000430
Chris Lattnerdf986172009-01-02 07:01:27 +0000431 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
432 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
433 return ParseAlias(Name, NameLoc, Visibility);
434}
435
Devang Patel256be962009-07-20 19:00:08 +0000436// MDString:
437// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000438bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000439 std::string Str;
440 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000441 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000442 return false;
443}
444
445// MDNode:
446// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000447//
448/// This version of ParseMDNodeID returns the slot number and null in the case
449/// of a forward reference.
450bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
451 // !{ ..., !42, ... }
452 if (ParseUInt32(SlotNo)) return true;
453
454 // Check existing MDNode.
455 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
456 Result = NumberedMetadata[SlotNo];
457 else
458 Result = 0;
459 return false;
460}
461
Chris Lattner4a72efc2009-12-30 04:15:23 +0000462bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000463 // !{ ..., !42, ... }
464 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000465 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000466
Chris Lattner449c3102010-04-01 05:14:45 +0000467 // If not a forward reference, just return it now.
468 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000469
Chris Lattner449c3102010-04-01 05:14:45 +0000470 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000471 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000472 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman407a6162012-11-15 22:34:00 +0000473
Chris Lattner0834e6a2009-12-30 04:51:58 +0000474 if (NumberedMetadata.size() <= MID)
475 NumberedMetadata.resize(MID+1);
476 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000477 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000478 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479}
Devang Patel256be962009-07-20 19:00:08 +0000480
Chris Lattner84d03b12009-12-29 22:35:39 +0000481/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000482/// !foo = !{ !1, !2 }
483bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000484 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000485 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000486 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000487
Chris Lattner84d03b12009-12-29 22:35:39 +0000488 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000489 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000490 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000491 return true;
492
Dan Gohman17aa92c2010-07-21 23:38:33 +0000493 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000494 if (Lex.getKind() != lltok::rbrace)
495 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000496 if (ParseToken(lltok::exclaim, "Expected '!' here"))
497 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000498
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000499 MDNode *N = 0;
500 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000501 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000502 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000503
504 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
505 return true;
506
Devang Pateleff2ab62009-07-29 00:34:02 +0000507 return false;
508}
509
Devang Patel923078c2009-07-01 19:21:12 +0000510/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000511/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000512bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000513 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000514 Lex.Lex();
515 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000516
517 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000518 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000519 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000520 if (ParseUInt32(MetadataID) ||
521 ParseToken(lltok::equal, "expected '=' here") ||
522 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000523 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000524 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000525 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000526 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000527 return true;
528
Jay Foadec9186b2011-04-21 19:59:31 +0000529 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman407a6162012-11-15 22:34:00 +0000530
Chris Lattner0834e6a2009-12-30 04:51:58 +0000531 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000532 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000533 FI = ForwardRefMDNodes.find(MetadataID);
534 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000535 MDNode *Temp = FI->second.first;
536 Temp->replaceAllUsesWith(Init);
537 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000538 ForwardRefMDNodes.erase(FI);
Michael Ilseman407a6162012-11-15 22:34:00 +0000539
Chris Lattner0834e6a2009-12-30 04:51:58 +0000540 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
541 } else {
542 if (MetadataID >= NumberedMetadata.size())
543 NumberedMetadata.resize(MetadataID+1);
544
545 if (NumberedMetadata[MetadataID] != 0)
546 return TokError("Metadata id is already used");
547 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000548 }
549
Devang Patel923078c2009-07-01 19:21:12 +0000550 return false;
551}
552
Chris Lattnerdf986172009-01-02 07:01:27 +0000553/// ParseAlias:
554/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
555/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000556/// ::= TypeAndValue
557/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000558/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000559///
560/// Everything through visibility has already been parsed.
561///
562bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
563 unsigned Visibility) {
564 assert(Lex.getKind() == lltok::kw_alias);
565 Lex.Lex();
566 unsigned Linkage;
567 LocTy LinkageLoc = Lex.getLoc();
568 if (ParseOptionalLinkage(Linkage))
569 return true;
570
571 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000572 Linkage != GlobalValue::WeakAnyLinkage &&
573 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000574 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000575 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000576 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling32811be2012-08-17 18:33:14 +0000577 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000578 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000579
Chris Lattnerdf986172009-01-02 07:01:27 +0000580 Constant *Aliasee;
581 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000582 if (Lex.getKind() != lltok::kw_bitcast &&
583 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000584 if (ParseGlobalTypeAndValue(Aliasee)) return true;
585 } else {
586 // The bitcast dest type is not present, it is implied by the dest type.
587 ValID ID;
588 if (ParseValID(ID)) return true;
589 if (ID.Kind != ValID::t_Constant)
590 return Error(AliaseeLoc, "invalid aliasee");
591 Aliasee = ID.ConstantVal;
592 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000593
Duncan Sands1df98592010-02-16 11:11:14 +0000594 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000595 return Error(AliaseeLoc, "alias must have pointer type");
596
597 // Okay, create the alias but do not insert it into the module yet.
598 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
599 (GlobalValue::LinkageTypes)Linkage, Name,
600 Aliasee);
601 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000602
Chris Lattnerdf986172009-01-02 07:01:27 +0000603 // See if this value already exists in the symbol table. If so, it is either
604 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000605 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000606 // See if this was a redefinition. If so, there is no entry in
607 // ForwardRefVals.
608 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
609 I = ForwardRefVals.find(Name);
610 if (I == ForwardRefVals.end())
611 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
612
613 // Otherwise, this was a definition of forward ref. Verify that types
614 // agree.
615 if (Val->getType() != GA->getType())
616 return Error(NameLoc,
617 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000618
Chris Lattnerdf986172009-01-02 07:01:27 +0000619 // If they agree, just RAUW the old value with the alias and remove the
620 // forward ref info.
621 Val->replaceAllUsesWith(GA);
622 Val->eraseFromParent();
623 ForwardRefVals.erase(I);
624 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000625
Chris Lattnerdf986172009-01-02 07:01:27 +0000626 // Insert into the module, we know its name won't collide now.
627 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000628 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000629
Chris Lattnerdf986172009-01-02 07:01:27 +0000630 return false;
631}
632
633/// ParseGlobal
634/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000635/// OptionalAddrSpace OptionalUnNammedAddr
636/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000637/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000638/// OptionalAddrSpace OptionalUnNammedAddr
639/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000640///
641/// Everything through visibility has been parsed already.
642///
643bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
644 unsigned Linkage, bool HasLinkage,
645 unsigned Visibility) {
646 unsigned AddrSpace;
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000647 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000648 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000649 LocTy UnnamedAddrLoc;
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000650 LocTy IsExternallyInitializedLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000651 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattner1afcace2011-07-09 17:41:24 +0000653 Type *Ty = 0;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000654 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
657 &UnnamedAddrLoc) ||
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000658 ParseOptionalToken(lltok::kw_externally_initialized,
659 IsExternallyInitialized,
660 &IsExternallyInitializedLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 ParseGlobalType(IsConstant) ||
662 ParseType(Ty, TyLoc))
663 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000664
Chris Lattnerdf986172009-01-02 07:01:27 +0000665 // If the linkage is specified and is external, then no initializer is
666 // present.
667 Constant *Init = 0;
668 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000669 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 Linkage != GlobalValue::ExternalLinkage)) {
671 if (ParseGlobalValue(Ty, Init))
672 return true;
673 }
674
Duncan Sands1df98592010-02-16 11:11:14 +0000675 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000676 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000677
Chris Lattnerdf986172009-01-02 07:01:27 +0000678 GlobalVariable *GV = 0;
679
680 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000681 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000682 if (GlobalValue *GVal = M->getNamedValue(Name)) {
683 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
684 return Error(NameLoc, "redefinition of global '@" + Name + "'");
685 GV = cast<GlobalVariable>(GVal);
686 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000687 } else {
688 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
689 I = ForwardRefValIDs.find(NumberedVals.size());
690 if (I != ForwardRefValIDs.end()) {
691 GV = cast<GlobalVariable>(I->second.first);
692 ForwardRefValIDs.erase(I);
693 }
694 }
695
696 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000697 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000698 Name, 0, GlobalVariable::NotThreadLocal,
699 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 } else {
701 if (GV->getType()->getElementType() != Ty)
702 return Error(TyLoc,
703 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000704
Chris Lattnerdf986172009-01-02 07:01:27 +0000705 // Move the forward-reference to the correct spot in the module.
706 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
707 }
708
709 if (Name.empty())
710 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000711
Chris Lattnerdf986172009-01-02 07:01:27 +0000712 // Set the parsed properties on the global.
713 if (Init)
714 GV->setInitializer(Init);
715 GV->setConstant(IsConstant);
716 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
717 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000718 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000719 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +0000720 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000721
Chris Lattnerdf986172009-01-02 07:01:27 +0000722 // Parse attributes on the global.
723 while (Lex.getKind() == lltok::comma) {
724 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000725
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 if (Lex.getKind() == lltok::kw_section) {
727 Lex.Lex();
728 GV->setSection(Lex.getStrVal());
729 if (ParseToken(lltok::StringConstant, "expected global section string"))
730 return true;
731 } else if (Lex.getKind() == lltok::kw_align) {
732 unsigned Alignment;
733 if (ParseOptionalAlignment(Alignment)) return true;
734 GV->setAlignment(Alignment);
735 } else {
736 TokError("unknown global variable property!");
737 }
738 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000739
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 return false;
741}
742
743
744//===----------------------------------------------------------------------===//
745// GlobalValue Reference/Resolution Routines.
746//===----------------------------------------------------------------------===//
747
748/// GetGlobalVal - Get a value with the specified name or ID, creating a
749/// forward reference record if needed. This can return null if the value
750/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000751GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000752 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000753 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000754 if (PTy == 0) {
755 Error(Loc, "global variable reference must have pointer type");
756 return 0;
757 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 // Look this name up in the normal function symbol table.
760 GlobalValue *Val =
761 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000762
Chris Lattnerdf986172009-01-02 07:01:27 +0000763 // If this is a forward reference for the value, see if we already created a
764 // forward ref record.
765 if (Val == 0) {
766 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
767 I = ForwardRefVals.find(Name);
768 if (I != ForwardRefVals.end())
769 Val = I->second.first;
770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000771
Chris Lattnerdf986172009-01-02 07:01:27 +0000772 // If we have the value in the symbol table or fwd-ref table, return it.
773 if (Val) {
774 if (Val->getType() == Ty) return Val;
775 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000776 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 return 0;
778 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000779
Chris Lattnerdf986172009-01-02 07:01:27 +0000780 // Otherwise, create a new forward reference for this value and remember it.
781 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000782 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000783 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000784 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000785 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinskieaff2d52012-11-16 21:03:47 +0000786 GlobalValue::ExternalWeakLinkage, 0, Name,
787 0, GlobalVariable::NotThreadLocal,
788 PTy->getAddressSpace());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000789
Chris Lattnerdf986172009-01-02 07:01:27 +0000790 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
791 return FwdVal;
792}
793
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000794GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
795 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000796 if (PTy == 0) {
797 Error(Loc, "global variable reference must have pointer type");
798 return 0;
799 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000800
Chris Lattnerdf986172009-01-02 07:01:27 +0000801 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000802
Chris Lattnerdf986172009-01-02 07:01:27 +0000803 // If this is a forward reference for the value, see if we already created a
804 // forward ref record.
805 if (Val == 0) {
806 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
807 I = ForwardRefValIDs.find(ID);
808 if (I != ForwardRefValIDs.end())
809 Val = I->second.first;
810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000811
Chris Lattnerdf986172009-01-02 07:01:27 +0000812 // If we have the value in the symbol table or fwd-ref table, return it.
813 if (Val) {
814 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000815 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000816 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 return 0;
818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Chris Lattnerdf986172009-01-02 07:01:27 +0000820 // Otherwise, create a new forward reference for this value and remember it.
821 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000822 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000823 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000824 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000825 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
826 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000827
Chris Lattnerdf986172009-01-02 07:01:27 +0000828 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
829 return FwdVal;
830}
831
832
833//===----------------------------------------------------------------------===//
834// Helper Routines.
835//===----------------------------------------------------------------------===//
836
837/// ParseToken - If the current token has the specified kind, eat it and return
838/// success. Otherwise, emit the specified error and return failure.
839bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
840 if (Lex.getKind() != T)
841 return TokError(ErrMsg);
842 Lex.Lex();
843 return false;
844}
845
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000846/// ParseStringConstant
847/// ::= StringConstant
848bool LLParser::ParseStringConstant(std::string &Result) {
849 if (Lex.getKind() != lltok::StringConstant)
850 return TokError("expected string constant");
851 Result = Lex.getStrVal();
852 Lex.Lex();
853 return false;
854}
855
856/// ParseUInt32
857/// ::= uint32
858bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
860 return TokError("expected integer");
861 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
862 if (Val64 != unsigned(Val64))
863 return TokError("expected 32-bit integer (too large)");
864 Val = Val64;
865 Lex.Lex();
866 return false;
867}
868
Hans Wennborgce718ff2012-06-23 11:37:03 +0000869/// ParseTLSModel
870/// := 'localdynamic'
871/// := 'initialexec'
872/// := 'localexec'
873bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
874 switch (Lex.getKind()) {
875 default:
876 return TokError("expected localdynamic, initialexec or localexec");
877 case lltok::kw_localdynamic:
878 TLM = GlobalVariable::LocalDynamicTLSModel;
879 break;
880 case lltok::kw_initialexec:
881 TLM = GlobalVariable::InitialExecTLSModel;
882 break;
883 case lltok::kw_localexec:
884 TLM = GlobalVariable::LocalExecTLSModel;
885 break;
886 }
887
888 Lex.Lex();
889 return false;
890}
891
892/// ParseOptionalThreadLocal
893/// := /*empty*/
894/// := 'thread_local'
895/// := 'thread_local' '(' tlsmodel ')'
896bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
897 TLM = GlobalVariable::NotThreadLocal;
898 if (!EatIfPresent(lltok::kw_thread_local))
899 return false;
900
901 TLM = GlobalVariable::GeneralDynamicTLSModel;
902 if (Lex.getKind() == lltok::lparen) {
903 Lex.Lex();
904 return ParseTLSModel(TLM) ||
905 ParseToken(lltok::rparen, "expected ')' after thread local model");
906 }
907 return false;
908}
Chris Lattnerdf986172009-01-02 07:01:27 +0000909
910/// ParseOptionalAddrSpace
911/// := /*empty*/
912/// := 'addrspace' '(' uint32 ')'
913bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
914 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000915 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000916 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000917 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000918 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000919 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000920}
Chris Lattnerdf986172009-01-02 07:01:27 +0000921
Bill Wendlinge01b81b2012-12-04 23:40:58 +0000922/// ParseOptionalFuncAttrs - Parse a potentially empty list of function attributes.
923bool LLParser::ParseOptionalFuncAttrs(AttrBuilder &B) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000924 bool HaveError = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925
Bill Wendlingf385f4c2012-10-08 23:27:46 +0000926 B.clear();
927
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 while (1) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000929 lltok::Kind Token = Lex.getKind();
930 switch (Token) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000931 default: // End of attributes.
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000932 return HaveError;
Charles Davis1e063d12010-02-12 00:31:15 +0000933 case lltok::kw_alignstack: {
934 unsigned Alignment;
935 if (ParseOptionalStackAlignment(Alignment))
936 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000937 B.addStackAlignmentAttr(Alignment);
Charles Davis1e063d12010-02-12 00:31:15 +0000938 continue;
939 }
Bill Wendlinge01b81b2012-12-04 23:40:58 +0000940 case lltok::kw_align: {
941 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
942 // 2".
943 unsigned Alignment;
944 if (ParseOptionalAlignment(Alignment))
945 return true;
946 B.addAlignmentAttr(Alignment);
947 continue;
948 }
Bill Wendling034b94b2012-12-19 07:18:57 +0000949 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
950 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
951 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
952 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
953 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
954 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
955 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
956 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
957 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
958 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
959 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
960 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
961 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
962 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
963 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
964 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
965 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
Bill Wendling114baee2013-01-23 06:41:41 +0000966 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
Bill Wendling034b94b2012-12-19 07:18:57 +0000967 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
James Molloy67ae1352012-12-20 16:04:27 +0000968 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
Charles Davis1e063d12010-02-12 00:31:15 +0000969
Bill Wendlinge01b81b2012-12-04 23:40:58 +0000970 // Error handling.
971 case lltok::kw_zeroext:
972 case lltok::kw_signext:
973 case lltok::kw_inreg:
974 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on a function");
975 break;
976 case lltok::kw_sret: case lltok::kw_noalias:
977 case lltok::kw_nocapture: case lltok::kw_byval:
978 case lltok::kw_nest:
979 HaveError |=
980 Error(Lex.getLoc(), "invalid use of parameter-only attribute on a function");
981 break;
982 }
983
984 Lex.Lex();
985 }
986}
987
988/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
989bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
990 bool HaveError = false;
991
992 B.clear();
993
994 while (1) {
995 lltok::Kind Token = Lex.getKind();
996 switch (Token) {
997 default: // End of attributes.
998 return HaveError;
Chris Lattnerdf986172009-01-02 07:01:27 +0000999 case lltok::kw_align: {
1000 unsigned Alignment;
1001 if (ParseOptionalAlignment(Alignment))
1002 return true;
Bill Wendling03272442012-10-08 22:20:14 +00001003 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001004 continue;
1005 }
Bill Wendling034b94b2012-12-19 07:18:57 +00001006 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1007 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1008 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1009 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1010 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1011 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1012 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1013 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davis1e063d12010-02-12 00:31:15 +00001014
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001015 case lltok::kw_noreturn: case lltok::kw_nounwind:
1016 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1017 case lltok::kw_noinline: case lltok::kw_readnone:
1018 case lltok::kw_readonly: case lltok::kw_inlinehint:
1019 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1020 case lltok::kw_ssp: case lltok::kw_sspreq:
1021 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1022 case lltok::kw_naked: case lltok::kw_nonlazybind:
1023 case lltok::kw_address_safety: case lltok::kw_minsize:
1024 case lltok::kw_alignstack:
1025 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1026 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001027 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001028
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001029 Lex.Lex();
1030 }
1031}
1032
1033/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1034bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1035 bool HaveError = false;
1036
1037 B.clear();
1038
1039 while (1) {
1040 lltok::Kind Token = Lex.getKind();
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001041 switch (Token) {
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001042 default: // End of attributes.
1043 return HaveError;
Bill Wendling034b94b2012-12-19 07:18:57 +00001044 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1045 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1046 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1047 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001048
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001049 // Error handling.
1050 case lltok::kw_sret: case lltok::kw_nocapture:
1051 case lltok::kw_byval: case lltok::kw_nest:
1052 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001053 break;
James Molloy67ae1352012-12-20 16:04:27 +00001054
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001055 case lltok::kw_noreturn: case lltok::kw_nounwind:
1056 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1057 case lltok::kw_noinline: case lltok::kw_readnone:
1058 case lltok::kw_readonly: case lltok::kw_inlinehint:
1059 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1060 case lltok::kw_ssp: case lltok::kw_sspreq:
Bill Wendling114baee2013-01-23 06:41:41 +00001061 case lltok::kw_sspstrong: case lltok::kw_noimplicitfloat:
1062 case lltok::kw_noredzone: case lltok::kw_naked:
1063 case lltok::kw_nonlazybind: case lltok::kw_address_safety:
1064 case lltok::kw_minsize: case lltok::kw_alignstack:
1065 case lltok::kw_align: case lltok::kw_noduplicate:
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001066 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001067 break;
1068 }
1069
Chris Lattnerdf986172009-01-02 07:01:27 +00001070 Lex.Lex();
1071 }
1072}
1073
1074/// ParseOptionalLinkage
1075/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001076/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001077/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001078/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001079/// ::= 'internal'
1080/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001081/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001082/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001083/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001084/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001085/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001086/// ::= 'appending'
1087/// ::= 'dllexport'
1088/// ::= 'common'
1089/// ::= 'dllimport'
1090/// ::= 'extern_weak'
1091/// ::= 'external'
1092bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1093 HasLinkage = false;
1094 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001095 default: Res=GlobalValue::ExternalLinkage; return false;
1096 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1097 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001098 case lltok::kw_linker_private_weak:
1099 Res = GlobalValue::LinkerPrivateWeakLinkage;
1100 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001101 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1102 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1103 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1104 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1105 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001106 case lltok::kw_linkonce_odr_auto_hide:
1107 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1108 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1109 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001110 case lltok::kw_available_externally:
1111 Res = GlobalValue::AvailableExternallyLinkage;
1112 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001113 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1114 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1115 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1116 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1117 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1118 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001119 }
1120 Lex.Lex();
1121 HasLinkage = true;
1122 return false;
1123}
1124
1125/// ParseOptionalVisibility
1126/// ::= /*empty*/
1127/// ::= 'default'
1128/// ::= 'hidden'
1129/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001130///
Chris Lattnerdf986172009-01-02 07:01:27 +00001131bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1132 switch (Lex.getKind()) {
1133 default: Res = GlobalValue::DefaultVisibility; return false;
1134 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1135 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1136 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1137 }
1138 Lex.Lex();
1139 return false;
1140}
1141
1142/// ParseOptionalCallingConv
1143/// ::= /*empty*/
1144/// ::= 'ccc'
1145/// ::= 'fastcc'
Elena Demikhovsky35752222012-10-24 14:46:16 +00001146/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001147/// ::= 'coldcc'
1148/// ::= 'x86_stdcallcc'
1149/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001150/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001151/// ::= 'arm_apcscc'
1152/// ::= 'arm_aapcscc'
1153/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001154/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001155/// ::= 'ptx_kernel'
1156/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001157/// ::= 'spir_func'
1158/// ::= 'spir_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001159/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001160///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001161bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 switch (Lex.getKind()) {
1163 default: CC = CallingConv::C; return false;
1164 case lltok::kw_ccc: CC = CallingConv::C; break;
1165 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1166 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1167 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1168 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001169 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001170 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1171 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1172 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001173 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001174 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1175 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001176 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1177 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001178 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001179 case lltok::kw_cc: {
1180 unsigned ArbitraryCC;
1181 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001182 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001183 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001184 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1185 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001186 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001187 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001188
Chris Lattnerdf986172009-01-02 07:01:27 +00001189 Lex.Lex();
1190 return false;
1191}
1192
Chris Lattnerb8c46862009-12-30 05:31:19 +00001193/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001194/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001195bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1196 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001197 do {
1198 if (Lex.getKind() != lltok::MetadataVar)
1199 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001200
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001201 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001202 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001203 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001204
Chris Lattner442ffa12009-12-29 21:53:55 +00001205 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001206 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001207
1208 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001209 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001210
Dan Gohman68261142010-08-24 14:35:45 +00001211 // This code is similar to that of ParseMetadataValue, however it needs to
1212 // have special-case code for a forward reference; see the comments on
1213 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1214 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001215 if (Lex.getKind() == lltok::lbrace) {
1216 ValID ID;
1217 if (ParseMetadataListValue(ID, PFS))
1218 return true;
1219 assert(ID.Kind == ValID::t_MDNode);
1220 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001221 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001222 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001223 if (ParseMDNodeID(Node, NodeID))
1224 return true;
1225 if (Node) {
1226 // If we got the node, add it to the instruction.
1227 Inst->setMetadata(MDK, Node);
1228 } else {
1229 MDRef R = { Loc, MDK, NodeID };
1230 // Otherwise, remember that this should be resolved later.
1231 ForwardRefInstMetadata[Inst].push_back(R);
1232 }
Chris Lattner449c3102010-04-01 05:14:45 +00001233 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001234
1235 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001236 } while (EatIfPresent(lltok::comma));
1237 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001238}
1239
Chris Lattnerdf986172009-01-02 07:01:27 +00001240/// ParseOptionalAlignment
1241/// ::= /* empty */
1242/// ::= 'align' 4
1243bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1244 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001245 if (!EatIfPresent(lltok::kw_align))
1246 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001247 LocTy AlignLoc = Lex.getLoc();
1248 if (ParseUInt32(Alignment)) return true;
1249 if (!isPowerOf2_32(Alignment))
1250 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001251 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001252 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001253 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001254}
1255
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001256/// ParseOptionalCommaAlign
Michael Ilseman407a6162012-11-15 22:34:00 +00001257/// ::=
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001258/// ::= ',' align 4
1259///
1260/// This returns with AteExtraComma set to true if it ate an excess comma at the
1261/// end.
1262bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1263 bool &AteExtraComma) {
1264 AteExtraComma = false;
1265 while (EatIfPresent(lltok::comma)) {
1266 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001267 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001268 AteExtraComma = true;
1269 return false;
1270 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001271
Chris Lattner093eed12010-04-23 00:50:50 +00001272 if (Lex.getKind() != lltok::kw_align)
1273 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001274
Chris Lattner093eed12010-04-23 00:50:50 +00001275 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001276 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Devang Patelf633a062009-09-17 23:04:48 +00001278 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001279}
1280
Eli Friedman47f35132011-07-25 23:16:38 +00001281/// ParseScopeAndOrdering
1282/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1283/// else: ::=
1284///
1285/// This sets Scope and Ordering to the parsed values.
1286bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1287 AtomicOrdering &Ordering) {
1288 if (!isAtomic)
1289 return false;
1290
1291 Scope = CrossThread;
1292 if (EatIfPresent(lltok::kw_singlethread))
1293 Scope = SingleThread;
1294 switch (Lex.getKind()) {
1295 default: return TokError("Expected ordering on atomic instruction");
1296 case lltok::kw_unordered: Ordering = Unordered; break;
1297 case lltok::kw_monotonic: Ordering = Monotonic; break;
1298 case lltok::kw_acquire: Ordering = Acquire; break;
1299 case lltok::kw_release: Ordering = Release; break;
1300 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1301 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1302 }
1303 Lex.Lex();
1304 return false;
1305}
1306
Charles Davis1e063d12010-02-12 00:31:15 +00001307/// ParseOptionalStackAlignment
1308/// ::= /* empty */
1309/// ::= 'alignstack' '(' 4 ')'
1310bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1311 Alignment = 0;
1312 if (!EatIfPresent(lltok::kw_alignstack))
1313 return false;
1314 LocTy ParenLoc = Lex.getLoc();
1315 if (!EatIfPresent(lltok::lparen))
1316 return Error(ParenLoc, "expected '('");
1317 LocTy AlignLoc = Lex.getLoc();
1318 if (ParseUInt32(Alignment)) return true;
1319 ParenLoc = Lex.getLoc();
1320 if (!EatIfPresent(lltok::rparen))
1321 return Error(ParenLoc, "expected ')'");
1322 if (!isPowerOf2_32(Alignment))
1323 return Error(AlignLoc, "stack alignment is not a power of two");
1324 return false;
1325}
Devang Patelf633a062009-09-17 23:04:48 +00001326
Chris Lattner628c13a2009-12-30 05:14:00 +00001327/// ParseIndexList - This parses the index list for an insert/extractvalue
1328/// instruction. This sets AteExtraComma in the case where we eat an extra
1329/// comma at the end of the line and find that it is followed by metadata.
1330/// Clients that don't allow metadata can call the version of this function that
1331/// only takes one argument.
1332///
Chris Lattnerdf986172009-01-02 07:01:27 +00001333/// ParseIndexList
1334/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001335///
1336bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1337 bool &AteExtraComma) {
1338 AteExtraComma = false;
Michael Ilseman407a6162012-11-15 22:34:00 +00001339
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 if (Lex.getKind() != lltok::comma)
1341 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001342
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001343 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001344 if (Lex.getKind() == lltok::MetadataVar) {
1345 AteExtraComma = true;
1346 return false;
1347 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001348 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001349 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 Indices.push_back(Idx);
1351 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001352
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 return false;
1354}
1355
1356//===----------------------------------------------------------------------===//
1357// Type Parsing.
1358//===----------------------------------------------------------------------===//
1359
Chris Lattner1afcace2011-07-09 17:41:24 +00001360/// ParseType - Parse a type.
1361bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1362 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 switch (Lex.getKind()) {
1364 default:
1365 return TokError("expected type");
1366 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001367 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001368 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001369 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001370 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001372 // Type ::= StructType
1373 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 return true;
1375 break;
1376 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001377 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001378 Lex.Lex(); // eat the lsquare.
1379 if (ParseArrayVectorType(Result, false))
1380 return true;
1381 break;
1382 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001383 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001384 Lex.Lex();
1385 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001386 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001387 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001389 } else if (ParseArrayVectorType(Result, true))
1390 return true;
1391 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001392 case lltok::LocalVar: {
1393 // Type ::= %foo
1394 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001395
Chris Lattner1afcace2011-07-09 17:41:24 +00001396 // If the type hasn't been defined yet, create a forward definition and
1397 // remember where that forward def'n was seen (in case it never is defined).
1398 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001399 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001400 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001402 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001403 Lex.Lex();
1404 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001406
Chris Lattner1afcace2011-07-09 17:41:24 +00001407 case lltok::LocalVarID: {
1408 // Type ::= %4
1409 if (Lex.getUIntVal() >= NumberedTypes.size())
1410 NumberedTypes.resize(Lex.getUIntVal()+1);
1411 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001412
Chris Lattner1afcace2011-07-09 17:41:24 +00001413 // If the type hasn't been defined yet, create a forward definition and
1414 // remember where that forward def'n was seen (in case it never is defined).
1415 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001416 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001417 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001419 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 Lex.Lex();
1421 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001422 }
1423 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001424
1425 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 while (1) {
1427 switch (Lex.getKind()) {
1428 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001429 default:
1430 if (!AllowVoid && Result->isVoidTy())
1431 return Error(TypeLoc, "void type only allowed for function results");
1432 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001433
Chris Lattner1afcace2011-07-09 17:41:24 +00001434 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001436 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001437 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001438 if (Result->isVoidTy())
1439 return TokError("pointers to void are invalid - use i8* instead");
1440 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001441 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001442 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001443 Lex.Lex();
1444 break;
1445
Chris Lattner1afcace2011-07-09 17:41:24 +00001446 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001448 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001449 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001450 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001451 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001452 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001453 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 unsigned AddrSpace;
1455 if (ParseOptionalAddrSpace(AddrSpace) ||
1456 ParseToken(lltok::star, "expected '*' in address space"))
1457 return true;
1458
Chris Lattner1afcace2011-07-09 17:41:24 +00001459 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 break;
1461 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001462
Chris Lattnerdf986172009-01-02 07:01:27 +00001463 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1464 case lltok::lparen:
1465 if (ParseFunctionType(Result))
1466 return true;
1467 break;
1468 }
1469 }
1470}
1471
1472/// ParseParameterList
1473/// ::= '(' ')'
1474/// ::= '(' Arg (',' Arg)* ')'
1475/// Arg
1476/// ::= Type OptionalAttributes Value OptionalAttributes
1477bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1478 PerFunctionState &PFS) {
1479 if (ParseToken(lltok::lparen, "expected '(' in call"))
1480 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001481
Bill Wendling73dee182013-01-31 00:29:54 +00001482 unsigned AttrIndex = 1;
Chris Lattnerdf986172009-01-02 07:01:27 +00001483 while (Lex.getKind() != lltok::rparen) {
1484 // If this isn't the first argument, we need a comma.
1485 if (!ArgList.empty() &&
1486 ParseToken(lltok::comma, "expected ',' in argument list"))
1487 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001488
Chris Lattnerdf986172009-01-02 07:01:27 +00001489 // Parse the argument.
1490 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001491 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001492 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001493 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001494 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001495 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001496
Chris Lattner287881d2009-12-30 02:11:14 +00001497 // Otherwise, handle normal operands.
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001498 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001499 return true;
Bill Wendling73dee182013-01-31 00:29:54 +00001500 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1501 AttrIndex++,
1502 ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 }
1504
1505 Lex.Lex(); // Lex the ')'.
1506 return false;
1507}
1508
1509
1510
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001511/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001512/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001513/// ::= '(' ArgTypeListI ')'
1514/// ArgTypeListI
1515/// ::= /*empty*/
1516/// ::= '...'
1517/// ::= ArgTypeList ',' '...'
1518/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001519///
Chris Lattner1afcace2011-07-09 17:41:24 +00001520bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1521 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 isVarArg = false;
1523 assert(Lex.getKind() == lltok::lparen);
1524 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 if (Lex.getKind() == lltok::rparen) {
1527 // empty
1528 } else if (Lex.getKind() == lltok::dotdotdot) {
1529 isVarArg = true;
1530 Lex.Lex();
1531 } else {
1532 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001533 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001534 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattner1afcace2011-07-09 17:41:24 +00001537 if (ParseType(ArgTy) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001538 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001539
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001540 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001541 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001542
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001543 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 Name = Lex.getStrVal();
1545 Lex.Lex();
1546 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001547
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001548 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Bill Wendling73dee182013-01-31 00:29:54 +00001551 unsigned AttrIndex = 1;
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001552 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendling73dee182013-01-31 00:29:54 +00001553 AttributeSet::get(ArgTy->getContext(),
1554 AttrIndex++, Attrs), Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001555
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001556 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001558 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 break;
1561 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattnerdf986172009-01-02 07:01:27 +00001563 // Otherwise must be an argument type.
1564 TypeLoc = Lex.getLoc();
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001565 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001566
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001567 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001568 return Error(TypeLoc, "argument can not have void type");
1569
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001570 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001571 Name = Lex.getStrVal();
1572 Lex.Lex();
1573 } else {
1574 Name = "";
1575 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001576
Chris Lattner1afcace2011-07-09 17:41:24 +00001577 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001578 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001580 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendling73dee182013-01-31 00:29:54 +00001581 AttributeSet::get(ArgTy->getContext(),
1582 AttrIndex++, Attrs),
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001583 Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00001584 }
1585 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001587 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001588}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001589
Chris Lattnerdf986172009-01-02 07:01:27 +00001590/// ParseFunctionType
1591/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001592bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001593 assert(Lex.getKind() == lltok::lparen);
1594
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001595 if (!FunctionType::isValidReturnType(Result))
1596 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattner1afcace2011-07-09 17:41:24 +00001598 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001600 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Chris Lattnerdf986172009-01-02 07:01:27 +00001603 // Reject names on the arguments lists.
1604 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1605 if (!ArgList[i].Name.empty())
1606 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendling73dee182013-01-31 00:29:54 +00001607 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattnera16546a2011-06-17 17:37:13 +00001608 return Error(ArgList[i].Loc,
1609 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611
Jay Foad5fdd6c82011-07-12 14:06:48 +00001612 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001613 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001614 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001615
Chris Lattner1afcace2011-07-09 17:41:24 +00001616 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001617 return false;
1618}
1619
Chris Lattner1afcace2011-07-09 17:41:24 +00001620/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1621/// other structs.
1622bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1623 SmallVector<Type*, 8> Elts;
1624 if (ParseStructBody(Elts)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001625
Chris Lattner1afcace2011-07-09 17:41:24 +00001626 Result = StructType::get(Context, Elts, Packed);
1627 return false;
1628}
1629
1630/// ParseStructDefinition - Parse a struct in a 'type' definition.
1631bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1632 std::pair<Type*, LocTy> &Entry,
1633 Type *&ResultTy) {
1634 // If the type was already defined, diagnose the redefinition.
1635 if (Entry.first && !Entry.second.isValid())
1636 return Error(TypeLoc, "redefinition of type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001637
Chris Lattner1afcace2011-07-09 17:41:24 +00001638 // If we have opaque, just return without filling in the definition for the
1639 // struct. This counts as a definition as far as the .ll file goes.
1640 if (EatIfPresent(lltok::kw_opaque)) {
1641 // This type is being defined, so clear the location to indicate this.
1642 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001643
Chris Lattner1afcace2011-07-09 17:41:24 +00001644 // If this type number has never been uttered, create it.
1645 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001646 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001647 ResultTy = Entry.first;
1648 return false;
1649 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001650
Chris Lattner1afcace2011-07-09 17:41:24 +00001651 // If the type starts with '<', then it is either a packed struct or a vector.
1652 bool isPacked = EatIfPresent(lltok::less);
1653
1654 // If we don't have a struct, then we have a random type alias, which we
1655 // accept for compatibility with old files. These types are not allowed to be
1656 // forward referenced and not allowed to be recursive.
1657 if (Lex.getKind() != lltok::lbrace) {
1658 if (Entry.first)
1659 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001660
Chris Lattner1afcace2011-07-09 17:41:24 +00001661 ResultTy = 0;
1662 if (isPacked)
1663 return ParseArrayVectorType(ResultTy, true);
1664 return ParseType(ResultTy);
1665 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001666
Chris Lattner1afcace2011-07-09 17:41:24 +00001667 // This type is being defined, so clear the location to indicate this.
1668 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001669
Chris Lattner1afcace2011-07-09 17:41:24 +00001670 // If this type number has never been uttered, create it.
1671 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001672 Entry.first = StructType::create(Context, Name);
Michael Ilseman407a6162012-11-15 22:34:00 +00001673
Chris Lattner1afcace2011-07-09 17:41:24 +00001674 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman407a6162012-11-15 22:34:00 +00001675
Chris Lattner1afcace2011-07-09 17:41:24 +00001676 SmallVector<Type*, 8> Body;
1677 if (ParseStructBody(Body) ||
1678 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1679 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001680
Chris Lattner1afcace2011-07-09 17:41:24 +00001681 STy->setBody(Body, isPacked);
1682 ResultTy = STy;
1683 return false;
1684}
1685
1686
Chris Lattnerdf986172009-01-02 07:01:27 +00001687/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001688/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001689/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001690/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001691/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001692/// ::= '<' '{' Type (',' Type)* '}' '>'
1693bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 assert(Lex.getKind() == lltok::lbrace);
1695 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattner1afcace2011-07-09 17:41:24 +00001697 // Handle the empty struct.
1698 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001700
Chris Lattnera9a9e072009-03-09 04:49:14 +00001701 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001702 Type *Ty = 0;
1703 if (ParseType(Ty)) return true;
1704 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattner1afcace2011-07-09 17:41:24 +00001706 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001707 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001709 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001710 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001711 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712
Chris Lattner1afcace2011-07-09 17:41:24 +00001713 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001714 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001715
Chris Lattner1afcace2011-07-09 17:41:24 +00001716 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001718
Chris Lattner1afcace2011-07-09 17:41:24 +00001719 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001720}
1721
1722/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1723/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001724/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001725/// ::= '[' APSINTVAL 'x' Types ']'
1726/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001727bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001728 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1729 Lex.getAPSIntVal().getBitWidth() > 64)
1730 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001731
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 LocTy SizeLoc = Lex.getLoc();
1733 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001734 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001735
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001736 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1737 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001738
1739 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001740 Type *EltTy = 0;
1741 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001742
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001743 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1744 "expected end of sequential type"))
1745 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001746
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001748 if (Size == 0)
1749 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001750 if ((unsigned)Size != Size)
1751 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001752 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00001753 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001754 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001755 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001756 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001758 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 }
1760 return false;
1761}
1762
1763//===----------------------------------------------------------------------===//
1764// Function Semantic Analysis.
1765//===----------------------------------------------------------------------===//
1766
Chris Lattner09d9ef42009-10-28 03:39:23 +00001767LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1768 int functionNumber)
1769 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001770
1771 // Insert unnamed arguments into the NumberedVals list.
1772 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1773 AI != E; ++AI)
1774 if (!AI->hasName())
1775 NumberedVals.push_back(AI);
1776}
1777
1778LLParser::PerFunctionState::~PerFunctionState() {
1779 // If there were any forward referenced non-basicblock values, delete them.
1780 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1781 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1782 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001783 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001784 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 delete I->second.first;
1786 I->second.first = 0;
1787 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001788
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1790 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1791 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001792 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001793 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001794 delete I->second.first;
1795 I->second.first = 0;
1796 }
1797}
1798
Chris Lattner09d9ef42009-10-28 03:39:23 +00001799bool LLParser::PerFunctionState::FinishFunction() {
1800 // Check to see if someone took the address of labels in this block.
1801 if (!P.ForwardRefBlockAddresses.empty()) {
1802 ValID FunctionID;
1803 if (!F.getName().empty()) {
1804 FunctionID.Kind = ValID::t_GlobalName;
1805 FunctionID.StrVal = F.getName();
1806 } else {
1807 FunctionID.Kind = ValID::t_GlobalID;
1808 FunctionID.UIntVal = FunctionNumber;
1809 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001810
Chris Lattner09d9ef42009-10-28 03:39:23 +00001811 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1812 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1813 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1814 // Resolve all these references.
1815 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1816 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001817
Chris Lattner09d9ef42009-10-28 03:39:23 +00001818 P.ForwardRefBlockAddresses.erase(FRBAI);
1819 }
1820 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001821
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 if (!ForwardRefVals.empty())
1823 return P.Error(ForwardRefVals.begin()->second.second,
1824 "use of undefined value '%" + ForwardRefVals.begin()->first +
1825 "'");
1826 if (!ForwardRefValIDs.empty())
1827 return P.Error(ForwardRefValIDs.begin()->second.second,
1828 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001829 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 return false;
1831}
1832
1833
1834/// GetVal - Get a value with the specified name or ID, creating a
1835/// forward reference record if needed. This can return null if the value
1836/// exists but does not have the right type.
1837Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001838 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 // Look this name up in the normal function symbol table.
1840 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 // If this is a forward reference for the value, see if we already created a
1843 // forward ref record.
1844 if (Val == 0) {
1845 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1846 I = ForwardRefVals.find(Name);
1847 if (I != ForwardRefVals.end())
1848 Val = I->second.first;
1849 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 // If we have the value in the symbol table or fwd-ref table, return it.
1852 if (Val) {
1853 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001854 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001855 P.Error(Loc, "'%" + Name + "' is not a basic block");
1856 else
1857 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001858 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 return 0;
1860 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001861
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001863 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 P.Error(Loc, "invalid use of a non-first-class type");
1865 return 0;
1866 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001867
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 // Otherwise, create a new forward reference for this value and remember it.
1869 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001870 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001871 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 else
1873 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874
Chris Lattnerdf986172009-01-02 07:01:27 +00001875 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1876 return FwdVal;
1877}
1878
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001879Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001880 LocTy Loc) {
1881 // Look this name up in the normal function symbol table.
1882 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001883
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 // If this is a forward reference for the value, see if we already created a
1885 // forward ref record.
1886 if (Val == 0) {
1887 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1888 I = ForwardRefValIDs.find(ID);
1889 if (I != ForwardRefValIDs.end())
1890 Val = I->second.first;
1891 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Chris Lattnerdf986172009-01-02 07:01:27 +00001893 // If we have the value in the symbol table or fwd-ref table, return it.
1894 if (Val) {
1895 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001896 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001897 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001899 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001900 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 return 0;
1902 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001903
Chris Lattner1afcace2011-07-09 17:41:24 +00001904 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001905 P.Error(Loc, "invalid use of a non-first-class type");
1906 return 0;
1907 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 // Otherwise, create a new forward reference for this value and remember it.
1910 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001911 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001912 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 else
1914 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1917 return FwdVal;
1918}
1919
1920/// SetInstName - After an instruction is parsed and inserted into its
1921/// basic block, this installs its name.
1922bool LLParser::PerFunctionState::SetInstName(int NameID,
1923 const std::string &NameStr,
1924 LocTy NameLoc, Instruction *Inst) {
1925 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001926 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001927 if (NameID != -1 || !NameStr.empty())
1928 return P.Error(NameLoc, "instructions returning void cannot have a name");
1929 return false;
1930 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001931
Chris Lattnerdf986172009-01-02 07:01:27 +00001932 // If this was a numbered instruction, verify that the instruction is the
1933 // expected value and resolve any forward references.
1934 if (NameStr.empty()) {
1935 // If neither a name nor an ID was specified, just use the next ID.
1936 if (NameID == -1)
1937 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001938
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 if (unsigned(NameID) != NumberedVals.size())
1940 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001941 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001942
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1944 ForwardRefValIDs.find(NameID);
1945 if (FI != ForwardRefValIDs.end()) {
1946 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001948 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001949 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001950 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 ForwardRefValIDs.erase(FI);
1952 }
1953
1954 NumberedVals.push_back(Inst);
1955 return false;
1956 }
1957
1958 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1959 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1960 FI = ForwardRefVals.find(NameStr);
1961 if (FI != ForwardRefVals.end()) {
1962 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001964 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001965 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001966 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001967 ForwardRefVals.erase(FI);
1968 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001969
Chris Lattnerdf986172009-01-02 07:01:27 +00001970 // Set the name on the instruction.
1971 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001972
Benjamin Krameraf812352010-10-16 11:28:23 +00001973 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 NameStr + "'");
1976 return false;
1977}
1978
1979/// GetBB - Get a basic block with the specified name or ID, creating a
1980/// forward reference record if needed.
1981BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1982 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001983 return cast_or_null<BasicBlock>(GetVal(Name,
1984 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001985}
1986
1987BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001988 return cast_or_null<BasicBlock>(GetVal(ID,
1989 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001990}
1991
1992/// DefineBB - Define the specified basic block, which is either named or
1993/// unnamed. If there is an error, this returns null otherwise it returns
1994/// the block being defined.
1995BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1996 LocTy Loc) {
1997 BasicBlock *BB;
1998 if (Name.empty())
1999 BB = GetBB(NumberedVals.size(), Loc);
2000 else
2001 BB = GetBB(Name, Loc);
2002 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002003
Chris Lattnerdf986172009-01-02 07:01:27 +00002004 // Move the block to the end of the function. Forward ref'd blocks are
2005 // inserted wherever they happen to be referenced.
2006 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002007
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 // Remove the block from forward ref sets.
2009 if (Name.empty()) {
2010 ForwardRefValIDs.erase(NumberedVals.size());
2011 NumberedVals.push_back(BB);
2012 } else {
2013 // BB forward references are already in the function symbol table.
2014 ForwardRefVals.erase(Name);
2015 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 return BB;
2018}
2019
2020//===----------------------------------------------------------------------===//
2021// Constants.
2022//===----------------------------------------------------------------------===//
2023
2024/// ParseValID - Parse an abstract value that doesn't necessarily have a
2025/// type implied. For example, if we parse "4" we don't know what integer type
2026/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002027/// sanity. PFS is used to convert function-local operands of metadata (since
2028/// metadata operands are not just parsed here but also converted to values).
2029/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002030bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 ID.Loc = Lex.getLoc();
2032 switch (Lex.getKind()) {
2033 default: return TokError("expected value token");
2034 case lltok::GlobalID: // @42
2035 ID.UIntVal = Lex.getUIntVal();
2036 ID.Kind = ValID::t_GlobalID;
2037 break;
2038 case lltok::GlobalVar: // @foo
2039 ID.StrVal = Lex.getStrVal();
2040 ID.Kind = ValID::t_GlobalName;
2041 break;
2042 case lltok::LocalVarID: // %42
2043 ID.UIntVal = Lex.getUIntVal();
2044 ID.Kind = ValID::t_LocalID;
2045 break;
2046 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00002047 ID.StrVal = Lex.getStrVal();
2048 ID.Kind = ValID::t_LocalName;
2049 break;
Dan Gohman83448032010-07-14 18:26:50 +00002050 case lltok::exclaim: // !42, !{...}, or !"foo"
2051 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002053 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002054 ID.Kind = ValID::t_APSInt;
2055 break;
2056 case lltok::APFloat:
2057 ID.APFloatVal = Lex.getAPFloatVal();
2058 ID.Kind = ValID::t_APFloat;
2059 break;
2060 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002061 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002062 ID.Kind = ValID::t_Constant;
2063 break;
2064 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002065 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 ID.Kind = ValID::t_Constant;
2067 break;
2068 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2069 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2070 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002071
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 case lltok::lbrace: {
2073 // ValID ::= '{' ConstVector '}'
2074 Lex.Lex();
2075 SmallVector<Constant*, 16> Elts;
2076 if (ParseGlobalValueVector(Elts) ||
2077 ParseToken(lltok::rbrace, "expected end of struct constant"))
2078 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002079
Chris Lattner1afcace2011-07-09 17:41:24 +00002080 ID.ConstantStructElts = new Constant*[Elts.size()];
2081 ID.UIntVal = Elts.size();
2082 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2083 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002084 return false;
2085 }
2086 case lltok::less: {
2087 // ValID ::= '<' ConstVector '>' --> Vector.
2088 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2089 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002090 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002091
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 SmallVector<Constant*, 16> Elts;
2093 LocTy FirstEltLoc = Lex.getLoc();
2094 if (ParseGlobalValueVector(Elts) ||
2095 (isPackedStruct &&
2096 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2097 ParseToken(lltok::greater, "expected end of constant"))
2098 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002101 ID.ConstantStructElts = new Constant*[Elts.size()];
2102 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2103 ID.UIntVal = Elts.size();
2104 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 return false;
2106 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 if (Elts.empty())
2109 return Error(ID.Loc, "constant vector must not be empty");
2110
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002111 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002112 !Elts[0]->getType()->isFloatingPointTy() &&
2113 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002114 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002115 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002116
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 // Verify that all the vector elements have the same type.
2118 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2119 if (Elts[i]->getType() != Elts[0]->getType())
2120 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002121 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002122 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002123
Chris Lattner2ca5c862011-02-15 00:14:00 +00002124 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 ID.Kind = ValID::t_Constant;
2126 return false;
2127 }
2128 case lltok::lsquare: { // Array Constant
2129 Lex.Lex();
2130 SmallVector<Constant*, 16> Elts;
2131 LocTy FirstEltLoc = Lex.getLoc();
2132 if (ParseGlobalValueVector(Elts) ||
2133 ParseToken(lltok::rsquare, "expected end of array constant"))
2134 return true;
2135
2136 // Handle empty element.
2137 if (Elts.empty()) {
2138 // Use undef instead of an array because it's inconvenient to determine
2139 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002140 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 return false;
2142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002146 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002147
Owen Andersondebcb012009-07-29 22:17:13 +00002148 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002149
Chris Lattnerdf986172009-01-02 07:01:27 +00002150 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002151 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 if (Elts[i]->getType() != Elts[0]->getType())
2153 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002154 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002155 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002157
Jay Foad26701082011-06-22 09:24:39 +00002158 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 ID.Kind = ValID::t_Constant;
2160 return false;
2161 }
2162 case lltok::kw_c: // c "foo"
2163 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002164 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2165 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2167 ID.Kind = ValID::t_Constant;
2168 return false;
2169
2170 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002171 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002172 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 Lex.Lex();
2174 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002175 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002176 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002177 ParseStringConstant(ID.StrVal) ||
2178 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 ParseToken(lltok::StringConstant, "expected constraint string"))
2180 return true;
2181 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002182 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002183 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 ID.Kind = ValID::t_InlineAsm;
2185 return false;
2186 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002187
Chris Lattner09d9ef42009-10-28 03:39:23 +00002188 case lltok::kw_blockaddress: {
2189 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2190 Lex.Lex();
2191
2192 ValID Fn, Label;
2193 LocTy FnLoc, LabelLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002194
Chris Lattner09d9ef42009-10-28 03:39:23 +00002195 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2196 ParseValID(Fn) ||
2197 ParseToken(lltok::comma, "expected comma in block address expression")||
2198 ParseValID(Label) ||
2199 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2200 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002201
Chris Lattner09d9ef42009-10-28 03:39:23 +00002202 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2203 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002204 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002205 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +00002206
Chris Lattner09d9ef42009-10-28 03:39:23 +00002207 // Make a global variable as a placeholder for this reference.
2208 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2209 false, GlobalValue::InternalLinkage,
2210 0, "");
2211 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2212 ID.ConstantVal = FwdRef;
2213 ID.Kind = ValID::t_Constant;
2214 return false;
2215 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002216
Chris Lattnerdf986172009-01-02 07:01:27 +00002217 case lltok::kw_trunc:
2218 case lltok::kw_zext:
2219 case lltok::kw_sext:
2220 case lltok::kw_fptrunc:
2221 case lltok::kw_fpext:
2222 case lltok::kw_bitcast:
2223 case lltok::kw_uitofp:
2224 case lltok::kw_sitofp:
2225 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002226 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002228 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002230 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002231 Constant *SrcVal;
2232 Lex.Lex();
2233 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2234 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002235 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 ParseType(DestTy) ||
2237 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2238 return true;
2239 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2240 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002241 getTypeString(SrcVal->getType()) + "' to '" +
2242 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002243 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002244 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 ID.Kind = ValID::t_Constant;
2246 return false;
2247 }
2248 case lltok::kw_extractvalue: {
2249 Lex.Lex();
2250 Constant *Val;
2251 SmallVector<unsigned, 4> Indices;
2252 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2253 ParseGlobalTypeAndValue(Val) ||
2254 ParseIndexList(Indices) ||
2255 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2256 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002257
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002258 if (!Val->getType()->isAggregateType())
2259 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002260 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002261 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002262 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002263 ID.Kind = ValID::t_Constant;
2264 return false;
2265 }
2266 case lltok::kw_insertvalue: {
2267 Lex.Lex();
2268 Constant *Val0, *Val1;
2269 SmallVector<unsigned, 4> Indices;
2270 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2271 ParseGlobalTypeAndValue(Val0) ||
2272 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2273 ParseGlobalTypeAndValue(Val1) ||
2274 ParseIndexList(Indices) ||
2275 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2276 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002277 if (!Val0->getType()->isAggregateType())
2278 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002279 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002281 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002282 ID.Kind = ValID::t_Constant;
2283 return false;
2284 }
2285 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002286 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 unsigned PredVal, Opc = Lex.getUIntVal();
2288 Constant *Val0, *Val1;
2289 Lex.Lex();
2290 if (ParseCmpPredicate(PredVal, Opc) ||
2291 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2292 ParseGlobalTypeAndValue(Val0) ||
2293 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2294 ParseGlobalTypeAndValue(Val1) ||
2295 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2296 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002297
Chris Lattnerdf986172009-01-02 07:01:27 +00002298 if (Val0->getType() != Val1->getType())
2299 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002300
Chris Lattnerdf986172009-01-02 07:01:27 +00002301 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002302
Chris Lattnerdf986172009-01-02 07:01:27 +00002303 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002304 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002305 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002306 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002307 } else {
2308 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002309 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002310 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002311 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002312 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002313 }
2314 ID.Kind = ValID::t_Constant;
2315 return false;
2316 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002317
Chris Lattnerdf986172009-01-02 07:01:27 +00002318 // Binary Operators.
2319 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002320 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002321 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002322 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002324 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002325 case lltok::kw_udiv:
2326 case lltok::kw_sdiv:
2327 case lltok::kw_fdiv:
2328 case lltok::kw_urem:
2329 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002330 case lltok::kw_frem:
2331 case lltok::kw_shl:
2332 case lltok::kw_lshr:
2333 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002334 bool NUW = false;
2335 bool NSW = false;
2336 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 unsigned Opc = Lex.getUIntVal();
2338 Constant *Val0, *Val1;
2339 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002340 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002341 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2342 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002343 if (EatIfPresent(lltok::kw_nuw))
2344 NUW = true;
2345 if (EatIfPresent(lltok::kw_nsw)) {
2346 NSW = true;
2347 if (EatIfPresent(lltok::kw_nuw))
2348 NUW = true;
2349 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002350 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2351 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002352 if (EatIfPresent(lltok::kw_exact))
2353 Exact = true;
2354 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002355 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2356 ParseGlobalTypeAndValue(Val0) ||
2357 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2358 ParseGlobalTypeAndValue(Val1) ||
2359 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2360 return true;
2361 if (Val0->getType() != Val1->getType())
2362 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002363 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002364 if (NUW)
2365 return Error(ModifierLoc, "nuw only applies to integer operations");
2366 if (NSW)
2367 return Error(ModifierLoc, "nsw only applies to integer operations");
2368 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002369 // Check that the type is valid for the operator.
2370 switch (Opc) {
2371 case Instruction::Add:
2372 case Instruction::Sub:
2373 case Instruction::Mul:
2374 case Instruction::UDiv:
2375 case Instruction::SDiv:
2376 case Instruction::URem:
2377 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002378 case Instruction::Shl:
2379 case Instruction::AShr:
2380 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002381 if (!Val0->getType()->isIntOrIntVectorTy())
2382 return Error(ID.Loc, "constexpr requires integer operands");
2383 break;
2384 case Instruction::FAdd:
2385 case Instruction::FSub:
2386 case Instruction::FMul:
2387 case Instruction::FDiv:
2388 case Instruction::FRem:
2389 if (!Val0->getType()->isFPOrFPVectorTy())
2390 return Error(ID.Loc, "constexpr requires fp operands");
2391 break;
2392 default: llvm_unreachable("Unknown binary operator!");
2393 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002394 unsigned Flags = 0;
2395 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2396 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002397 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002398 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002399 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 ID.Kind = ValID::t_Constant;
2401 return false;
2402 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002403
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002405 case lltok::kw_and:
2406 case lltok::kw_or:
2407 case lltok::kw_xor: {
2408 unsigned Opc = Lex.getUIntVal();
2409 Constant *Val0, *Val1;
2410 Lex.Lex();
2411 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2412 ParseGlobalTypeAndValue(Val0) ||
2413 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2414 ParseGlobalTypeAndValue(Val1) ||
2415 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2416 return true;
2417 if (Val0->getType() != Val1->getType())
2418 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002419 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002420 return Error(ID.Loc,
2421 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002422 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 ID.Kind = ValID::t_Constant;
2424 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002425 }
2426
Chris Lattnerdf986172009-01-02 07:01:27 +00002427 case lltok::kw_getelementptr:
2428 case lltok::kw_shufflevector:
2429 case lltok::kw_insertelement:
2430 case lltok::kw_extractelement:
2431 case lltok::kw_select: {
2432 unsigned Opc = Lex.getUIntVal();
2433 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002434 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002436 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002437 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2439 ParseGlobalValueVector(Elts) ||
2440 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2441 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002442
Chris Lattnerdf986172009-01-02 07:01:27 +00002443 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002444 if (Elts.size() == 0 ||
2445 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002447
Jay Foaddab3d292011-07-21 14:31:17 +00002448 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002449 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002451 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2452 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 } else if (Opc == Instruction::Select) {
2454 if (Elts.size() != 3)
2455 return Error(ID.Loc, "expected three operands to select");
2456 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2457 Elts[2]))
2458 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002459 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002460 } else if (Opc == Instruction::ShuffleVector) {
2461 if (Elts.size() != 3)
2462 return Error(ID.Loc, "expected three operands to shufflevector");
2463 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2464 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002465 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002466 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002467 } else if (Opc == Instruction::ExtractElement) {
2468 if (Elts.size() != 2)
2469 return Error(ID.Loc, "expected two operands to extractelement");
2470 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2471 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002472 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002473 } else {
2474 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2475 if (Elts.size() != 3)
2476 return Error(ID.Loc, "expected three operands to insertelement");
2477 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2478 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002479 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002480 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002481 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002482
Chris Lattnerdf986172009-01-02 07:01:27 +00002483 ID.Kind = ValID::t_Constant;
2484 return false;
2485 }
2486 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002487
Chris Lattnerdf986172009-01-02 07:01:27 +00002488 Lex.Lex();
2489 return false;
2490}
2491
2492/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002493bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002494 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002495 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002496 Value *V = NULL;
2497 bool Parsed = ParseValID(ID) ||
2498 ConvertValIDToValue(Ty, ID, V, NULL);
2499 if (V && !(C = dyn_cast<Constant>(V)))
2500 return Error(ID.Loc, "global values must be constants");
2501 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002502}
2503
Victor Hernandez92f238d2010-01-11 22:31:58 +00002504bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002505 Type *Ty = 0;
2506 return ParseType(Ty) ||
2507 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002508}
2509
2510/// ParseGlobalValueVector
2511/// ::= /*empty*/
2512/// ::= TypeAndValue (',' TypeAndValue)*
2513bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2514 // Empty list.
2515 if (Lex.getKind() == lltok::rbrace ||
2516 Lex.getKind() == lltok::rsquare ||
2517 Lex.getKind() == lltok::greater ||
2518 Lex.getKind() == lltok::rparen)
2519 return false;
2520
2521 Constant *C;
2522 if (ParseGlobalTypeAndValue(C)) return true;
2523 Elts.push_back(C);
2524
2525 while (EatIfPresent(lltok::comma)) {
2526 if (ParseGlobalTypeAndValue(C)) return true;
2527 Elts.push_back(C);
2528 }
2529
2530 return false;
2531}
2532
Dan Gohman309b3af2010-08-24 02:24:03 +00002533bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2534 assert(Lex.getKind() == lltok::lbrace);
2535 Lex.Lex();
2536
2537 SmallVector<Value*, 16> Elts;
2538 if (ParseMDNodeVector(Elts, PFS) ||
2539 ParseToken(lltok::rbrace, "expected end of metadata node"))
2540 return true;
2541
Jay Foadec9186b2011-04-21 19:59:31 +00002542 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002543 ID.Kind = ValID::t_MDNode;
2544 return false;
2545}
2546
Dan Gohman83448032010-07-14 18:26:50 +00002547/// ParseMetadataValue
2548/// ::= !42
2549/// ::= !{...}
2550/// ::= !"string"
2551bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2552 assert(Lex.getKind() == lltok::exclaim);
2553 Lex.Lex();
2554
2555 // MDNode:
2556 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002557 if (Lex.getKind() == lltok::lbrace)
2558 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002559
2560 // Standalone metadata reference
2561 // !42
2562 if (Lex.getKind() == lltok::APSInt) {
2563 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2564 ID.Kind = ValID::t_MDNode;
2565 return false;
2566 }
2567
2568 // MDString:
2569 // ::= '!' STRINGCONSTANT
2570 if (ParseMDString(ID.MDStringVal)) return true;
2571 ID.Kind = ValID::t_MDString;
2572 return false;
2573}
2574
Victor Hernandez92f238d2010-01-11 22:31:58 +00002575
2576//===----------------------------------------------------------------------===//
2577// Function Parsing.
2578//===----------------------------------------------------------------------===//
2579
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002580bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002581 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002582 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002584
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002587 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2588 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2589 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002591 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2592 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2593 return (V == 0);
2594 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002595 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman407a6162012-11-15 22:34:00 +00002596 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002597 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2598 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2599 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002600 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002601 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002602 return false;
2603 }
2604 case ValID::t_MDNode:
2605 if (!Ty->isMetadataTy())
2606 return Error(ID.Loc, "metadata value must have metadata type");
2607 V = ID.MDNodeVal;
2608 return false;
2609 case ValID::t_MDString:
2610 if (!Ty->isMetadataTy())
2611 return Error(ID.Loc, "metadata value must have metadata type");
2612 V = ID.MDStringVal;
2613 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002614 case ValID::t_GlobalName:
2615 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2616 return V == 0;
2617 case ValID::t_GlobalID:
2618 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2619 return V == 0;
2620 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002621 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002623 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002624 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 return false;
2626 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002627 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002628 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2629 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002630
Dan Gohmance163392011-12-17 00:04:22 +00002631 // The lexer has no type info, so builds all half, float, and double FP
2632 // constants as double. Fix this here. Long double does not need this.
2633 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002635 if (Ty->isHalfTy())
2636 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2637 &Ignored);
2638 else if (Ty->isFloatTy())
2639 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2640 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002641 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002642 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002643
Chris Lattner959873d2009-01-05 18:24:23 +00002644 if (V->getType() != Ty)
2645 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002646 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002647
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 return false;
2649 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002650 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002651 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002652 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002653 return false;
2654 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002655 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002656 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002657 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002658 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002659 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002660 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002661 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002662 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002663 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002664 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002665 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002666 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002667 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002668 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002669 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002670 return false;
2671 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002672 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002673 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002674
Chris Lattnerdf986172009-01-02 07:01:27 +00002675 V = ID.ConstantVal;
2676 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002677 case ValID::t_ConstantStruct:
2678 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002679 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002680 if (ST->getNumElements() != ID.UIntVal)
2681 return Error(ID.Loc,
2682 "initializer with struct type has wrong # elements");
2683 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2684 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman407a6162012-11-15 22:34:00 +00002685
Chris Lattner1afcace2011-07-09 17:41:24 +00002686 // Verify that the elements are compatible with the structtype.
2687 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2688 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2689 return Error(ID.Loc, "element " + Twine(i) +
2690 " of struct initializer doesn't match struct element type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002691
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002692 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2693 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002694 } else
2695 return Error(ID.Loc, "constant expression type mismatch");
2696 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002697 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002698 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002699}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002700
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002701bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 V = 0;
2703 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002704 return ParseValID(ID, PFS) ||
2705 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002706}
2707
Chris Lattner1afcace2011-07-09 17:41:24 +00002708bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2709 Type *Ty = 0;
2710 return ParseType(Ty) ||
2711 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002712}
2713
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002714bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2715 PerFunctionState &PFS) {
2716 Value *V;
2717 Loc = Lex.getLoc();
2718 if (ParseTypeAndValue(V, PFS)) return true;
2719 if (!isa<BasicBlock>(V))
2720 return Error(Loc, "expected a basic block");
2721 BB = cast<BasicBlock>(V);
2722 return false;
2723}
2724
2725
Chris Lattnerdf986172009-01-02 07:01:27 +00002726/// FunctionHeader
2727/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002728/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002729/// OptionalAlign OptGC
2730bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2731 // Parse the linkage.
2732 LocTy LinkageLoc = Lex.getLoc();
2733 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002734
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002735 unsigned Visibility;
Bill Wendling702cc912012-10-15 20:35:56 +00002736 AttrBuilder RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002737 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002738 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002739 LocTy RetTypeLoc = Lex.getLoc();
2740 if (ParseOptionalLinkage(Linkage) ||
2741 ParseOptionalVisibility(Visibility) ||
2742 ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002743 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002744 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 return true;
2746
2747 // Verify that the linkage is ok.
2748 switch ((GlobalValue::LinkageTypes)Linkage) {
2749 case GlobalValue::ExternalLinkage:
2750 break; // always ok.
2751 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002752 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002753 if (isDefine)
2754 return Error(LinkageLoc, "invalid linkage for function definition");
2755 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002756 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002757 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002758 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002759 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002760 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002761 case GlobalValue::LinkOnceAnyLinkage:
2762 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002763 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002764 case GlobalValue::WeakAnyLinkage:
2765 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 case GlobalValue::DLLExportLinkage:
2767 if (!isDefine)
2768 return Error(LinkageLoc, "invalid linkage for function declaration");
2769 break;
2770 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002771 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002772 return Error(LinkageLoc, "invalid function linkage type");
2773 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002774
Chris Lattner1afcace2011-07-09 17:41:24 +00002775 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777
Chris Lattnerdf986172009-01-02 07:01:27 +00002778 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002779
2780 std::string FunctionName;
2781 if (Lex.getKind() == lltok::GlobalVar) {
2782 FunctionName = Lex.getStrVal();
2783 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2784 unsigned NameID = Lex.getUIntVal();
2785
2786 if (NameID != NumberedVals.size())
2787 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002788 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002789 } else {
2790 return TokError("expected function name");
2791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002792
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002793 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002795 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattner1afcace2011-07-09 17:41:24 +00002798 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002799 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00002800 AttrBuilder FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002801 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002802 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002803 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002804 bool UnnamedAddr;
2805 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002806
Chris Lattner1afcace2011-07-09 17:41:24 +00002807 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002808 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2809 &UnnamedAddrLoc) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002810 ParseOptionalFuncAttrs(FuncAttrs) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002811 (EatIfPresent(lltok::kw_section) &&
2812 ParseStringConstant(Section)) ||
2813 ParseOptionalAlignment(Alignment) ||
2814 (EatIfPresent(lltok::kw_gc) &&
2815 ParseStringConstant(GC)))
2816 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002817
2818 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00002819 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002820 Alignment = FuncAttrs.getAlignment();
Bill Wendling034b94b2012-12-19 07:18:57 +00002821 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00002822 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 // Okay, if we got here, the function is syntactically valid. Convert types
2825 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002826 std::vector<Type*> ParamTypeList;
Bill Wendlinga1683d62013-01-27 02:24:02 +00002827 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Bill Wendlinge603fe42012-09-19 23:54:18 +00002829 if (RetAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00002830 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2831 AttributeSet::ReturnIndex,
2832 RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002833
Chris Lattnerdf986172009-01-02 07:01:27 +00002834 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002835 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendling73dee182013-01-31 00:29:54 +00002836 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
2837 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlinga1683d62013-01-27 02:24:02 +00002838 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
2839 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002840 }
2841
Bill Wendlinge603fe42012-09-19 23:54:18 +00002842 if (FuncAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00002843 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2844 AttributeSet::FunctionIndex,
2845 FuncAttrs));
Chris Lattnerdf986172009-01-02 07:01:27 +00002846
Bill Wendling99faa3b2012-12-07 23:16:57 +00002847 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002848
Bill Wendling94e94b32012-12-30 13:50:49 +00002849 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002850 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2851
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002852 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002853 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002854 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002855
2856 Fn = 0;
2857 if (!FunctionName.empty()) {
2858 // If this was a definition of a forward reference, remove the definition
2859 // from the forward reference table and fill in the forward ref.
2860 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2861 ForwardRefVals.find(FunctionName);
2862 if (FRVI != ForwardRefVals.end()) {
2863 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00002864 if (!Fn)
2865 return Error(FRVI->second.second, "invalid forward reference to "
2866 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002867 if (Fn->getType() != PFT)
2868 return Error(FRVI->second.second, "invalid forward reference to "
2869 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman407a6162012-11-15 22:34:00 +00002870
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 ForwardRefVals.erase(FRVI);
2872 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002873 // Reject redefinitions.
2874 return Error(NameLoc, "invalid redefinition of function '" +
2875 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002876 } else if (M->getNamedValue(FunctionName)) {
2877 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002879
Dan Gohman41905542009-08-29 23:37:49 +00002880 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002881 // If this is a definition of a forward referenced function, make sure the
2882 // types agree.
2883 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2884 = ForwardRefValIDs.find(NumberedVals.size());
2885 if (I != ForwardRefValIDs.end()) {
2886 Fn = cast<Function>(I->second.first);
2887 if (Fn->getType() != PFT)
2888 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002889 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 ForwardRefValIDs.erase(I);
2891 }
2892 }
2893
2894 if (Fn == 0)
2895 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2896 else // Move the forward-reference to the correct spot in the module.
2897 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2898
2899 if (FunctionName.empty())
2900 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002901
Chris Lattnerdf986172009-01-02 07:01:27 +00002902 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2903 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2904 Fn->setCallingConv(CC);
2905 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002906 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 Fn->setAlignment(Alignment);
2908 Fn->setSection(Section);
2909 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002910
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 // Add all of the arguments we parsed to the function.
2912 Function::arg_iterator ArgIt = Fn->arg_begin();
2913 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2914 // If the argument has a name, insert it into the argument symbol table.
2915 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002916
Chris Lattnerdf986172009-01-02 07:01:27 +00002917 // Set the name, if it conflicted, it will be auto-renamed.
2918 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919
Benjamin Krameraf812352010-10-16 11:28:23 +00002920 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002921 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2922 ArgList[i].Name + "'");
2923 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 return false;
2926}
2927
2928
2929/// ParseFunctionBody
2930/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002931///
2932bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002933 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002934 return TokError("expected '{' in function body");
2935 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002936
Chris Lattner09d9ef42009-10-28 03:39:23 +00002937 int FunctionNumber = -1;
2938 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman407a6162012-11-15 22:34:00 +00002939
Chris Lattner09d9ef42009-10-28 03:39:23 +00002940 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002941
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002942 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002943 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002944 return TokError("function body requires at least one basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +00002945
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002946 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002947 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002948
Chris Lattnerdf986172009-01-02 07:01:27 +00002949 // Eat the }.
2950 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002951
Chris Lattnerdf986172009-01-02 07:01:27 +00002952 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002953 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002954}
2955
2956/// ParseBasicBlock
2957/// ::= LabelStr? Instruction*
2958bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2959 // If this basic block starts out with a name, remember it.
2960 std::string Name;
2961 LocTy NameLoc = Lex.getLoc();
2962 if (Lex.getKind() == lltok::LabelStr) {
2963 Name = Lex.getStrVal();
2964 Lex.Lex();
2965 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002966
Chris Lattnerdf986172009-01-02 07:01:27 +00002967 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2968 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002969
Chris Lattnerdf986172009-01-02 07:01:27 +00002970 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002971
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 // Parse the instructions in this block until we get a terminator.
2973 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002974 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002975 do {
2976 // This instruction may have three possibilities for a name: a) none
2977 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2978 LocTy NameLoc = Lex.getLoc();
2979 int NameID = -1;
2980 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002981
Chris Lattnerdf986172009-01-02 07:01:27 +00002982 if (Lex.getKind() == lltok::LocalVarID) {
2983 NameID = Lex.getUIntVal();
2984 Lex.Lex();
2985 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2986 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002987 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 NameStr = Lex.getStrVal();
2989 Lex.Lex();
2990 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2991 return true;
2992 }
Devang Patelf633a062009-09-17 23:04:48 +00002993
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002994 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002995 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002996 case InstError: return true;
2997 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002998 BB->getInstList().push_back(Inst);
2999
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003000 // With a normal result, we check to see if the instruction is followed by
3001 // a comma and metadata.
3002 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00003003 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003004 return true;
3005 break;
3006 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00003007 BB->getInstList().push_back(Inst);
3008
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003009 // If the instruction parser ate an extra comma at the end of it, it
3010 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00003011 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003012 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003013 break;
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003014 }
Devang Patelf633a062009-09-17 23:04:48 +00003015
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 // Set the name on the instruction.
3017 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3018 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003019
Chris Lattnerdf986172009-01-02 07:01:27 +00003020 return false;
3021}
3022
3023//===----------------------------------------------------------------------===//
3024// Instruction Parsing.
3025//===----------------------------------------------------------------------===//
3026
3027/// ParseInstruction - Parse one of the many different instructions.
3028///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003029int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3030 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003031 lltok::Kind Token = Lex.getKind();
3032 if (Token == lltok::Eof)
3033 return TokError("found end of file when expecting more instructions");
3034 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003035 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003036 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003037
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 switch (Token) {
3039 default: return Error(Loc, "expected instruction opcode");
3040 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003041 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003042 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3043 case lltok::kw_br: return ParseBr(Inst, PFS);
3044 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003045 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003047 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 // Binary Operators.
3049 case lltok::kw_add:
3050 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00003051 case lltok::kw_mul:
3052 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00003053 bool NUW = EatIfPresent(lltok::kw_nuw);
3054 bool NSW = EatIfPresent(lltok::kw_nsw);
3055 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman407a6162012-11-15 22:34:00 +00003056
Chris Lattnerf067d582011-02-07 16:40:21 +00003057 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003058
Chris Lattnerf067d582011-02-07 16:40:21 +00003059 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3060 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3061 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003062 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003063 case lltok::kw_fadd:
3064 case lltok::kw_fsub:
Michael Ilseman15c13d32012-11-27 00:42:44 +00003065 case lltok::kw_fmul:
3066 case lltok::kw_fdiv:
3067 case lltok::kw_frem: {
3068 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3069 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3070 if (Res != 0)
3071 return Res;
3072 if (FMF.any())
3073 Inst->setFastMathFlags(FMF);
3074 return 0;
3075 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003076
Chris Lattner35bda892011-02-06 21:44:57 +00003077 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00003078 case lltok::kw_udiv:
3079 case lltok::kw_lshr:
3080 case lltok::kw_ashr: {
3081 bool Exact = EatIfPresent(lltok::kw_exact);
3082
3083 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3084 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3085 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003086 }
3087
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003089 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 case lltok::kw_and:
3091 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003092 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003093 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003094 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 // Casts.
3096 case lltok::kw_trunc:
3097 case lltok::kw_zext:
3098 case lltok::kw_sext:
3099 case lltok::kw_fptrunc:
3100 case lltok::kw_fpext:
3101 case lltok::kw_bitcast:
3102 case lltok::kw_uitofp:
3103 case lltok::kw_sitofp:
3104 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003105 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003106 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003107 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003108 // Other.
3109 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003110 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3112 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3113 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3114 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003115 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003116 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3117 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3118 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003119 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003120 case lltok::kw_load: return ParseLoad(Inst, PFS);
3121 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003122 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3123 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003124 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003125 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3126 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3127 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3128 }
3129}
3130
3131/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3132bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003133 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003134 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00003135 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00003136 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3137 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3138 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3139 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3140 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3141 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3142 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3143 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3144 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3145 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3146 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3147 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3148 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3149 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3150 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3151 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3152 }
3153 } else {
3154 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00003155 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00003156 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3157 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3158 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3159 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3160 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3161 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3162 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3163 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3164 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3165 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3166 }
3167 }
3168 Lex.Lex();
3169 return false;
3170}
3171
3172//===----------------------------------------------------------------------===//
3173// Terminator Instructions.
3174//===----------------------------------------------------------------------===//
3175
3176/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003177/// ::= 'ret' void (',' !dbg, !1)*
3178/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003179bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003180 PerFunctionState &PFS) {
3181 SMLoc TypeLoc = Lex.getLoc();
3182 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003183 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003184
Chris Lattner1afcace2011-07-09 17:41:24 +00003185 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman407a6162012-11-15 22:34:00 +00003186
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003187 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003188 if (!ResType->isVoidTy())
3189 return Error(TypeLoc, "value doesn't match function result type '" +
3190 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003191
Owen Anderson1d0be152009-08-13 21:58:54 +00003192 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003193 return false;
3194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003195
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 Value *RV;
3197 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003198
Chris Lattner1afcace2011-07-09 17:41:24 +00003199 if (ResType != RV->getType())
3200 return Error(TypeLoc, "value doesn't match function result type '" +
3201 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003202
Owen Anderson1d0be152009-08-13 21:58:54 +00003203 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003204 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003205}
3206
3207
3208/// ParseBr
3209/// ::= 'br' TypeAndValue
3210/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3211bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3212 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003213 Value *Op0;
3214 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003216
Chris Lattnerdf986172009-01-02 07:01:27 +00003217 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3218 Inst = BranchInst::Create(BB);
3219 return false;
3220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003221
Owen Anderson1d0be152009-08-13 21:58:54 +00003222 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003224
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003226 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003228 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003230
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003231 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 return false;
3233}
3234
3235/// ParseSwitch
3236/// Instruction
3237/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3238/// JumpTable
3239/// ::= (TypeAndValue ',' TypeAndValue)*
3240bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3241 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003242 Value *Cond;
3243 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003244 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3245 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003246 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3248 return true;
3249
Duncan Sands1df98592010-02-16 11:11:14 +00003250 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003252
Chris Lattnerdf986172009-01-02 07:01:27 +00003253 // Parse the jump table pairs.
3254 SmallPtrSet<Value*, 32> SeenCases;
3255 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3256 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003257 Value *Constant;
3258 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003259
Chris Lattnerdf986172009-01-02 07:01:27 +00003260 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3261 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003262 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003264
Chris Lattnerdf986172009-01-02 07:01:27 +00003265 if (!SeenCases.insert(Constant))
3266 return Error(CondLoc, "duplicate case value in switch");
3267 if (!isa<ConstantInt>(Constant))
3268 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003269
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003270 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003272
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003274
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3277 SI->addCase(Table[i].first, Table[i].second);
3278 Inst = SI;
3279 return false;
3280}
3281
Chris Lattnerab21db72009-10-28 00:19:10 +00003282/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003283/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003284/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3285bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003286 LocTy AddrLoc;
3287 Value *Address;
3288 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003289 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3290 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003291 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003292
Duncan Sands1df98592010-02-16 11:11:14 +00003293 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003294 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman407a6162012-11-15 22:34:00 +00003295
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003296 // Parse the destination list.
3297 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman407a6162012-11-15 22:34:00 +00003298
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003299 if (Lex.getKind() != lltok::rsquare) {
3300 BasicBlock *DestBB;
3301 if (ParseTypeAndBasicBlock(DestBB, PFS))
3302 return true;
3303 DestList.push_back(DestBB);
Michael Ilseman407a6162012-11-15 22:34:00 +00003304
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003305 while (EatIfPresent(lltok::comma)) {
3306 if (ParseTypeAndBasicBlock(DestBB, PFS))
3307 return true;
3308 DestList.push_back(DestBB);
3309 }
3310 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003311
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003312 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3313 return true;
3314
Chris Lattnerab21db72009-10-28 00:19:10 +00003315 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003316 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3317 IBI->addDestination(DestList[i]);
3318 Inst = IBI;
3319 return false;
3320}
3321
3322
Chris Lattnerdf986172009-01-02 07:01:27 +00003323/// ParseInvoke
3324/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3325/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3326bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3327 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00003328 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003329 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003330 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003331 LocTy RetTypeLoc;
3332 ValID CalleeID;
3333 SmallVector<ParamInfo, 16> ArgList;
3334
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003335 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 if (ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003337 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003338 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003339 ParseValID(CalleeID) ||
3340 ParseParameterList(ArgList, PFS) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003341 ParseOptionalFuncAttrs(FnAttrs) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003342 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003343 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003345 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003347
Chris Lattnerdf986172009-01-02 07:01:27 +00003348 // If RetType is a non-function pointer type, then this is the short syntax
3349 // for the call, which means that RetType is just the return type. Infer the
3350 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003351 PointerType *PFTy = 0;
3352 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003353 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3354 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3355 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003356 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3358 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 if (!FunctionType::isValidReturnType(RetType))
3361 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003362
Owen Andersondebcb012009-07-29 22:17:13 +00003363 Ty = FunctionType::get(RetType, ParamTypes, false);
3364 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003366
Chris Lattnerdf986172009-01-02 07:01:27 +00003367 // Look up the callee.
3368 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003369 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003370
Bill Wendling034b94b2012-12-19 07:18:57 +00003371 // Set up the Attribute for the function.
Bill Wendlinga1683d62013-01-27 02:24:02 +00003372 SmallVector<AttributeSet, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003373 if (RetAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003374 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3375 AttributeSet::ReturnIndex,
3376 RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003377
Chris Lattnerdf986172009-01-02 07:01:27 +00003378 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003379
Chris Lattnerdf986172009-01-02 07:01:27 +00003380 // Loop through FunctionType's arguments and ensure they are specified
3381 // correctly. Also, gather any parameter attributes.
3382 FunctionType::param_iterator I = Ty->param_begin();
3383 FunctionType::param_iterator E = Ty->param_end();
3384 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003385 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 if (I != E) {
3387 ExpectedTy = *I++;
3388 } else if (!Ty->isVarArg()) {
3389 return Error(ArgList[i].Loc, "too many arguments specified");
3390 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003391
Chris Lattnerdf986172009-01-02 07:01:27 +00003392 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3393 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003394 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 Args.push_back(ArgList[i].V);
Bill Wendling73dee182013-01-31 00:29:54 +00003396 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3397 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlinga1683d62013-01-27 02:24:02 +00003398 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3399 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003401
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 if (I != E)
3403 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003404
Bill Wendlinge603fe42012-09-19 23:54:18 +00003405 if (FnAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003406 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3407 AttributeSet::FunctionIndex,
3408 FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003409
Bill Wendling034b94b2012-12-19 07:18:57 +00003410 // Finish off the Attribute and check them
Bill Wendling99faa3b2012-12-07 23:16:57 +00003411 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003412
Jay Foada3efbb12011-07-15 08:37:34 +00003413 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 II->setCallingConv(CC);
3415 II->setAttributes(PAL);
3416 Inst = II;
3417 return false;
3418}
3419
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003420/// ParseResume
3421/// ::= 'resume' TypeAndValue
3422bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3423 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003424 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3425 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003426
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003427 ResumeInst *RI = ResumeInst::Create(Exn);
3428 Inst = RI;
3429 return false;
3430}
Chris Lattnerdf986172009-01-02 07:01:27 +00003431
3432//===----------------------------------------------------------------------===//
3433// Binary Operators.
3434//===----------------------------------------------------------------------===//
3435
3436/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003437/// ::= ArithmeticOps TypeAndValue ',' Value
3438///
3439/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3440/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003441bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003442 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003443 LocTy Loc; Value *LHS, *RHS;
3444 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3446 ParseValue(LHS->getType(), RHS, PFS))
3447 return true;
3448
Chris Lattnere914b592009-01-05 08:24:46 +00003449 bool Valid;
3450 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003451 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003452 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003453 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3454 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003455 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003456 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3457 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003458 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003459
Chris Lattnere914b592009-01-05 08:24:46 +00003460 if (!Valid)
3461 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003462
Chris Lattnerdf986172009-01-02 07:01:27 +00003463 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3464 return false;
3465}
3466
3467/// ParseLogical
3468/// ::= ArithmeticOps TypeAndValue ',' Value {
3469bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3470 unsigned Opc) {
3471 LocTy Loc; Value *LHS, *RHS;
3472 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3473 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3474 ParseValue(LHS->getType(), RHS, PFS))
3475 return true;
3476
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003477 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003478 return Error(Loc,"instruction requires integer or integer vector operands");
3479
3480 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3481 return false;
3482}
3483
3484
3485/// ParseCompare
3486/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3487/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003488bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3489 unsigned Opc) {
3490 // Parse the integer/fp comparison predicate.
3491 LocTy Loc;
3492 unsigned Pred;
3493 Value *LHS, *RHS;
3494 if (ParseCmpPredicate(Pred, Opc) ||
3495 ParseTypeAndValue(LHS, Loc, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after compare value") ||
3497 ParseValue(LHS->getType(), RHS, PFS))
3498 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003499
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003501 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003502 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003503 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003504 } else {
3505 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003506 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003507 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003509 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003510 }
3511 return false;
3512}
3513
3514//===----------------------------------------------------------------------===//
3515// Other Instructions.
3516//===----------------------------------------------------------------------===//
3517
3518
3519/// ParseCast
3520/// ::= CastOpc TypeAndValue 'to' Type
3521bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3522 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003523 LocTy Loc;
3524 Value *Op;
3525 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 if (ParseTypeAndValue(Op, Loc, PFS) ||
3527 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3528 ParseType(DestTy))
3529 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003530
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003531 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3532 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003533 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003534 getTypeString(Op->getType()) + "' to '" +
3535 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003536 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3538 return false;
3539}
3540
3541/// ParseSelect
3542/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3543bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3544 LocTy Loc;
3545 Value *Op0, *Op1, *Op2;
3546 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3547 ParseToken(lltok::comma, "expected ',' after select condition") ||
3548 ParseTypeAndValue(Op1, PFS) ||
3549 ParseToken(lltok::comma, "expected ',' after select value") ||
3550 ParseTypeAndValue(Op2, PFS))
3551 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003552
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3554 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003555
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 Inst = SelectInst::Create(Op0, Op1, Op2);
3557 return false;
3558}
3559
Chris Lattner0088a5c2009-01-05 08:18:44 +00003560/// ParseVA_Arg
3561/// ::= 'va_arg' TypeAndValue ',' Type
3562bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003563 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003564 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003565 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003566 if (ParseTypeAndValue(Op, PFS) ||
3567 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003568 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003569 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003570
Chris Lattner0088a5c2009-01-05 08:18:44 +00003571 if (!EltTy->isFirstClassType())
3572 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003573
3574 Inst = new VAArgInst(Op, EltTy);
3575 return false;
3576}
3577
3578/// ParseExtractElement
3579/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3580bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3581 LocTy Loc;
3582 Value *Op0, *Op1;
3583 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' after extract value") ||
3585 ParseTypeAndValue(Op1, PFS))
3586 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003587
Chris Lattnerdf986172009-01-02 07:01:27 +00003588 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3589 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003590
Eric Christophera3500da2009-07-25 02:28:41 +00003591 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003592 return false;
3593}
3594
3595/// ParseInsertElement
3596/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3597bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3598 LocTy Loc;
3599 Value *Op0, *Op1, *Op2;
3600 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3601 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3602 ParseTypeAndValue(Op1, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3604 ParseTypeAndValue(Op2, PFS))
3605 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003606
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003608 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3611 return false;
3612}
3613
3614/// ParseShuffleVector
3615/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3616bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3617 LocTy Loc;
3618 Value *Op0, *Op1, *Op2;
3619 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3620 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3621 ParseTypeAndValue(Op1, PFS) ||
3622 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3623 ParseTypeAndValue(Op2, PFS))
3624 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003625
Chris Lattnerdf986172009-01-02 07:01:27 +00003626 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003627 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003628
Chris Lattnerdf986172009-01-02 07:01:27 +00003629 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3630 return false;
3631}
3632
3633/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003634/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003635int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003636 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003638
Chris Lattner1afcace2011-07-09 17:41:24 +00003639 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3641 ParseValue(Ty, Op0, PFS) ||
3642 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003643 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003644 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3645 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003646
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003647 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003648 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3649 while (1) {
3650 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003651
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003652 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003653 break;
3654
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003655 if (Lex.getKind() == lltok::MetadataVar) {
3656 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003657 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003658 }
Devang Patela43d46f2009-10-16 18:45:49 +00003659
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003660 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003661 ParseValue(Ty, Op0, PFS) ||
3662 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003663 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003664 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3665 return true;
3666 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003667
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 if (!Ty->isFirstClassType())
3669 return Error(TypeLoc, "phi node must have first class type");
3670
Jay Foad3ecfc862011-03-30 11:28:46 +00003671 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3673 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3674 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003675 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003676}
3677
Bill Wendlinge6e88262011-08-12 20:24:12 +00003678/// ParseLandingPad
3679/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3680/// Clause
3681/// ::= 'catch' TypeAndValue
3682/// ::= 'filter'
3683/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3684bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3685 Type *Ty = 0; LocTy TyLoc;
3686 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003687
3688 if (ParseType(Ty, TyLoc) ||
3689 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3690 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3691 return true;
3692
3693 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3694 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3695
3696 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3697 LandingPadInst::ClauseType CT;
3698 if (EatIfPresent(lltok::kw_catch))
3699 CT = LandingPadInst::Catch;
3700 else if (EatIfPresent(lltok::kw_filter))
3701 CT = LandingPadInst::Filter;
3702 else
3703 return TokError("expected 'catch' or 'filter' clause type");
3704
3705 Value *V; LocTy VLoc;
3706 if (ParseTypeAndValue(V, VLoc, PFS)) {
3707 delete LP;
3708 return true;
3709 }
3710
Bill Wendling746c8822011-08-12 20:52:25 +00003711 // A 'catch' type expects a non-array constant. A filter clause expects an
3712 // array constant.
3713 if (CT == LandingPadInst::Catch) {
3714 if (isa<ArrayType>(V->getType()))
3715 Error(VLoc, "'catch' clause has an invalid type");
3716 } else {
3717 if (!isa<ArrayType>(V->getType()))
3718 Error(VLoc, "'filter' clause has an invalid type");
3719 }
3720
Bill Wendlinge6e88262011-08-12 20:24:12 +00003721 LP->addClause(V);
3722 }
3723
3724 Inst = LP;
3725 return false;
3726}
3727
Chris Lattnerdf986172009-01-02 07:01:27 +00003728/// ParseCall
3729/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3730/// ParameterList OptionalAttrs
3731bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3732 bool isTail) {
Bill Wendling702cc912012-10-15 20:35:56 +00003733 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003734 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003735 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003736 LocTy RetTypeLoc;
3737 ValID CalleeID;
3738 SmallVector<ParamInfo, 16> ArgList;
3739 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003740
Chris Lattnerdf986172009-01-02 07:01:27 +00003741 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3742 ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003743 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003744 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003745 ParseValID(CalleeID) ||
3746 ParseParameterList(ArgList, PFS) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003747 ParseOptionalFuncAttrs(FnAttrs))
Chris Lattnerdf986172009-01-02 07:01:27 +00003748 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003749
Chris Lattnerdf986172009-01-02 07:01:27 +00003750 // If RetType is a non-function pointer type, then this is the short syntax
3751 // for the call, which means that RetType is just the return type. Infer the
3752 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003753 PointerType *PFTy = 0;
3754 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003755 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3756 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3757 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003758 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003759 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3760 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003761
Chris Lattnerdf986172009-01-02 07:01:27 +00003762 if (!FunctionType::isValidReturnType(RetType))
3763 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003764
Owen Andersondebcb012009-07-29 22:17:13 +00003765 Ty = FunctionType::get(RetType, ParamTypes, false);
3766 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003767 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003768
Chris Lattnerdf986172009-01-02 07:01:27 +00003769 // Look up the callee.
3770 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003771 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003772
Bill Wendling034b94b2012-12-19 07:18:57 +00003773 // Set up the Attribute for the function.
Bill Wendlinga1683d62013-01-27 02:24:02 +00003774 SmallVector<AttributeSet, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003775 if (RetAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003776 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3777 AttributeSet::ReturnIndex,
3778 RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003779
Chris Lattnerdf986172009-01-02 07:01:27 +00003780 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003781
Chris Lattnerdf986172009-01-02 07:01:27 +00003782 // Loop through FunctionType's arguments and ensure they are specified
3783 // correctly. Also, gather any parameter attributes.
3784 FunctionType::param_iterator I = Ty->param_begin();
3785 FunctionType::param_iterator E = Ty->param_end();
3786 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003787 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003788 if (I != E) {
3789 ExpectedTy = *I++;
3790 } else if (!Ty->isVarArg()) {
3791 return Error(ArgList[i].Loc, "too many arguments specified");
3792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003793
Chris Lattnerdf986172009-01-02 07:01:27 +00003794 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3795 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003796 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003797 Args.push_back(ArgList[i].V);
Bill Wendling73dee182013-01-31 00:29:54 +00003798 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3799 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlinga1683d62013-01-27 02:24:02 +00003800 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3801 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003803
Chris Lattnerdf986172009-01-02 07:01:27 +00003804 if (I != E)
3805 return Error(CallLoc, "not enough parameters specified for call");
3806
Bill Wendlinge603fe42012-09-19 23:54:18 +00003807 if (FnAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003808 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3809 AttributeSet::FunctionIndex,
3810 FnAttrs));
Chris Lattnerdf986172009-01-02 07:01:27 +00003811
Bill Wendling034b94b2012-12-19 07:18:57 +00003812 // Finish off the Attribute and check them
Bill Wendling99faa3b2012-12-07 23:16:57 +00003813 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003814
Jay Foada3efbb12011-07-15 08:37:34 +00003815 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003816 CI->setTailCall(isTail);
3817 CI->setCallingConv(CC);
3818 CI->setAttributes(PAL);
3819 Inst = CI;
3820 return false;
3821}
3822
3823//===----------------------------------------------------------------------===//
3824// Memory Instructions.
3825//===----------------------------------------------------------------------===//
3826
3827/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003828/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003829int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003830 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003831 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003832 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003833 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003834 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003835
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003836 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003837 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003838 if (Lex.getKind() == lltok::kw_align) {
3839 if (ParseOptionalAlignment(Alignment)) return true;
3840 } else if (Lex.getKind() == lltok::MetadataVar) {
3841 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003842 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003843 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3844 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3845 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003846 }
3847 }
3848
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003849 if (Size && !Size->getType()->isIntegerTy())
3850 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003851
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003852 Inst = new AllocaInst(Ty, Size, Alignment);
3853 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003854}
3855
3856/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003857/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman407a6162012-11-15 22:34:00 +00003858/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedmanf03bb262011-08-12 22:50:01 +00003859/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003860int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003861 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003862 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003863 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003864 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003865 AtomicOrdering Ordering = NotAtomic;
3866 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003867
3868 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003869 isAtomic = true;
3870 Lex.Lex();
3871 }
3872
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003873 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003874 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003875 isVolatile = true;
3876 Lex.Lex();
3877 }
3878
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003879 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003880 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003881 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3882 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003883
Duncan Sands1df98592010-02-16 11:11:14 +00003884 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003885 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3886 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003887 if (isAtomic && !Alignment)
3888 return Error(Loc, "atomic load must have explicit non-zero alignment");
3889 if (Ordering == Release || Ordering == AcquireRelease)
3890 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003891
Eli Friedman21006d42011-08-09 23:02:53 +00003892 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003893 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003894}
3895
3896/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003897
3898/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3899/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003900/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003901int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003902 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003903 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003904 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003905 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003906 AtomicOrdering Ordering = NotAtomic;
3907 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003908
3909 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003910 isAtomic = true;
3911 Lex.Lex();
3912 }
3913
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003914 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003915 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003916 isVolatile = true;
3917 Lex.Lex();
3918 }
3919
Chris Lattnerdf986172009-01-02 07:01:27 +00003920 if (ParseTypeAndValue(Val, Loc, PFS) ||
3921 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003922 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003923 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003924 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003925 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003926
Duncan Sands1df98592010-02-16 11:11:14 +00003927 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003928 return Error(PtrLoc, "store operand must be a pointer");
3929 if (!Val->getType()->isFirstClassType())
3930 return Error(Loc, "store operand must be a first class value");
3931 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3932 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003933 if (isAtomic && !Alignment)
3934 return Error(Loc, "atomic store must have explicit non-zero alignment");
3935 if (Ordering == Acquire || Ordering == AcquireRelease)
3936 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003937
Eli Friedman21006d42011-08-09 23:02:53 +00003938 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003939 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003940}
3941
Eli Friedmanff030482011-07-28 21:48:00 +00003942/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003943/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3944/// 'singlethread'? AtomicOrdering
3945int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003946 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3947 bool AteExtraComma = false;
3948 AtomicOrdering Ordering = NotAtomic;
3949 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003950 bool isVolatile = false;
3951
3952 if (EatIfPresent(lltok::kw_volatile))
3953 isVolatile = true;
3954
Eli Friedmanff030482011-07-28 21:48:00 +00003955 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3956 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3957 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3958 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3959 ParseTypeAndValue(New, NewLoc, PFS) ||
3960 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3961 return true;
3962
3963 if (Ordering == Unordered)
3964 return TokError("cmpxchg cannot be unordered");
3965 if (!Ptr->getType()->isPointerTy())
3966 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3967 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3968 return Error(CmpLoc, "compare value and pointer type do not match");
3969 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3970 return Error(NewLoc, "new value and pointer type do not match");
3971 if (!New->getType()->isIntegerTy())
3972 return Error(NewLoc, "cmpxchg operand must be an integer");
3973 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3974 if (Size < 8 || (Size & (Size - 1)))
3975 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3976 " integer");
3977
3978 AtomicCmpXchgInst *CXI =
3979 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3980 CXI->setVolatile(isVolatile);
3981 Inst = CXI;
3982 return AteExtraComma ? InstExtraComma : InstNormal;
3983}
3984
3985/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003986/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3987/// 'singlethread'? AtomicOrdering
3988int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003989 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3990 bool AteExtraComma = false;
3991 AtomicOrdering Ordering = NotAtomic;
3992 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003993 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003994 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003995
3996 if (EatIfPresent(lltok::kw_volatile))
3997 isVolatile = true;
3998
Eli Friedmanff030482011-07-28 21:48:00 +00003999 switch (Lex.getKind()) {
4000 default: return TokError("expected binary operation in atomicrmw");
4001 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4002 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4003 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4004 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4005 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4006 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4007 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4008 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4009 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4010 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4011 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4012 }
4013 Lex.Lex(); // Eat the operation.
4014
4015 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4016 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4017 ParseTypeAndValue(Val, ValLoc, PFS) ||
4018 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4019 return true;
4020
4021 if (Ordering == Unordered)
4022 return TokError("atomicrmw cannot be unordered");
4023 if (!Ptr->getType()->isPointerTy())
4024 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4025 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4026 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4027 if (!Val->getType()->isIntegerTy())
4028 return Error(ValLoc, "atomicrmw operand must be an integer");
4029 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4030 if (Size < 8 || (Size & (Size - 1)))
4031 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4032 " integer");
4033
4034 AtomicRMWInst *RMWI =
4035 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4036 RMWI->setVolatile(isVolatile);
4037 Inst = RMWI;
4038 return AteExtraComma ? InstExtraComma : InstNormal;
4039}
4040
Eli Friedman47f35132011-07-25 23:16:38 +00004041/// ParseFence
4042/// ::= 'fence' 'singlethread'? AtomicOrdering
4043int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4044 AtomicOrdering Ordering = NotAtomic;
4045 SynchronizationScope Scope = CrossThread;
4046 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4047 return true;
4048
4049 if (Ordering == Unordered)
4050 return TokError("fence cannot be unordered");
4051 if (Ordering == Monotonic)
4052 return TokError("fence cannot be monotonic");
4053
4054 Inst = new FenceInst(Context, Ordering, Scope);
4055 return InstNormal;
4056}
4057
Chris Lattnerdf986172009-01-02 07:01:27 +00004058/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00004059/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004060int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00004061 Value *Ptr = 0;
4062 Value *Val = 0;
4063 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00004064
Dan Gohmandcb40a32009-07-29 15:58:36 +00004065 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004066
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004067 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00004068
Nadav Rotem16087692011-12-05 06:29:09 +00004069 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004070 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004071
Chris Lattnerdf986172009-01-02 07:01:27 +00004072 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004073 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004074 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004075 if (Lex.getKind() == lltok::MetadataVar) {
4076 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00004077 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004078 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004079 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00004080 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004081 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00004082 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4083 return Error(EltLoc, "getelementptr index type missmatch");
4084 if (Val->getType()->isVectorTy()) {
4085 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4086 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4087 if (ValNumEl != PtrNumEl)
4088 return Error(EltLoc,
4089 "getelementptr vector index has a wrong number of elements");
4090 }
Chris Lattnerdf986172009-01-02 07:01:27 +00004091 Indices.push_back(Val);
4092 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00004093
Jay Foada9203102011-07-25 09:48:08 +00004094 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004095 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004096 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004097 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004098 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004099 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004100}
4101
4102/// ParseExtractValue
4103/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004104int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004105 Value *Val; LocTy Loc;
4106 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004107 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004108 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004109 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004110 return true;
4111
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004112 if (!Val->getType()->isAggregateType())
4113 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004114
Jay Foadfc6d3a42011-07-13 10:26:04 +00004115 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004116 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004117 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004118 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004119}
4120
4121/// ParseInsertValue
4122/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004123int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004124 Value *Val0, *Val1; LocTy Loc0, Loc1;
4125 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004126 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004127 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4128 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4129 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004130 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004131 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00004132
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004133 if (!Val0->getType()->isAggregateType())
4134 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004135
Jay Foadfc6d3a42011-07-13 10:26:04 +00004136 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004137 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004138 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004139 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004140}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004141
4142//===----------------------------------------------------------------------===//
4143// Embedded metadata.
4144//===----------------------------------------------------------------------===//
4145
4146/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004147/// ::= Element (',' Element)*
4148/// Element
4149/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004150bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004151 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004152 // Check for an empty list.
4153 if (Lex.getKind() == lltok::rbrace)
4154 return false;
4155
Nick Lewycky21cc4462009-04-04 07:22:01 +00004156 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004157 // Null is a special case since it is typeless.
4158 if (EatIfPresent(lltok::kw_null)) {
4159 Elts.push_back(0);
4160 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004161 }
Michael Ilseman407a6162012-11-15 22:34:00 +00004162
Chris Lattnera7352392009-12-30 04:42:57 +00004163 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004164 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004165 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004166 } while (EatIfPresent(lltok::comma));
4167
4168 return false;
4169}