blob: 0eb6023272c7d069989cc6eaaec4fcd6092390fa [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
Rafael Espindolabea46262011-01-08 16:42:36 +0000635/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000636/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000637/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000638///
639/// Everything through visibility has been parsed already.
640///
641bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
642 unsigned Linkage, bool HasLinkage,
643 unsigned Visibility) {
644 unsigned AddrSpace;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000645 bool IsConstant, UnnamedAddr;
646 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000647 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000648 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000649
Chris Lattner1afcace2011-07-09 17:41:24 +0000650 Type *Ty = 0;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000651 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000652 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000653 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
654 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 ParseGlobalType(IsConstant) ||
656 ParseType(Ty, TyLoc))
657 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000658
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 // If the linkage is specified and is external, then no initializer is
660 // present.
661 Constant *Init = 0;
662 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000663 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000664 Linkage != GlobalValue::ExternalLinkage)) {
665 if (ParseGlobalValue(Ty, Init))
666 return true;
667 }
668
Duncan Sands1df98592010-02-16 11:11:14 +0000669 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000670 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000671
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 GlobalVariable *GV = 0;
673
674 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000675 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000676 if (GlobalValue *GVal = M->getNamedValue(Name)) {
677 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
678 return Error(NameLoc, "redefinition of global '@" + Name + "'");
679 GV = cast<GlobalVariable>(GVal);
680 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 } else {
682 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
683 I = ForwardRefValIDs.find(NumberedVals.size());
684 if (I != ForwardRefValIDs.end()) {
685 GV = cast<GlobalVariable>(I->second.first);
686 ForwardRefValIDs.erase(I);
687 }
688 }
689
690 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000691 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000692 Name, 0, GlobalVariable::NotThreadLocal,
693 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 } else {
695 if (GV->getType()->getElementType() != Ty)
696 return Error(TyLoc,
697 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000698
Chris Lattnerdf986172009-01-02 07:01:27 +0000699 // Move the forward-reference to the correct spot in the module.
700 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
701 }
702
703 if (Name.empty())
704 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000705
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 // Set the parsed properties on the global.
707 if (Init)
708 GV->setInitializer(Init);
709 GV->setConstant(IsConstant);
710 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
711 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000712 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +0000713 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000714
Chris Lattnerdf986172009-01-02 07:01:27 +0000715 // Parse attributes on the global.
716 while (Lex.getKind() == lltok::comma) {
717 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 if (Lex.getKind() == lltok::kw_section) {
720 Lex.Lex();
721 GV->setSection(Lex.getStrVal());
722 if (ParseToken(lltok::StringConstant, "expected global section string"))
723 return true;
724 } else if (Lex.getKind() == lltok::kw_align) {
725 unsigned Alignment;
726 if (ParseOptionalAlignment(Alignment)) return true;
727 GV->setAlignment(Alignment);
728 } else {
729 TokError("unknown global variable property!");
730 }
731 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000732
Chris Lattnerdf986172009-01-02 07:01:27 +0000733 return false;
734}
735
736
737//===----------------------------------------------------------------------===//
738// GlobalValue Reference/Resolution Routines.
739//===----------------------------------------------------------------------===//
740
741/// GetGlobalVal - Get a value with the specified name or ID, creating a
742/// forward reference record if needed. This can return null if the value
743/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000744GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000746 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000747 if (PTy == 0) {
748 Error(Loc, "global variable reference must have pointer type");
749 return 0;
750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751
Chris Lattnerdf986172009-01-02 07:01:27 +0000752 // Look this name up in the normal function symbol table.
753 GlobalValue *Val =
754 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000755
Chris Lattnerdf986172009-01-02 07:01:27 +0000756 // If this is a forward reference for the value, see if we already created a
757 // forward ref record.
758 if (Val == 0) {
759 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
760 I = ForwardRefVals.find(Name);
761 if (I != ForwardRefVals.end())
762 Val = I->second.first;
763 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000764
Chris Lattnerdf986172009-01-02 07:01:27 +0000765 // If we have the value in the symbol table or fwd-ref table, return it.
766 if (Val) {
767 if (Val->getType() == Ty) return Val;
768 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000769 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000770 return 0;
771 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Chris Lattnerdf986172009-01-02 07:01:27 +0000773 // Otherwise, create a new forward reference for this value and remember it.
774 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000775 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000776 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000777 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000778 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinskieaff2d52012-11-16 21:03:47 +0000779 GlobalValue::ExternalWeakLinkage, 0, Name,
780 0, GlobalVariable::NotThreadLocal,
781 PTy->getAddressSpace());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Chris Lattnerdf986172009-01-02 07:01:27 +0000783 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
784 return FwdVal;
785}
786
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000787GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
788 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000789 if (PTy == 0) {
790 Error(Loc, "global variable reference must have pointer type");
791 return 0;
792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Chris Lattnerdf986172009-01-02 07:01:27 +0000794 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Chris Lattnerdf986172009-01-02 07:01:27 +0000796 // If this is a forward reference for the value, see if we already created a
797 // forward ref record.
798 if (Val == 0) {
799 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
800 I = ForwardRefValIDs.find(ID);
801 if (I != ForwardRefValIDs.end())
802 Val = I->second.first;
803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000804
Chris Lattnerdf986172009-01-02 07:01:27 +0000805 // If we have the value in the symbol table or fwd-ref table, return it.
806 if (Val) {
807 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000808 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000809 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 return 0;
811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000812
Chris Lattnerdf986172009-01-02 07:01:27 +0000813 // Otherwise, create a new forward reference for this value and remember it.
814 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000815 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000816 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000817 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000818 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
819 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000820
Chris Lattnerdf986172009-01-02 07:01:27 +0000821 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
822 return FwdVal;
823}
824
825
826//===----------------------------------------------------------------------===//
827// Helper Routines.
828//===----------------------------------------------------------------------===//
829
830/// ParseToken - If the current token has the specified kind, eat it and return
831/// success. Otherwise, emit the specified error and return failure.
832bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
833 if (Lex.getKind() != T)
834 return TokError(ErrMsg);
835 Lex.Lex();
836 return false;
837}
838
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000839/// ParseStringConstant
840/// ::= StringConstant
841bool LLParser::ParseStringConstant(std::string &Result) {
842 if (Lex.getKind() != lltok::StringConstant)
843 return TokError("expected string constant");
844 Result = Lex.getStrVal();
845 Lex.Lex();
846 return false;
847}
848
849/// ParseUInt32
850/// ::= uint32
851bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000852 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
853 return TokError("expected integer");
854 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
855 if (Val64 != unsigned(Val64))
856 return TokError("expected 32-bit integer (too large)");
857 Val = Val64;
858 Lex.Lex();
859 return false;
860}
861
Hans Wennborgce718ff2012-06-23 11:37:03 +0000862/// ParseTLSModel
863/// := 'localdynamic'
864/// := 'initialexec'
865/// := 'localexec'
866bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
867 switch (Lex.getKind()) {
868 default:
869 return TokError("expected localdynamic, initialexec or localexec");
870 case lltok::kw_localdynamic:
871 TLM = GlobalVariable::LocalDynamicTLSModel;
872 break;
873 case lltok::kw_initialexec:
874 TLM = GlobalVariable::InitialExecTLSModel;
875 break;
876 case lltok::kw_localexec:
877 TLM = GlobalVariable::LocalExecTLSModel;
878 break;
879 }
880
881 Lex.Lex();
882 return false;
883}
884
885/// ParseOptionalThreadLocal
886/// := /*empty*/
887/// := 'thread_local'
888/// := 'thread_local' '(' tlsmodel ')'
889bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
890 TLM = GlobalVariable::NotThreadLocal;
891 if (!EatIfPresent(lltok::kw_thread_local))
892 return false;
893
894 TLM = GlobalVariable::GeneralDynamicTLSModel;
895 if (Lex.getKind() == lltok::lparen) {
896 Lex.Lex();
897 return ParseTLSModel(TLM) ||
898 ParseToken(lltok::rparen, "expected ')' after thread local model");
899 }
900 return false;
901}
Chris Lattnerdf986172009-01-02 07:01:27 +0000902
903/// ParseOptionalAddrSpace
904/// := /*empty*/
905/// := 'addrspace' '(' uint32 ')'
906bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
907 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000908 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000909 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000911 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000912 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000913}
Chris Lattnerdf986172009-01-02 07:01:27 +0000914
Bill Wendlinge01b81b2012-12-04 23:40:58 +0000915/// ParseOptionalFuncAttrs - Parse a potentially empty list of function attributes.
916bool LLParser::ParseOptionalFuncAttrs(AttrBuilder &B) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000917 bool HaveError = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000918
Bill Wendlingf385f4c2012-10-08 23:27:46 +0000919 B.clear();
920
Chris Lattnerdf986172009-01-02 07:01:27 +0000921 while (1) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000922 lltok::Kind Token = Lex.getKind();
923 switch (Token) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000924 default: // End of attributes.
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000925 return HaveError;
Charles Davis1e063d12010-02-12 00:31:15 +0000926 case lltok::kw_alignstack: {
927 unsigned Alignment;
928 if (ParseOptionalStackAlignment(Alignment))
929 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000930 B.addStackAlignmentAttr(Alignment);
Charles Davis1e063d12010-02-12 00:31:15 +0000931 continue;
932 }
Bill Wendlinge01b81b2012-12-04 23:40:58 +0000933 case lltok::kw_align: {
934 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
935 // 2".
936 unsigned Alignment;
937 if (ParseOptionalAlignment(Alignment))
938 return true;
939 B.addAlignmentAttr(Alignment);
940 continue;
941 }
Bill Wendling034b94b2012-12-19 07:18:57 +0000942 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
943 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
944 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
945 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
946 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
947 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
948 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
949 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
950 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
951 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
952 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
953 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
954 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
955 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
956 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
957 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
958 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
Bill Wendling114baee2013-01-23 06:41:41 +0000959 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
Bill Wendling034b94b2012-12-19 07:18:57 +0000960 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
James Molloy67ae1352012-12-20 16:04:27 +0000961 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
Charles Davis1e063d12010-02-12 00:31:15 +0000962
Bill Wendlinge01b81b2012-12-04 23:40:58 +0000963 // Error handling.
964 case lltok::kw_zeroext:
965 case lltok::kw_signext:
966 case lltok::kw_inreg:
967 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on a function");
968 break;
969 case lltok::kw_sret: case lltok::kw_noalias:
970 case lltok::kw_nocapture: case lltok::kw_byval:
971 case lltok::kw_nest:
972 HaveError |=
973 Error(Lex.getLoc(), "invalid use of parameter-only attribute on a function");
974 break;
975 }
976
977 Lex.Lex();
978 }
979}
980
981/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
982bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
983 bool HaveError = false;
984
985 B.clear();
986
987 while (1) {
988 lltok::Kind Token = Lex.getKind();
989 switch (Token) {
990 default: // End of attributes.
991 return HaveError;
Chris Lattnerdf986172009-01-02 07:01:27 +0000992 case lltok::kw_align: {
993 unsigned Alignment;
994 if (ParseOptionalAlignment(Alignment))
995 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000996 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000997 continue;
998 }
Bill Wendling034b94b2012-12-19 07:18:57 +0000999 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1000 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1001 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1002 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1003 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1004 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1005 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1006 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davis1e063d12010-02-12 00:31:15 +00001007
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001008 case lltok::kw_noreturn: case lltok::kw_nounwind:
1009 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1010 case lltok::kw_noinline: case lltok::kw_readnone:
1011 case lltok::kw_readonly: case lltok::kw_inlinehint:
1012 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1013 case lltok::kw_ssp: case lltok::kw_sspreq:
1014 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1015 case lltok::kw_naked: case lltok::kw_nonlazybind:
1016 case lltok::kw_address_safety: case lltok::kw_minsize:
1017 case lltok::kw_alignstack:
1018 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1019 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001020 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001021
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001022 Lex.Lex();
1023 }
1024}
1025
1026/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1027bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1028 bool HaveError = false;
1029
1030 B.clear();
1031
1032 while (1) {
1033 lltok::Kind Token = Lex.getKind();
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001034 switch (Token) {
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001035 default: // End of attributes.
1036 return HaveError;
Bill Wendling034b94b2012-12-19 07:18:57 +00001037 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1038 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1039 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1040 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001041
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001042 // Error handling.
1043 case lltok::kw_sret: case lltok::kw_nocapture:
1044 case lltok::kw_byval: case lltok::kw_nest:
1045 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001046 break;
James Molloy67ae1352012-12-20 16:04:27 +00001047
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001048 case lltok::kw_noreturn: case lltok::kw_nounwind:
1049 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1050 case lltok::kw_noinline: case lltok::kw_readnone:
1051 case lltok::kw_readonly: case lltok::kw_inlinehint:
1052 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1053 case lltok::kw_ssp: case lltok::kw_sspreq:
Bill Wendling114baee2013-01-23 06:41:41 +00001054 case lltok::kw_sspstrong: case lltok::kw_noimplicitfloat:
1055 case lltok::kw_noredzone: case lltok::kw_naked:
1056 case lltok::kw_nonlazybind: case lltok::kw_address_safety:
1057 case lltok::kw_minsize: case lltok::kw_alignstack:
1058 case lltok::kw_align: case lltok::kw_noduplicate:
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001059 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001060 break;
1061 }
1062
Chris Lattnerdf986172009-01-02 07:01:27 +00001063 Lex.Lex();
1064 }
1065}
1066
1067/// ParseOptionalLinkage
1068/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001069/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001070/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001071/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001072/// ::= 'internal'
1073/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001074/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001075/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001076/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001077/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001078/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001079/// ::= 'appending'
1080/// ::= 'dllexport'
1081/// ::= 'common'
1082/// ::= 'dllimport'
1083/// ::= 'extern_weak'
1084/// ::= 'external'
1085bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1086 HasLinkage = false;
1087 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001088 default: Res=GlobalValue::ExternalLinkage; return false;
1089 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1090 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001091 case lltok::kw_linker_private_weak:
1092 Res = GlobalValue::LinkerPrivateWeakLinkage;
1093 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001094 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1095 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1096 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1097 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1098 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001099 case lltok::kw_linkonce_odr_auto_hide:
1100 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1101 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1102 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001103 case lltok::kw_available_externally:
1104 Res = GlobalValue::AvailableExternallyLinkage;
1105 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001106 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1107 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1108 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1109 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1110 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1111 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001112 }
1113 Lex.Lex();
1114 HasLinkage = true;
1115 return false;
1116}
1117
1118/// ParseOptionalVisibility
1119/// ::= /*empty*/
1120/// ::= 'default'
1121/// ::= 'hidden'
1122/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001123///
Chris Lattnerdf986172009-01-02 07:01:27 +00001124bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1125 switch (Lex.getKind()) {
1126 default: Res = GlobalValue::DefaultVisibility; return false;
1127 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1128 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1129 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1130 }
1131 Lex.Lex();
1132 return false;
1133}
1134
1135/// ParseOptionalCallingConv
1136/// ::= /*empty*/
1137/// ::= 'ccc'
1138/// ::= 'fastcc'
Elena Demikhovsky35752222012-10-24 14:46:16 +00001139/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001140/// ::= 'coldcc'
1141/// ::= 'x86_stdcallcc'
1142/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001143/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001144/// ::= 'arm_apcscc'
1145/// ::= 'arm_aapcscc'
1146/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001147/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001148/// ::= 'ptx_kernel'
1149/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001150/// ::= 'spir_func'
1151/// ::= 'spir_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001152/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001153///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001154bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001155 switch (Lex.getKind()) {
1156 default: CC = CallingConv::C; return false;
1157 case lltok::kw_ccc: CC = CallingConv::C; break;
1158 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1159 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1160 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1161 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001162 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001163 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1164 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1165 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001166 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001167 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1168 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001169 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1170 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001171 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001172 case lltok::kw_cc: {
1173 unsigned ArbitraryCC;
1174 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001175 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001176 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001177 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1178 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001179 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182 Lex.Lex();
1183 return false;
1184}
1185
Chris Lattnerb8c46862009-12-30 05:31:19 +00001186/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001187/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001188bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1189 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001190 do {
1191 if (Lex.getKind() != lltok::MetadataVar)
1192 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001193
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001194 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001195 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001196 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001197
Chris Lattner442ffa12009-12-29 21:53:55 +00001198 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001199 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001200
1201 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001202 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001203
Dan Gohman68261142010-08-24 14:35:45 +00001204 // This code is similar to that of ParseMetadataValue, however it needs to
1205 // have special-case code for a forward reference; see the comments on
1206 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1207 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001208 if (Lex.getKind() == lltok::lbrace) {
1209 ValID ID;
1210 if (ParseMetadataListValue(ID, PFS))
1211 return true;
1212 assert(ID.Kind == ValID::t_MDNode);
1213 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001214 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001215 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001216 if (ParseMDNodeID(Node, NodeID))
1217 return true;
1218 if (Node) {
1219 // If we got the node, add it to the instruction.
1220 Inst->setMetadata(MDK, Node);
1221 } else {
1222 MDRef R = { Loc, MDK, NodeID };
1223 // Otherwise, remember that this should be resolved later.
1224 ForwardRefInstMetadata[Inst].push_back(R);
1225 }
Chris Lattner449c3102010-04-01 05:14:45 +00001226 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001227
1228 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001229 } while (EatIfPresent(lltok::comma));
1230 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001231}
1232
Chris Lattnerdf986172009-01-02 07:01:27 +00001233/// ParseOptionalAlignment
1234/// ::= /* empty */
1235/// ::= 'align' 4
1236bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1237 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001238 if (!EatIfPresent(lltok::kw_align))
1239 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001240 LocTy AlignLoc = Lex.getLoc();
1241 if (ParseUInt32(Alignment)) return true;
1242 if (!isPowerOf2_32(Alignment))
1243 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001244 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001245 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001246 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001247}
1248
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001249/// ParseOptionalCommaAlign
Michael Ilseman407a6162012-11-15 22:34:00 +00001250/// ::=
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001251/// ::= ',' align 4
1252///
1253/// This returns with AteExtraComma set to true if it ate an excess comma at the
1254/// end.
1255bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1256 bool &AteExtraComma) {
1257 AteExtraComma = false;
1258 while (EatIfPresent(lltok::comma)) {
1259 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001260 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001261 AteExtraComma = true;
1262 return false;
1263 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001264
Chris Lattner093eed12010-04-23 00:50:50 +00001265 if (Lex.getKind() != lltok::kw_align)
1266 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001267
Chris Lattner093eed12010-04-23 00:50:50 +00001268 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001269 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001270
Devang Patelf633a062009-09-17 23:04:48 +00001271 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001272}
1273
Eli Friedman47f35132011-07-25 23:16:38 +00001274/// ParseScopeAndOrdering
1275/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1276/// else: ::=
1277///
1278/// This sets Scope and Ordering to the parsed values.
1279bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1280 AtomicOrdering &Ordering) {
1281 if (!isAtomic)
1282 return false;
1283
1284 Scope = CrossThread;
1285 if (EatIfPresent(lltok::kw_singlethread))
1286 Scope = SingleThread;
1287 switch (Lex.getKind()) {
1288 default: return TokError("Expected ordering on atomic instruction");
1289 case lltok::kw_unordered: Ordering = Unordered; break;
1290 case lltok::kw_monotonic: Ordering = Monotonic; break;
1291 case lltok::kw_acquire: Ordering = Acquire; break;
1292 case lltok::kw_release: Ordering = Release; break;
1293 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1294 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1295 }
1296 Lex.Lex();
1297 return false;
1298}
1299
Charles Davis1e063d12010-02-12 00:31:15 +00001300/// ParseOptionalStackAlignment
1301/// ::= /* empty */
1302/// ::= 'alignstack' '(' 4 ')'
1303bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1304 Alignment = 0;
1305 if (!EatIfPresent(lltok::kw_alignstack))
1306 return false;
1307 LocTy ParenLoc = Lex.getLoc();
1308 if (!EatIfPresent(lltok::lparen))
1309 return Error(ParenLoc, "expected '('");
1310 LocTy AlignLoc = Lex.getLoc();
1311 if (ParseUInt32(Alignment)) return true;
1312 ParenLoc = Lex.getLoc();
1313 if (!EatIfPresent(lltok::rparen))
1314 return Error(ParenLoc, "expected ')'");
1315 if (!isPowerOf2_32(Alignment))
1316 return Error(AlignLoc, "stack alignment is not a power of two");
1317 return false;
1318}
Devang Patelf633a062009-09-17 23:04:48 +00001319
Chris Lattner628c13a2009-12-30 05:14:00 +00001320/// ParseIndexList - This parses the index list for an insert/extractvalue
1321/// instruction. This sets AteExtraComma in the case where we eat an extra
1322/// comma at the end of the line and find that it is followed by metadata.
1323/// Clients that don't allow metadata can call the version of this function that
1324/// only takes one argument.
1325///
Chris Lattnerdf986172009-01-02 07:01:27 +00001326/// ParseIndexList
1327/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001328///
1329bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1330 bool &AteExtraComma) {
1331 AteExtraComma = false;
Michael Ilseman407a6162012-11-15 22:34:00 +00001332
Chris Lattnerdf986172009-01-02 07:01:27 +00001333 if (Lex.getKind() != lltok::comma)
1334 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001335
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001336 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001337 if (Lex.getKind() == lltok::MetadataVar) {
1338 AteExtraComma = true;
1339 return false;
1340 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001341 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001342 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001343 Indices.push_back(Idx);
1344 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001345
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 return false;
1347}
1348
1349//===----------------------------------------------------------------------===//
1350// Type Parsing.
1351//===----------------------------------------------------------------------===//
1352
Chris Lattner1afcace2011-07-09 17:41:24 +00001353/// ParseType - Parse a type.
1354bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1355 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001356 switch (Lex.getKind()) {
1357 default:
1358 return TokError("expected type");
1359 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001360 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001361 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001362 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001365 // Type ::= StructType
1366 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001367 return true;
1368 break;
1369 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001370 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 Lex.Lex(); // eat the lsquare.
1372 if (ParseArrayVectorType(Result, false))
1373 return true;
1374 break;
1375 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001376 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001377 Lex.Lex();
1378 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001379 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001380 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001381 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001382 } else if (ParseArrayVectorType(Result, true))
1383 return true;
1384 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001385 case lltok::LocalVar: {
1386 // Type ::= %foo
1387 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001388
Chris Lattner1afcace2011-07-09 17:41:24 +00001389 // If the type hasn't been defined yet, create a forward definition and
1390 // remember where that forward def'n was seen (in case it never is defined).
1391 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001392 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001393 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001395 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 Lex.Lex();
1397 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
Chris Lattner1afcace2011-07-09 17:41:24 +00001400 case lltok::LocalVarID: {
1401 // Type ::= %4
1402 if (Lex.getUIntVal() >= NumberedTypes.size())
1403 NumberedTypes.resize(Lex.getUIntVal()+1);
1404 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001405
Chris Lattner1afcace2011-07-09 17:41:24 +00001406 // If the type hasn't been defined yet, create a forward definition and
1407 // remember where that forward def'n was seen (in case it never is defined).
1408 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001409 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001410 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001411 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001412 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 Lex.Lex();
1414 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 }
1416 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001417
1418 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 while (1) {
1420 switch (Lex.getKind()) {
1421 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001422 default:
1423 if (!AllowVoid && Result->isVoidTy())
1424 return Error(TypeLoc, "void type only allowed for function results");
1425 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001426
Chris Lattner1afcace2011-07-09 17:41:24 +00001427 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001429 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001430 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001431 if (Result->isVoidTy())
1432 return TokError("pointers to void are invalid - use i8* instead");
1433 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001434 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001435 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001436 Lex.Lex();
1437 break;
1438
Chris Lattner1afcace2011-07-09 17:41:24 +00001439 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001440 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001441 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001443 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001444 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001445 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001446 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 unsigned AddrSpace;
1448 if (ParseOptionalAddrSpace(AddrSpace) ||
1449 ParseToken(lltok::star, "expected '*' in address space"))
1450 return true;
1451
Chris Lattner1afcace2011-07-09 17:41:24 +00001452 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001453 break;
1454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001455
Chris Lattnerdf986172009-01-02 07:01:27 +00001456 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1457 case lltok::lparen:
1458 if (ParseFunctionType(Result))
1459 return true;
1460 break;
1461 }
1462 }
1463}
1464
1465/// ParseParameterList
1466/// ::= '(' ')'
1467/// ::= '(' Arg (',' Arg)* ')'
1468/// Arg
1469/// ::= Type OptionalAttributes Value OptionalAttributes
1470bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1471 PerFunctionState &PFS) {
1472 if (ParseToken(lltok::lparen, "expected '(' in call"))
1473 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001474
Chris Lattnerdf986172009-01-02 07:01:27 +00001475 while (Lex.getKind() != lltok::rparen) {
1476 // If this isn't the first argument, we need a comma.
1477 if (!ArgList.empty() &&
1478 ParseToken(lltok::comma, "expected ',' in argument list"))
1479 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001480
Chris Lattnerdf986172009-01-02 07:01:27 +00001481 // Parse the argument.
1482 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001483 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001484 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001485 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001486 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001487 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001488
Chris Lattner287881d2009-12-30 02:11:14 +00001489 // Otherwise, handle normal operands.
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001490 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001491 return true;
Bill Wendling034b94b2012-12-19 07:18:57 +00001492 ArgList.push_back(ParamInfo(ArgLoc, V, Attribute::get(V->getContext(),
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001493 ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 }
1495
1496 Lex.Lex(); // Lex the ')'.
1497 return false;
1498}
1499
1500
1501
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001502/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001503/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001504/// ::= '(' ArgTypeListI ')'
1505/// ArgTypeListI
1506/// ::= /*empty*/
1507/// ::= '...'
1508/// ::= ArgTypeList ',' '...'
1509/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001510///
Chris Lattner1afcace2011-07-09 17:41:24 +00001511bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1512 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001513 isVarArg = false;
1514 assert(Lex.getKind() == lltok::lparen);
1515 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001516
Chris Lattnerdf986172009-01-02 07:01:27 +00001517 if (Lex.getKind() == lltok::rparen) {
1518 // empty
1519 } else if (Lex.getKind() == lltok::dotdotdot) {
1520 isVarArg = true;
1521 Lex.Lex();
1522 } else {
1523 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001524 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001525 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001527
Chris Lattner1afcace2011-07-09 17:41:24 +00001528 if (ParseType(ArgTy) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001529 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001530
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001531 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001532 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001534 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 Name = Lex.getStrVal();
1536 Lex.Lex();
1537 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001538
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001539 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001540 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001542 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001543 Attribute::get(ArgTy->getContext(),
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001544 Attrs), Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001546 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001547 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001548 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001549 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001550 break;
1551 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001552
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 // Otherwise must be an argument type.
1554 TypeLoc = Lex.getLoc();
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001555 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001556
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001557 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001558 return Error(TypeLoc, "argument can not have void type");
1559
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001560 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 Name = Lex.getStrVal();
1562 Lex.Lex();
1563 } else {
1564 Name = "";
1565 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001566
Chris Lattner1afcace2011-07-09 17:41:24 +00001567 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001568 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001569
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001570 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001571 Attribute::get(ArgTy->getContext(), Attrs),
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001572 Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00001573 }
1574 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001575
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001576 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001577}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001578
Chris Lattnerdf986172009-01-02 07:01:27 +00001579/// ParseFunctionType
1580/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001581bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001582 assert(Lex.getKind() == lltok::lparen);
1583
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001584 if (!FunctionType::isValidReturnType(Result))
1585 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattner1afcace2011-07-09 17:41:24 +00001587 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001588 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001589 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001591
Chris Lattnerdf986172009-01-02 07:01:27 +00001592 // Reject names on the arguments lists.
1593 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1594 if (!ArgList[i].Name.empty())
1595 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendling7be78482012-10-14 08:54:26 +00001596 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnera16546a2011-06-17 17:37:13 +00001597 return Error(ArgList[i].Loc,
1598 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001600
Jay Foad5fdd6c82011-07-12 14:06:48 +00001601 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001602 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001603 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001604
Chris Lattner1afcace2011-07-09 17:41:24 +00001605 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001606 return false;
1607}
1608
Chris Lattner1afcace2011-07-09 17:41:24 +00001609/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1610/// other structs.
1611bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1612 SmallVector<Type*, 8> Elts;
1613 if (ParseStructBody(Elts)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001614
Chris Lattner1afcace2011-07-09 17:41:24 +00001615 Result = StructType::get(Context, Elts, Packed);
1616 return false;
1617}
1618
1619/// ParseStructDefinition - Parse a struct in a 'type' definition.
1620bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1621 std::pair<Type*, LocTy> &Entry,
1622 Type *&ResultTy) {
1623 // If the type was already defined, diagnose the redefinition.
1624 if (Entry.first && !Entry.second.isValid())
1625 return Error(TypeLoc, "redefinition of type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001626
Chris Lattner1afcace2011-07-09 17:41:24 +00001627 // If we have opaque, just return without filling in the definition for the
1628 // struct. This counts as a definition as far as the .ll file goes.
1629 if (EatIfPresent(lltok::kw_opaque)) {
1630 // This type is being defined, so clear the location to indicate this.
1631 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001632
Chris Lattner1afcace2011-07-09 17:41:24 +00001633 // If this type number has never been uttered, create it.
1634 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001635 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001636 ResultTy = Entry.first;
1637 return false;
1638 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001639
Chris Lattner1afcace2011-07-09 17:41:24 +00001640 // If the type starts with '<', then it is either a packed struct or a vector.
1641 bool isPacked = EatIfPresent(lltok::less);
1642
1643 // If we don't have a struct, then we have a random type alias, which we
1644 // accept for compatibility with old files. These types are not allowed to be
1645 // forward referenced and not allowed to be recursive.
1646 if (Lex.getKind() != lltok::lbrace) {
1647 if (Entry.first)
1648 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001649
Chris Lattner1afcace2011-07-09 17:41:24 +00001650 ResultTy = 0;
1651 if (isPacked)
1652 return ParseArrayVectorType(ResultTy, true);
1653 return ParseType(ResultTy);
1654 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001655
Chris Lattner1afcace2011-07-09 17:41:24 +00001656 // This type is being defined, so clear the location to indicate this.
1657 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001658
Chris Lattner1afcace2011-07-09 17:41:24 +00001659 // If this type number has never been uttered, create it.
1660 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001661 Entry.first = StructType::create(Context, Name);
Michael Ilseman407a6162012-11-15 22:34:00 +00001662
Chris Lattner1afcace2011-07-09 17:41:24 +00001663 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman407a6162012-11-15 22:34:00 +00001664
Chris Lattner1afcace2011-07-09 17:41:24 +00001665 SmallVector<Type*, 8> Body;
1666 if (ParseStructBody(Body) ||
1667 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1668 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001669
Chris Lattner1afcace2011-07-09 17:41:24 +00001670 STy->setBody(Body, isPacked);
1671 ResultTy = STy;
1672 return false;
1673}
1674
1675
Chris Lattnerdf986172009-01-02 07:01:27 +00001676/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001677/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001678/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001679/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001680/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001681/// ::= '<' '{' Type (',' Type)* '}' '>'
1682bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001683 assert(Lex.getKind() == lltok::lbrace);
1684 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685
Chris Lattner1afcace2011-07-09 17:41:24 +00001686 // Handle the empty struct.
1687 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001688 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001689
Chris Lattnera9a9e072009-03-09 04:49:14 +00001690 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001691 Type *Ty = 0;
1692 if (ParseType(Ty)) return true;
1693 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001694
Chris Lattner1afcace2011-07-09 17:41:24 +00001695 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001696 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001697
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001698 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001699 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001700 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001701
Chris Lattner1afcace2011-07-09 17:41:24 +00001702 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001703 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001704
Chris Lattner1afcace2011-07-09 17:41:24 +00001705 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001707
Chris Lattner1afcace2011-07-09 17:41:24 +00001708 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001709}
1710
1711/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1712/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001713/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001714/// ::= '[' APSINTVAL 'x' Types ']'
1715/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001716bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1718 Lex.getAPSIntVal().getBitWidth() > 64)
1719 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 LocTy SizeLoc = Lex.getLoc();
1722 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001723 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001725 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1726 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001727
1728 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001729 Type *EltTy = 0;
1730 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001731
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001732 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1733 "expected end of sequential type"))
1734 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001735
Chris Lattnerdf986172009-01-02 07:01:27 +00001736 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001737 if (Size == 0)
1738 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 if ((unsigned)Size != Size)
1740 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001741 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00001742 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001743 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001744 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001745 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001747 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001748 }
1749 return false;
1750}
1751
1752//===----------------------------------------------------------------------===//
1753// Function Semantic Analysis.
1754//===----------------------------------------------------------------------===//
1755
Chris Lattner09d9ef42009-10-28 03:39:23 +00001756LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1757 int functionNumber)
1758 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001759
1760 // Insert unnamed arguments into the NumberedVals list.
1761 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1762 AI != E; ++AI)
1763 if (!AI->hasName())
1764 NumberedVals.push_back(AI);
1765}
1766
1767LLParser::PerFunctionState::~PerFunctionState() {
1768 // If there were any forward referenced non-basicblock values, delete them.
1769 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1770 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1771 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001772 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001773 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 delete I->second.first;
1775 I->second.first = 0;
1776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001777
Chris Lattnerdf986172009-01-02 07:01:27 +00001778 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1779 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1780 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001781 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001782 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001783 delete I->second.first;
1784 I->second.first = 0;
1785 }
1786}
1787
Chris Lattner09d9ef42009-10-28 03:39:23 +00001788bool LLParser::PerFunctionState::FinishFunction() {
1789 // Check to see if someone took the address of labels in this block.
1790 if (!P.ForwardRefBlockAddresses.empty()) {
1791 ValID FunctionID;
1792 if (!F.getName().empty()) {
1793 FunctionID.Kind = ValID::t_GlobalName;
1794 FunctionID.StrVal = F.getName();
1795 } else {
1796 FunctionID.Kind = ValID::t_GlobalID;
1797 FunctionID.UIntVal = FunctionNumber;
1798 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001799
Chris Lattner09d9ef42009-10-28 03:39:23 +00001800 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1801 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1802 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1803 // Resolve all these references.
1804 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1805 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001806
Chris Lattner09d9ef42009-10-28 03:39:23 +00001807 P.ForwardRefBlockAddresses.erase(FRBAI);
1808 }
1809 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001810
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 if (!ForwardRefVals.empty())
1812 return P.Error(ForwardRefVals.begin()->second.second,
1813 "use of undefined value '%" + ForwardRefVals.begin()->first +
1814 "'");
1815 if (!ForwardRefValIDs.empty())
1816 return P.Error(ForwardRefValIDs.begin()->second.second,
1817 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001818 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 return false;
1820}
1821
1822
1823/// GetVal - Get a value with the specified name or ID, creating a
1824/// forward reference record if needed. This can return null if the value
1825/// exists but does not have the right type.
1826Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001827 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 // Look this name up in the normal function symbol table.
1829 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001830
Chris Lattnerdf986172009-01-02 07:01:27 +00001831 // If this is a forward reference for the value, see if we already created a
1832 // forward ref record.
1833 if (Val == 0) {
1834 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1835 I = ForwardRefVals.find(Name);
1836 if (I != ForwardRefVals.end())
1837 Val = I->second.first;
1838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001839
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 // If we have the value in the symbol table or fwd-ref table, return it.
1841 if (Val) {
1842 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001843 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001844 P.Error(Loc, "'%" + Name + "' is not a basic block");
1845 else
1846 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001847 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 return 0;
1849 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001852 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001853 P.Error(Loc, "invalid use of a non-first-class type");
1854 return 0;
1855 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 // Otherwise, create a new forward reference for this value and remember it.
1858 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001859 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001860 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 else
1862 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1865 return FwdVal;
1866}
1867
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001868Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 LocTy Loc) {
1870 // Look this name up in the normal function symbol table.
1871 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001872
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 // If this is a forward reference for the value, see if we already created a
1874 // forward ref record.
1875 if (Val == 0) {
1876 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1877 I = ForwardRefValIDs.find(ID);
1878 if (I != ForwardRefValIDs.end())
1879 Val = I->second.first;
1880 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001881
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 // If we have the value in the symbol table or fwd-ref table, return it.
1883 if (Val) {
1884 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001885 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001886 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001888 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001889 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 return 0;
1891 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Chris Lattner1afcace2011-07-09 17:41:24 +00001893 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 P.Error(Loc, "invalid use of a non-first-class type");
1895 return 0;
1896 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 // Otherwise, create a new forward reference for this value and remember it.
1899 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001900 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001901 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001902 else
1903 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001904
Chris Lattnerdf986172009-01-02 07:01:27 +00001905 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1906 return FwdVal;
1907}
1908
1909/// SetInstName - After an instruction is parsed and inserted into its
1910/// basic block, this installs its name.
1911bool LLParser::PerFunctionState::SetInstName(int NameID,
1912 const std::string &NameStr,
1913 LocTy NameLoc, Instruction *Inst) {
1914 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001915 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 if (NameID != -1 || !NameStr.empty())
1917 return P.Error(NameLoc, "instructions returning void cannot have a name");
1918 return false;
1919 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 // If this was a numbered instruction, verify that the instruction is the
1922 // expected value and resolve any forward references.
1923 if (NameStr.empty()) {
1924 // If neither a name nor an ID was specified, just use the next ID.
1925 if (NameID == -1)
1926 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927
Chris Lattnerdf986172009-01-02 07:01:27 +00001928 if (unsigned(NameID) != NumberedVals.size())
1929 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001930 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001931
Chris Lattnerdf986172009-01-02 07:01:27 +00001932 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1933 ForwardRefValIDs.find(NameID);
1934 if (FI != ForwardRefValIDs.end()) {
1935 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001936 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001937 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001939 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 ForwardRefValIDs.erase(FI);
1941 }
1942
1943 NumberedVals.push_back(Inst);
1944 return false;
1945 }
1946
1947 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1948 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1949 FI = ForwardRefVals.find(NameStr);
1950 if (FI != ForwardRefVals.end()) {
1951 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001952 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001953 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001954 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001955 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001956 ForwardRefVals.erase(FI);
1957 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 // Set the name on the instruction.
1960 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001961
Benjamin Krameraf812352010-10-16 11:28:23 +00001962 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 NameStr + "'");
1965 return false;
1966}
1967
1968/// GetBB - Get a basic block with the specified name or ID, creating a
1969/// forward reference record if needed.
1970BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1971 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001972 return cast_or_null<BasicBlock>(GetVal(Name,
1973 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001974}
1975
1976BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001977 return cast_or_null<BasicBlock>(GetVal(ID,
1978 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001979}
1980
1981/// DefineBB - Define the specified basic block, which is either named or
1982/// unnamed. If there is an error, this returns null otherwise it returns
1983/// the block being defined.
1984BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1985 LocTy Loc) {
1986 BasicBlock *BB;
1987 if (Name.empty())
1988 BB = GetBB(NumberedVals.size(), Loc);
1989 else
1990 BB = GetBB(Name, Loc);
1991 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001992
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 // Move the block to the end of the function. Forward ref'd blocks are
1994 // inserted wherever they happen to be referenced.
1995 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001996
Chris Lattnerdf986172009-01-02 07:01:27 +00001997 // Remove the block from forward ref sets.
1998 if (Name.empty()) {
1999 ForwardRefValIDs.erase(NumberedVals.size());
2000 NumberedVals.push_back(BB);
2001 } else {
2002 // BB forward references are already in the function symbol table.
2003 ForwardRefVals.erase(Name);
2004 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002005
Chris Lattnerdf986172009-01-02 07:01:27 +00002006 return BB;
2007}
2008
2009//===----------------------------------------------------------------------===//
2010// Constants.
2011//===----------------------------------------------------------------------===//
2012
2013/// ParseValID - Parse an abstract value that doesn't necessarily have a
2014/// type implied. For example, if we parse "4" we don't know what integer type
2015/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002016/// sanity. PFS is used to convert function-local operands of metadata (since
2017/// metadata operands are not just parsed here but also converted to values).
2018/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002019bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002020 ID.Loc = Lex.getLoc();
2021 switch (Lex.getKind()) {
2022 default: return TokError("expected value token");
2023 case lltok::GlobalID: // @42
2024 ID.UIntVal = Lex.getUIntVal();
2025 ID.Kind = ValID::t_GlobalID;
2026 break;
2027 case lltok::GlobalVar: // @foo
2028 ID.StrVal = Lex.getStrVal();
2029 ID.Kind = ValID::t_GlobalName;
2030 break;
2031 case lltok::LocalVarID: // %42
2032 ID.UIntVal = Lex.getUIntVal();
2033 ID.Kind = ValID::t_LocalID;
2034 break;
2035 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 ID.StrVal = Lex.getStrVal();
2037 ID.Kind = ValID::t_LocalName;
2038 break;
Dan Gohman83448032010-07-14 18:26:50 +00002039 case lltok::exclaim: // !42, !{...}, or !"foo"
2040 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002041 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002042 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002043 ID.Kind = ValID::t_APSInt;
2044 break;
2045 case lltok::APFloat:
2046 ID.APFloatVal = Lex.getAPFloatVal();
2047 ID.Kind = ValID::t_APFloat;
2048 break;
2049 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002050 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002051 ID.Kind = ValID::t_Constant;
2052 break;
2053 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002054 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 ID.Kind = ValID::t_Constant;
2056 break;
2057 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2058 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2059 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002060
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 case lltok::lbrace: {
2062 // ValID ::= '{' ConstVector '}'
2063 Lex.Lex();
2064 SmallVector<Constant*, 16> Elts;
2065 if (ParseGlobalValueVector(Elts) ||
2066 ParseToken(lltok::rbrace, "expected end of struct constant"))
2067 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002068
Chris Lattner1afcace2011-07-09 17:41:24 +00002069 ID.ConstantStructElts = new Constant*[Elts.size()];
2070 ID.UIntVal = Elts.size();
2071 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2072 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 return false;
2074 }
2075 case lltok::less: {
2076 // ValID ::= '<' ConstVector '>' --> Vector.
2077 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2078 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002079 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 SmallVector<Constant*, 16> Elts;
2082 LocTy FirstEltLoc = Lex.getLoc();
2083 if (ParseGlobalValueVector(Elts) ||
2084 (isPackedStruct &&
2085 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2086 ParseToken(lltok::greater, "expected end of constant"))
2087 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002088
Chris Lattnerdf986172009-01-02 07:01:27 +00002089 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002090 ID.ConstantStructElts = new Constant*[Elts.size()];
2091 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2092 ID.UIntVal = Elts.size();
2093 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 return false;
2095 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 if (Elts.empty())
2098 return Error(ID.Loc, "constant vector must not be empty");
2099
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002100 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002101 !Elts[0]->getType()->isFloatingPointTy() &&
2102 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002104 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002105
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 // Verify that all the vector elements have the same type.
2107 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2108 if (Elts[i]->getType() != Elts[0]->getType())
2109 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002110 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002111 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002112
Chris Lattner2ca5c862011-02-15 00:14:00 +00002113 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002114 ID.Kind = ValID::t_Constant;
2115 return false;
2116 }
2117 case lltok::lsquare: { // Array Constant
2118 Lex.Lex();
2119 SmallVector<Constant*, 16> Elts;
2120 LocTy FirstEltLoc = Lex.getLoc();
2121 if (ParseGlobalValueVector(Elts) ||
2122 ParseToken(lltok::rsquare, "expected end of array constant"))
2123 return true;
2124
2125 // Handle empty element.
2126 if (Elts.empty()) {
2127 // Use undef instead of an array because it's inconvenient to determine
2128 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002129 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 return false;
2131 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002132
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002134 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002135 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002136
Owen Andersondebcb012009-07-29 22:17:13 +00002137 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002138
Chris Lattnerdf986172009-01-02 07:01:27 +00002139 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002140 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 if (Elts[i]->getType() != Elts[0]->getType())
2142 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002143 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002144 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002145 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002146
Jay Foad26701082011-06-22 09:24:39 +00002147 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002148 ID.Kind = ValID::t_Constant;
2149 return false;
2150 }
2151 case lltok::kw_c: // c "foo"
2152 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002153 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2154 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002155 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2156 ID.Kind = ValID::t_Constant;
2157 return false;
2158
2159 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002160 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002161 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002162 Lex.Lex();
2163 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002164 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002165 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002166 ParseStringConstant(ID.StrVal) ||
2167 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 ParseToken(lltok::StringConstant, "expected constraint string"))
2169 return true;
2170 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002171 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002172 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 ID.Kind = ValID::t_InlineAsm;
2174 return false;
2175 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002176
Chris Lattner09d9ef42009-10-28 03:39:23 +00002177 case lltok::kw_blockaddress: {
2178 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2179 Lex.Lex();
2180
2181 ValID Fn, Label;
2182 LocTy FnLoc, LabelLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002183
Chris Lattner09d9ef42009-10-28 03:39:23 +00002184 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2185 ParseValID(Fn) ||
2186 ParseToken(lltok::comma, "expected comma in block address expression")||
2187 ParseValID(Label) ||
2188 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2189 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002190
Chris Lattner09d9ef42009-10-28 03:39:23 +00002191 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2192 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002193 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002194 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +00002195
Chris Lattner09d9ef42009-10-28 03:39:23 +00002196 // Make a global variable as a placeholder for this reference.
2197 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2198 false, GlobalValue::InternalLinkage,
2199 0, "");
2200 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2201 ID.ConstantVal = FwdRef;
2202 ID.Kind = ValID::t_Constant;
2203 return false;
2204 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002205
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 case lltok::kw_trunc:
2207 case lltok::kw_zext:
2208 case lltok::kw_sext:
2209 case lltok::kw_fptrunc:
2210 case lltok::kw_fpext:
2211 case lltok::kw_bitcast:
2212 case lltok::kw_uitofp:
2213 case lltok::kw_sitofp:
2214 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002215 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002219 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 Constant *SrcVal;
2221 Lex.Lex();
2222 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2223 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002224 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 ParseType(DestTy) ||
2226 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2227 return true;
2228 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2229 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002230 getTypeString(SrcVal->getType()) + "' to '" +
2231 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002232 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002233 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 ID.Kind = ValID::t_Constant;
2235 return false;
2236 }
2237 case lltok::kw_extractvalue: {
2238 Lex.Lex();
2239 Constant *Val;
2240 SmallVector<unsigned, 4> Indices;
2241 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2242 ParseGlobalTypeAndValue(Val) ||
2243 ParseIndexList(Indices) ||
2244 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2245 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002246
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002247 if (!Val->getType()->isAggregateType())
2248 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002249 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002251 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 ID.Kind = ValID::t_Constant;
2253 return false;
2254 }
2255 case lltok::kw_insertvalue: {
2256 Lex.Lex();
2257 Constant *Val0, *Val1;
2258 SmallVector<unsigned, 4> Indices;
2259 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2260 ParseGlobalTypeAndValue(Val0) ||
2261 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2262 ParseGlobalTypeAndValue(Val1) ||
2263 ParseIndexList(Indices) ||
2264 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2265 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002266 if (!Val0->getType()->isAggregateType())
2267 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002268 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002269 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002270 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002271 ID.Kind = ValID::t_Constant;
2272 return false;
2273 }
2274 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002275 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 unsigned PredVal, Opc = Lex.getUIntVal();
2277 Constant *Val0, *Val1;
2278 Lex.Lex();
2279 if (ParseCmpPredicate(PredVal, Opc) ||
2280 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2281 ParseGlobalTypeAndValue(Val0) ||
2282 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2283 ParseGlobalTypeAndValue(Val1) ||
2284 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2285 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002286
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 if (Val0->getType() != Val1->getType())
2288 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002289
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002291
Chris Lattnerdf986172009-01-02 07:01:27 +00002292 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002293 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002294 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002295 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002296 } else {
2297 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002298 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002299 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002301 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 }
2303 ID.Kind = ValID::t_Constant;
2304 return false;
2305 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002306
Chris Lattnerdf986172009-01-02 07:01:27 +00002307 // Binary Operators.
2308 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002309 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002311 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002313 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 case lltok::kw_udiv:
2315 case lltok::kw_sdiv:
2316 case lltok::kw_fdiv:
2317 case lltok::kw_urem:
2318 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002319 case lltok::kw_frem:
2320 case lltok::kw_shl:
2321 case lltok::kw_lshr:
2322 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002323 bool NUW = false;
2324 bool NSW = false;
2325 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002326 unsigned Opc = Lex.getUIntVal();
2327 Constant *Val0, *Val1;
2328 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002329 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002330 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2331 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002332 if (EatIfPresent(lltok::kw_nuw))
2333 NUW = true;
2334 if (EatIfPresent(lltok::kw_nsw)) {
2335 NSW = true;
2336 if (EatIfPresent(lltok::kw_nuw))
2337 NUW = true;
2338 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002339 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2340 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002341 if (EatIfPresent(lltok::kw_exact))
2342 Exact = true;
2343 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2345 ParseGlobalTypeAndValue(Val0) ||
2346 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2347 ParseGlobalTypeAndValue(Val1) ||
2348 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2349 return true;
2350 if (Val0->getType() != Val1->getType())
2351 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002352 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002353 if (NUW)
2354 return Error(ModifierLoc, "nuw only applies to integer operations");
2355 if (NSW)
2356 return Error(ModifierLoc, "nsw only applies to integer operations");
2357 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002358 // Check that the type is valid for the operator.
2359 switch (Opc) {
2360 case Instruction::Add:
2361 case Instruction::Sub:
2362 case Instruction::Mul:
2363 case Instruction::UDiv:
2364 case Instruction::SDiv:
2365 case Instruction::URem:
2366 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002367 case Instruction::Shl:
2368 case Instruction::AShr:
2369 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002370 if (!Val0->getType()->isIntOrIntVectorTy())
2371 return Error(ID.Loc, "constexpr requires integer operands");
2372 break;
2373 case Instruction::FAdd:
2374 case Instruction::FSub:
2375 case Instruction::FMul:
2376 case Instruction::FDiv:
2377 case Instruction::FRem:
2378 if (!Val0->getType()->isFPOrFPVectorTy())
2379 return Error(ID.Loc, "constexpr requires fp operands");
2380 break;
2381 default: llvm_unreachable("Unknown binary operator!");
2382 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002383 unsigned Flags = 0;
2384 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2385 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002386 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002387 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002388 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002389 ID.Kind = ValID::t_Constant;
2390 return false;
2391 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002392
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 case lltok::kw_and:
2395 case lltok::kw_or:
2396 case lltok::kw_xor: {
2397 unsigned Opc = Lex.getUIntVal();
2398 Constant *Val0, *Val1;
2399 Lex.Lex();
2400 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2401 ParseGlobalTypeAndValue(Val0) ||
2402 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2403 ParseGlobalTypeAndValue(Val1) ||
2404 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2405 return true;
2406 if (Val0->getType() != Val1->getType())
2407 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002408 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 return Error(ID.Loc,
2410 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002411 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002412 ID.Kind = ValID::t_Constant;
2413 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002414 }
2415
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 case lltok::kw_getelementptr:
2417 case lltok::kw_shufflevector:
2418 case lltok::kw_insertelement:
2419 case lltok::kw_extractelement:
2420 case lltok::kw_select: {
2421 unsigned Opc = Lex.getUIntVal();
2422 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002423 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002424 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002425 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002426 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002427 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2428 ParseGlobalValueVector(Elts) ||
2429 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2430 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002431
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002433 if (Elts.size() == 0 ||
2434 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002436
Jay Foaddab3d292011-07-21 14:31:17 +00002437 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002438 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002440 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2441 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 } else if (Opc == Instruction::Select) {
2443 if (Elts.size() != 3)
2444 return Error(ID.Loc, "expected three operands to select");
2445 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2446 Elts[2]))
2447 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002448 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002449 } else if (Opc == Instruction::ShuffleVector) {
2450 if (Elts.size() != 3)
2451 return Error(ID.Loc, "expected three operands to shufflevector");
2452 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2453 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002454 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002455 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002456 } else if (Opc == Instruction::ExtractElement) {
2457 if (Elts.size() != 2)
2458 return Error(ID.Loc, "expected two operands to extractelement");
2459 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2460 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002461 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002462 } else {
2463 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2464 if (Elts.size() != 3)
2465 return Error(ID.Loc, "expected three operands to insertelement");
2466 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2467 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002468 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002469 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002470 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002471
Chris Lattnerdf986172009-01-02 07:01:27 +00002472 ID.Kind = ValID::t_Constant;
2473 return false;
2474 }
2475 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002476
Chris Lattnerdf986172009-01-02 07:01:27 +00002477 Lex.Lex();
2478 return false;
2479}
2480
2481/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002482bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002483 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002484 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002485 Value *V = NULL;
2486 bool Parsed = ParseValID(ID) ||
2487 ConvertValIDToValue(Ty, ID, V, NULL);
2488 if (V && !(C = dyn_cast<Constant>(V)))
2489 return Error(ID.Loc, "global values must be constants");
2490 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002491}
2492
Victor Hernandez92f238d2010-01-11 22:31:58 +00002493bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002494 Type *Ty = 0;
2495 return ParseType(Ty) ||
2496 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002497}
2498
2499/// ParseGlobalValueVector
2500/// ::= /*empty*/
2501/// ::= TypeAndValue (',' TypeAndValue)*
2502bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2503 // Empty list.
2504 if (Lex.getKind() == lltok::rbrace ||
2505 Lex.getKind() == lltok::rsquare ||
2506 Lex.getKind() == lltok::greater ||
2507 Lex.getKind() == lltok::rparen)
2508 return false;
2509
2510 Constant *C;
2511 if (ParseGlobalTypeAndValue(C)) return true;
2512 Elts.push_back(C);
2513
2514 while (EatIfPresent(lltok::comma)) {
2515 if (ParseGlobalTypeAndValue(C)) return true;
2516 Elts.push_back(C);
2517 }
2518
2519 return false;
2520}
2521
Dan Gohman309b3af2010-08-24 02:24:03 +00002522bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2523 assert(Lex.getKind() == lltok::lbrace);
2524 Lex.Lex();
2525
2526 SmallVector<Value*, 16> Elts;
2527 if (ParseMDNodeVector(Elts, PFS) ||
2528 ParseToken(lltok::rbrace, "expected end of metadata node"))
2529 return true;
2530
Jay Foadec9186b2011-04-21 19:59:31 +00002531 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002532 ID.Kind = ValID::t_MDNode;
2533 return false;
2534}
2535
Dan Gohman83448032010-07-14 18:26:50 +00002536/// ParseMetadataValue
2537/// ::= !42
2538/// ::= !{...}
2539/// ::= !"string"
2540bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2541 assert(Lex.getKind() == lltok::exclaim);
2542 Lex.Lex();
2543
2544 // MDNode:
2545 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002546 if (Lex.getKind() == lltok::lbrace)
2547 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002548
2549 // Standalone metadata reference
2550 // !42
2551 if (Lex.getKind() == lltok::APSInt) {
2552 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2553 ID.Kind = ValID::t_MDNode;
2554 return false;
2555 }
2556
2557 // MDString:
2558 // ::= '!' STRINGCONSTANT
2559 if (ParseMDString(ID.MDStringVal)) return true;
2560 ID.Kind = ValID::t_MDString;
2561 return false;
2562}
2563
Victor Hernandez92f238d2010-01-11 22:31:58 +00002564
2565//===----------------------------------------------------------------------===//
2566// Function Parsing.
2567//===----------------------------------------------------------------------===//
2568
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002569bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002570 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002571 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002572 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002573
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002575 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002576 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2577 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2578 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002579 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002580 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2581 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2582 return (V == 0);
2583 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002584 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman407a6162012-11-15 22:34:00 +00002585 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002586 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2587 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2588 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002589 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002590 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002591 return false;
2592 }
2593 case ValID::t_MDNode:
2594 if (!Ty->isMetadataTy())
2595 return Error(ID.Loc, "metadata value must have metadata type");
2596 V = ID.MDNodeVal;
2597 return false;
2598 case ValID::t_MDString:
2599 if (!Ty->isMetadataTy())
2600 return Error(ID.Loc, "metadata value must have metadata type");
2601 V = ID.MDStringVal;
2602 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002603 case ValID::t_GlobalName:
2604 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2605 return V == 0;
2606 case ValID::t_GlobalID:
2607 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2608 return V == 0;
2609 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002610 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002612 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002613 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002614 return false;
2615 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002616 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002617 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2618 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002619
Dan Gohmance163392011-12-17 00:04:22 +00002620 // The lexer has no type info, so builds all half, float, and double FP
2621 // constants as double. Fix this here. Long double does not need this.
2622 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002623 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002624 if (Ty->isHalfTy())
2625 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2626 &Ignored);
2627 else if (Ty->isFloatTy())
2628 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2629 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002631 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattner959873d2009-01-05 18:24:23 +00002633 if (V->getType() != Ty)
2634 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002635 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002636
Chris Lattnerdf986172009-01-02 07:01:27 +00002637 return false;
2638 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002639 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002641 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 return false;
2643 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002644 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002645 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002646 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002647 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002649 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002650 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002651 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002652 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002653 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002654 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002655 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002656 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002657 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002658 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002659 return false;
2660 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002661 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002662 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002663
Chris Lattnerdf986172009-01-02 07:01:27 +00002664 V = ID.ConstantVal;
2665 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002666 case ValID::t_ConstantStruct:
2667 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002668 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002669 if (ST->getNumElements() != ID.UIntVal)
2670 return Error(ID.Loc,
2671 "initializer with struct type has wrong # elements");
2672 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2673 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman407a6162012-11-15 22:34:00 +00002674
Chris Lattner1afcace2011-07-09 17:41:24 +00002675 // Verify that the elements are compatible with the structtype.
2676 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2677 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2678 return Error(ID.Loc, "element " + Twine(i) +
2679 " of struct initializer doesn't match struct element type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002680
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002681 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2682 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002683 } else
2684 return Error(ID.Loc, "constant expression type mismatch");
2685 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002686 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002687 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002688}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002689
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002690bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 V = 0;
2692 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002693 return ParseValID(ID, PFS) ||
2694 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002695}
2696
Chris Lattner1afcace2011-07-09 17:41:24 +00002697bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2698 Type *Ty = 0;
2699 return ParseType(Ty) ||
2700 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002701}
2702
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002703bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2704 PerFunctionState &PFS) {
2705 Value *V;
2706 Loc = Lex.getLoc();
2707 if (ParseTypeAndValue(V, PFS)) return true;
2708 if (!isa<BasicBlock>(V))
2709 return Error(Loc, "expected a basic block");
2710 BB = cast<BasicBlock>(V);
2711 return false;
2712}
2713
2714
Chris Lattnerdf986172009-01-02 07:01:27 +00002715/// FunctionHeader
2716/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002717/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002718/// OptionalAlign OptGC
2719bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2720 // Parse the linkage.
2721 LocTy LinkageLoc = Lex.getLoc();
2722 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002724 unsigned Visibility;
Bill Wendling702cc912012-10-15 20:35:56 +00002725 AttrBuilder RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002726 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002727 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 LocTy RetTypeLoc = Lex.getLoc();
2729 if (ParseOptionalLinkage(Linkage) ||
2730 ParseOptionalVisibility(Visibility) ||
2731 ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002732 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002733 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 return true;
2735
2736 // Verify that the linkage is ok.
2737 switch ((GlobalValue::LinkageTypes)Linkage) {
2738 case GlobalValue::ExternalLinkage:
2739 break; // always ok.
2740 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002741 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002742 if (isDefine)
2743 return Error(LinkageLoc, "invalid linkage for function definition");
2744 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002745 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002746 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002747 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002749 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002750 case GlobalValue::LinkOnceAnyLinkage:
2751 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002752 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002753 case GlobalValue::WeakAnyLinkage:
2754 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002755 case GlobalValue::DLLExportLinkage:
2756 if (!isDefine)
2757 return Error(LinkageLoc, "invalid linkage for function declaration");
2758 break;
2759 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002760 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 return Error(LinkageLoc, "invalid function linkage type");
2762 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002763
Chris Lattner1afcace2011-07-09 17:41:24 +00002764 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002768
2769 std::string FunctionName;
2770 if (Lex.getKind() == lltok::GlobalVar) {
2771 FunctionName = Lex.getStrVal();
2772 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2773 unsigned NameID = Lex.getUIntVal();
2774
2775 if (NameID != NumberedVals.size())
2776 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002777 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002778 } else {
2779 return TokError("expected function name");
2780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002782 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002783
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002784 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002785 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002786
Chris Lattner1afcace2011-07-09 17:41:24 +00002787 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002788 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00002789 AttrBuilder FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002790 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002791 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002792 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002793 bool UnnamedAddr;
2794 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002795
Chris Lattner1afcace2011-07-09 17:41:24 +00002796 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002797 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2798 &UnnamedAddrLoc) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002799 ParseOptionalFuncAttrs(FuncAttrs) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002800 (EatIfPresent(lltok::kw_section) &&
2801 ParseStringConstant(Section)) ||
2802 ParseOptionalAlignment(Alignment) ||
2803 (EatIfPresent(lltok::kw_gc) &&
2804 ParseStringConstant(GC)))
2805 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002806
2807 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00002808 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002809 Alignment = FuncAttrs.getAlignment();
Bill Wendling034b94b2012-12-19 07:18:57 +00002810 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00002811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002812
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 // Okay, if we got here, the function is syntactically valid. Convert types
2814 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002815 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002817
Bill Wendlinge603fe42012-09-19 23:54:18 +00002818 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002819 Attrs.push_back(
Bill Wendling99faa3b2012-12-07 23:16:57 +00002820 AttributeWithIndex::get(AttributeSet::ReturnIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00002821 Attribute::get(RetType->getContext(),
Bill Wendling07aae2e2012-10-15 07:29:08 +00002822 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002825 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlinge603fe42012-09-19 23:54:18 +00002826 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2828 }
2829
Bill Wendlinge603fe42012-09-19 23:54:18 +00002830 if (FuncAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002831 Attrs.push_back(
Bill Wendling99faa3b2012-12-07 23:16:57 +00002832 AttributeWithIndex::get(AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00002833 Attribute::get(RetType->getContext(),
Bill Wendling07aae2e2012-10-15 07:29:08 +00002834 FuncAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00002835
Bill Wendling99faa3b2012-12-07 23:16:57 +00002836 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002837
Bill Wendling94e94b32012-12-30 13:50:49 +00002838 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002839 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2840
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002841 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002842 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002843 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002844
2845 Fn = 0;
2846 if (!FunctionName.empty()) {
2847 // If this was a definition of a forward reference, remove the definition
2848 // from the forward reference table and fill in the forward ref.
2849 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2850 ForwardRefVals.find(FunctionName);
2851 if (FRVI != ForwardRefVals.end()) {
2852 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00002853 if (!Fn)
2854 return Error(FRVI->second.second, "invalid forward reference to "
2855 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002856 if (Fn->getType() != PFT)
2857 return Error(FRVI->second.second, "invalid forward reference to "
2858 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman407a6162012-11-15 22:34:00 +00002859
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 ForwardRefVals.erase(FRVI);
2861 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002862 // Reject redefinitions.
2863 return Error(NameLoc, "invalid redefinition of function '" +
2864 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002865 } else if (M->getNamedValue(FunctionName)) {
2866 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002867 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868
Dan Gohman41905542009-08-29 23:37:49 +00002869 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002870 // If this is a definition of a forward referenced function, make sure the
2871 // types agree.
2872 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2873 = ForwardRefValIDs.find(NumberedVals.size());
2874 if (I != ForwardRefValIDs.end()) {
2875 Fn = cast<Function>(I->second.first);
2876 if (Fn->getType() != PFT)
2877 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002878 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002879 ForwardRefValIDs.erase(I);
2880 }
2881 }
2882
2883 if (Fn == 0)
2884 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2885 else // Move the forward-reference to the correct spot in the module.
2886 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2887
2888 if (FunctionName.empty())
2889 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnerdf986172009-01-02 07:01:27 +00002891 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2892 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2893 Fn->setCallingConv(CC);
2894 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002895 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 Fn->setAlignment(Alignment);
2897 Fn->setSection(Section);
2898 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002899
Chris Lattnerdf986172009-01-02 07:01:27 +00002900 // Add all of the arguments we parsed to the function.
2901 Function::arg_iterator ArgIt = Fn->arg_begin();
2902 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2903 // If the argument has a name, insert it into the argument symbol table.
2904 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905
Chris Lattnerdf986172009-01-02 07:01:27 +00002906 // Set the name, if it conflicted, it will be auto-renamed.
2907 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002908
Benjamin Krameraf812352010-10-16 11:28:23 +00002909 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002910 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2911 ArgList[i].Name + "'");
2912 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002913
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 return false;
2915}
2916
2917
2918/// ParseFunctionBody
2919/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002920///
2921bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002922 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 return TokError("expected '{' in function body");
2924 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002925
Chris Lattner09d9ef42009-10-28 03:39:23 +00002926 int FunctionNumber = -1;
2927 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman407a6162012-11-15 22:34:00 +00002928
Chris Lattner09d9ef42009-10-28 03:39:23 +00002929 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002930
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002931 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002932 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002933 return TokError("function body requires at least one basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +00002934
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002935 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002936 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002937
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 // Eat the }.
2939 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002940
Chris Lattnerdf986172009-01-02 07:01:27 +00002941 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002942 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002943}
2944
2945/// ParseBasicBlock
2946/// ::= LabelStr? Instruction*
2947bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2948 // If this basic block starts out with a name, remember it.
2949 std::string Name;
2950 LocTy NameLoc = Lex.getLoc();
2951 if (Lex.getKind() == lltok::LabelStr) {
2952 Name = Lex.getStrVal();
2953 Lex.Lex();
2954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002955
Chris Lattnerdf986172009-01-02 07:01:27 +00002956 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2957 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002958
Chris Lattnerdf986172009-01-02 07:01:27 +00002959 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002960
Chris Lattnerdf986172009-01-02 07:01:27 +00002961 // Parse the instructions in this block until we get a terminator.
2962 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002963 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002964 do {
2965 // This instruction may have three possibilities for a name: a) none
2966 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2967 LocTy NameLoc = Lex.getLoc();
2968 int NameID = -1;
2969 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002970
Chris Lattnerdf986172009-01-02 07:01:27 +00002971 if (Lex.getKind() == lltok::LocalVarID) {
2972 NameID = Lex.getUIntVal();
2973 Lex.Lex();
2974 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2975 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002976 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002977 NameStr = Lex.getStrVal();
2978 Lex.Lex();
2979 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2980 return true;
2981 }
Devang Patelf633a062009-09-17 23:04:48 +00002982
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002983 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002984 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002985 case InstError: return true;
2986 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002987 BB->getInstList().push_back(Inst);
2988
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002989 // With a normal result, we check to see if the instruction is followed by
2990 // a comma and metadata.
2991 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002992 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002993 return true;
2994 break;
2995 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002996 BB->getInstList().push_back(Inst);
2997
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002998 // If the instruction parser ate an extra comma at the end of it, it
2999 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00003000 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003001 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003002 break;
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003003 }
Devang Patelf633a062009-09-17 23:04:48 +00003004
Chris Lattnerdf986172009-01-02 07:01:27 +00003005 // Set the name on the instruction.
3006 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3007 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003008
Chris Lattnerdf986172009-01-02 07:01:27 +00003009 return false;
3010}
3011
3012//===----------------------------------------------------------------------===//
3013// Instruction Parsing.
3014//===----------------------------------------------------------------------===//
3015
3016/// ParseInstruction - Parse one of the many different instructions.
3017///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003018int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3019 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003020 lltok::Kind Token = Lex.getKind();
3021 if (Token == lltok::Eof)
3022 return TokError("found end of file when expecting more instructions");
3023 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003024 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003025 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003026
Chris Lattnerdf986172009-01-02 07:01:27 +00003027 switch (Token) {
3028 default: return Error(Loc, "expected instruction opcode");
3029 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003030 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003031 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3032 case lltok::kw_br: return ParseBr(Inst, PFS);
3033 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003034 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003036 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003037 // Binary Operators.
3038 case lltok::kw_add:
3039 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00003040 case lltok::kw_mul:
3041 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00003042 bool NUW = EatIfPresent(lltok::kw_nuw);
3043 bool NSW = EatIfPresent(lltok::kw_nsw);
3044 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman407a6162012-11-15 22:34:00 +00003045
Chris Lattnerf067d582011-02-07 16:40:21 +00003046 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003047
Chris Lattnerf067d582011-02-07 16:40:21 +00003048 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3049 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3050 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003051 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003052 case lltok::kw_fadd:
3053 case lltok::kw_fsub:
Michael Ilseman15c13d32012-11-27 00:42:44 +00003054 case lltok::kw_fmul:
3055 case lltok::kw_fdiv:
3056 case lltok::kw_frem: {
3057 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3058 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3059 if (Res != 0)
3060 return Res;
3061 if (FMF.any())
3062 Inst->setFastMathFlags(FMF);
3063 return 0;
3064 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003065
Chris Lattner35bda892011-02-06 21:44:57 +00003066 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00003067 case lltok::kw_udiv:
3068 case lltok::kw_lshr:
3069 case lltok::kw_ashr: {
3070 bool Exact = EatIfPresent(lltok::kw_exact);
3071
3072 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3073 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3074 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003075 }
3076
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003078 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 case lltok::kw_and:
3080 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003081 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003083 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 // Casts.
3085 case lltok::kw_trunc:
3086 case lltok::kw_zext:
3087 case lltok::kw_sext:
3088 case lltok::kw_fptrunc:
3089 case lltok::kw_fpext:
3090 case lltok::kw_bitcast:
3091 case lltok::kw_uitofp:
3092 case lltok::kw_sitofp:
3093 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003094 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003096 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 // Other.
3098 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003099 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003100 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3101 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3102 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3103 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003104 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003105 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3106 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3107 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003108 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003109 case lltok::kw_load: return ParseLoad(Inst, PFS);
3110 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003111 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3112 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003113 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003114 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3115 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3116 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3117 }
3118}
3119
3120/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3121bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003122 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00003124 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00003125 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3126 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3127 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3128 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3129 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3130 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3131 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3132 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3133 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3134 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3135 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3136 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3137 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3138 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3139 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3140 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3141 }
3142 } else {
3143 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00003144 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00003145 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3146 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3147 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3148 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3149 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3150 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3151 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3152 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3153 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3154 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3155 }
3156 }
3157 Lex.Lex();
3158 return false;
3159}
3160
3161//===----------------------------------------------------------------------===//
3162// Terminator Instructions.
3163//===----------------------------------------------------------------------===//
3164
3165/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003166/// ::= 'ret' void (',' !dbg, !1)*
3167/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003168bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003169 PerFunctionState &PFS) {
3170 SMLoc TypeLoc = Lex.getLoc();
3171 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003172 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003173
Chris Lattner1afcace2011-07-09 17:41:24 +00003174 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman407a6162012-11-15 22:34:00 +00003175
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003176 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003177 if (!ResType->isVoidTy())
3178 return Error(TypeLoc, "value doesn't match function result type '" +
3179 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003180
Owen Anderson1d0be152009-08-13 21:58:54 +00003181 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003182 return false;
3183 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003184
Chris Lattnerdf986172009-01-02 07:01:27 +00003185 Value *RV;
3186 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003187
Chris Lattner1afcace2011-07-09 17:41:24 +00003188 if (ResType != RV->getType())
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, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003193 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003194}
3195
3196
3197/// ParseBr
3198/// ::= 'br' TypeAndValue
3199/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3200bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3201 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003202 Value *Op0;
3203 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003205
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3207 Inst = BranchInst::Create(BB);
3208 return false;
3209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003210
Owen Anderson1d0be152009-08-13 21:58:54 +00003211 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003213
Chris Lattnerdf986172009-01-02 07:01:27 +00003214 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003215 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003216 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003217 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003218 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003219
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003220 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 return false;
3222}
3223
3224/// ParseSwitch
3225/// Instruction
3226/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3227/// JumpTable
3228/// ::= (TypeAndValue ',' TypeAndValue)*
3229bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3230 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003231 Value *Cond;
3232 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003233 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3234 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003235 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003236 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3237 return true;
3238
Duncan Sands1df98592010-02-16 11:11:14 +00003239 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 // Parse the jump table pairs.
3243 SmallPtrSet<Value*, 32> SeenCases;
3244 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3245 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003246 Value *Constant;
3247 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003248
Chris Lattnerdf986172009-01-02 07:01:27 +00003249 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3250 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003251 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003253
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 if (!SeenCases.insert(Constant))
3255 return Error(CondLoc, "duplicate case value in switch");
3256 if (!isa<ConstantInt>(Constant))
3257 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003258
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003259 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003260 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003261
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003263
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003264 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003265 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3266 SI->addCase(Table[i].first, Table[i].second);
3267 Inst = SI;
3268 return false;
3269}
3270
Chris Lattnerab21db72009-10-28 00:19:10 +00003271/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003272/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003273/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3274bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275 LocTy AddrLoc;
3276 Value *Address;
3277 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003278 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3279 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003280 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003281
Duncan Sands1df98592010-02-16 11:11:14 +00003282 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003283 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman407a6162012-11-15 22:34:00 +00003284
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003285 // Parse the destination list.
3286 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman407a6162012-11-15 22:34:00 +00003287
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003288 if (Lex.getKind() != lltok::rsquare) {
3289 BasicBlock *DestBB;
3290 if (ParseTypeAndBasicBlock(DestBB, PFS))
3291 return true;
3292 DestList.push_back(DestBB);
Michael Ilseman407a6162012-11-15 22:34:00 +00003293
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003294 while (EatIfPresent(lltok::comma)) {
3295 if (ParseTypeAndBasicBlock(DestBB, PFS))
3296 return true;
3297 DestList.push_back(DestBB);
3298 }
3299 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003300
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003301 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3302 return true;
3303
Chris Lattnerab21db72009-10-28 00:19:10 +00003304 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003305 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3306 IBI->addDestination(DestList[i]);
3307 Inst = IBI;
3308 return false;
3309}
3310
3311
Chris Lattnerdf986172009-01-02 07:01:27 +00003312/// ParseInvoke
3313/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3314/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3315bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3316 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00003317 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003318 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003319 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003320 LocTy RetTypeLoc;
3321 ValID CalleeID;
3322 SmallVector<ParamInfo, 16> ArgList;
3323
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003324 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 if (ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003326 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003327 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003328 ParseValID(CalleeID) ||
3329 ParseParameterList(ArgList, PFS) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003330 ParseOptionalFuncAttrs(FnAttrs) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003331 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003332 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003334 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003335 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003336
Chris Lattnerdf986172009-01-02 07:01:27 +00003337 // If RetType is a non-function pointer type, then this is the short syntax
3338 // for the call, which means that RetType is just the return type. Infer the
3339 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003340 PointerType *PFTy = 0;
3341 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003342 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3343 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3344 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003345 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3347 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003348
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 if (!FunctionType::isValidReturnType(RetType))
3350 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003351
Owen Andersondebcb012009-07-29 22:17:13 +00003352 Ty = FunctionType::get(RetType, ParamTypes, false);
3353 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003355
Chris Lattnerdf986172009-01-02 07:01:27 +00003356 // Look up the callee.
3357 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003358 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Bill Wendling034b94b2012-12-19 07:18:57 +00003360 // Set up the Attribute for the function.
Chris Lattnerdf986172009-01-02 07:01:27 +00003361 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003362 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003363 Attrs.push_back(
Bill Wendling99faa3b2012-12-07 23:16:57 +00003364 AttributeWithIndex::get(AttributeSet::ReturnIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003365 Attribute::get(Callee->getContext(),
Bill Wendling07aae2e2012-10-15 07:29:08 +00003366 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003367
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003369
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 // Loop through FunctionType's arguments and ensure they are specified
3371 // correctly. Also, gather any parameter attributes.
3372 FunctionType::param_iterator I = Ty->param_begin();
3373 FunctionType::param_iterator E = Ty->param_end();
3374 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003375 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 if (I != E) {
3377 ExpectedTy = *I++;
3378 } else if (!Ty->isVarArg()) {
3379 return Error(ArgList[i].Loc, "too many arguments specified");
3380 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003381
Chris Lattnerdf986172009-01-02 07:01:27 +00003382 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3383 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003384 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003386 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3388 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 if (I != E)
3391 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003392
Bill Wendlinge603fe42012-09-19 23:54:18 +00003393 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003394 Attrs.push_back(
Bill Wendling99faa3b2012-12-07 23:16:57 +00003395 AttributeWithIndex::get(AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003396 Attribute::get(Callee->getContext(),
Bill Wendling07aae2e2012-10-15 07:29:08 +00003397 FnAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003398
Bill Wendling034b94b2012-12-19 07:18:57 +00003399 // Finish off the Attribute and check them
Bill Wendling99faa3b2012-12-07 23:16:57 +00003400 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003401
Jay Foada3efbb12011-07-15 08:37:34 +00003402 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 II->setCallingConv(CC);
3404 II->setAttributes(PAL);
3405 Inst = II;
3406 return false;
3407}
3408
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003409/// ParseResume
3410/// ::= 'resume' TypeAndValue
3411bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3412 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003413 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3414 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003415
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003416 ResumeInst *RI = ResumeInst::Create(Exn);
3417 Inst = RI;
3418 return false;
3419}
Chris Lattnerdf986172009-01-02 07:01:27 +00003420
3421//===----------------------------------------------------------------------===//
3422// Binary Operators.
3423//===----------------------------------------------------------------------===//
3424
3425/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003426/// ::= ArithmeticOps TypeAndValue ',' Value
3427///
3428/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3429/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003430bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003431 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003432 LocTy Loc; Value *LHS, *RHS;
3433 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3434 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3435 ParseValue(LHS->getType(), RHS, PFS))
3436 return true;
3437
Chris Lattnere914b592009-01-05 08:24:46 +00003438 bool Valid;
3439 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003440 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003441 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003442 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3443 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003444 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003445 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3446 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003447 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003448
Chris Lattnere914b592009-01-05 08:24:46 +00003449 if (!Valid)
3450 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003451
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3453 return false;
3454}
3455
3456/// ParseLogical
3457/// ::= ArithmeticOps TypeAndValue ',' Value {
3458bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3459 unsigned Opc) {
3460 LocTy Loc; Value *LHS, *RHS;
3461 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3462 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3463 ParseValue(LHS->getType(), RHS, PFS))
3464 return true;
3465
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003466 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003467 return Error(Loc,"instruction requires integer or integer vector operands");
3468
3469 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3470 return false;
3471}
3472
3473
3474/// ParseCompare
3475/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3476/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003477bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3478 unsigned Opc) {
3479 // Parse the integer/fp comparison predicate.
3480 LocTy Loc;
3481 unsigned Pred;
3482 Value *LHS, *RHS;
3483 if (ParseCmpPredicate(Pred, Opc) ||
3484 ParseTypeAndValue(LHS, Loc, PFS) ||
3485 ParseToken(lltok::comma, "expected ',' after compare value") ||
3486 ParseValue(LHS->getType(), RHS, PFS))
3487 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003488
Chris Lattnerdf986172009-01-02 07:01:27 +00003489 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003490 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003491 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003492 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003493 } else {
3494 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003495 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003496 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003497 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003498 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003499 }
3500 return false;
3501}
3502
3503//===----------------------------------------------------------------------===//
3504// Other Instructions.
3505//===----------------------------------------------------------------------===//
3506
3507
3508/// ParseCast
3509/// ::= CastOpc TypeAndValue 'to' Type
3510bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3511 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003512 LocTy Loc;
3513 Value *Op;
3514 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003515 if (ParseTypeAndValue(Op, Loc, PFS) ||
3516 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3517 ParseType(DestTy))
3518 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003519
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003520 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3521 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003523 getTypeString(Op->getType()) + "' to '" +
3524 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003525 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3527 return false;
3528}
3529
3530/// ParseSelect
3531/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3532bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3533 LocTy Loc;
3534 Value *Op0, *Op1, *Op2;
3535 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3536 ParseToken(lltok::comma, "expected ',' after select condition") ||
3537 ParseTypeAndValue(Op1, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after select value") ||
3539 ParseTypeAndValue(Op2, PFS))
3540 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003541
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3543 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003544
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 Inst = SelectInst::Create(Op0, Op1, Op2);
3546 return false;
3547}
3548
Chris Lattner0088a5c2009-01-05 08:18:44 +00003549/// ParseVA_Arg
3550/// ::= 'va_arg' TypeAndValue ',' Type
3551bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003552 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003553 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003554 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003555 if (ParseTypeAndValue(Op, PFS) ||
3556 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003557 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003559
Chris Lattner0088a5c2009-01-05 08:18:44 +00003560 if (!EltTy->isFirstClassType())
3561 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003562
3563 Inst = new VAArgInst(Op, EltTy);
3564 return false;
3565}
3566
3567/// ParseExtractElement
3568/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3569bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3570 LocTy Loc;
3571 Value *Op0, *Op1;
3572 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3573 ParseToken(lltok::comma, "expected ',' after extract value") ||
3574 ParseTypeAndValue(Op1, PFS))
3575 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003576
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3578 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Eric Christophera3500da2009-07-25 02:28:41 +00003580 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003581 return false;
3582}
3583
3584/// ParseInsertElement
3585/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3586bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3587 LocTy Loc;
3588 Value *Op0, *Op1, *Op2;
3589 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3590 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3591 ParseTypeAndValue(Op1, PFS) ||
3592 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3593 ParseTypeAndValue(Op2, PFS))
3594 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003595
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003597 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003598
Chris Lattnerdf986172009-01-02 07:01:27 +00003599 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3600 return false;
3601}
3602
3603/// ParseShuffleVector
3604/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3605bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3606 LocTy Loc;
3607 Value *Op0, *Op1, *Op2;
3608 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3609 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3610 ParseTypeAndValue(Op1, PFS) ||
3611 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3612 ParseTypeAndValue(Op2, PFS))
3613 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003614
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003616 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003617
Chris Lattnerdf986172009-01-02 07:01:27 +00003618 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3619 return false;
3620}
3621
3622/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003623/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003624int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003625 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003626 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003627
Chris Lattner1afcace2011-07-09 17:41:24 +00003628 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003629 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3630 ParseValue(Ty, Op0, PFS) ||
3631 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003632 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003633 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3634 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003635
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003636 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3638 while (1) {
3639 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003640
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003641 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003642 break;
3643
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003644 if (Lex.getKind() == lltok::MetadataVar) {
3645 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003646 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003647 }
Devang Patela43d46f2009-10-16 18:45:49 +00003648
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003649 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003650 ParseValue(Ty, Op0, PFS) ||
3651 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003652 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003653 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3654 return true;
3655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003656
Chris Lattnerdf986172009-01-02 07:01:27 +00003657 if (!Ty->isFirstClassType())
3658 return Error(TypeLoc, "phi node must have first class type");
3659
Jay Foad3ecfc862011-03-30 11:28:46 +00003660 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003661 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3662 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3663 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003664 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003665}
3666
Bill Wendlinge6e88262011-08-12 20:24:12 +00003667/// ParseLandingPad
3668/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3669/// Clause
3670/// ::= 'catch' TypeAndValue
3671/// ::= 'filter'
3672/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3673bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3674 Type *Ty = 0; LocTy TyLoc;
3675 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003676
3677 if (ParseType(Ty, TyLoc) ||
3678 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3679 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3680 return true;
3681
3682 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3683 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3684
3685 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3686 LandingPadInst::ClauseType CT;
3687 if (EatIfPresent(lltok::kw_catch))
3688 CT = LandingPadInst::Catch;
3689 else if (EatIfPresent(lltok::kw_filter))
3690 CT = LandingPadInst::Filter;
3691 else
3692 return TokError("expected 'catch' or 'filter' clause type");
3693
3694 Value *V; LocTy VLoc;
3695 if (ParseTypeAndValue(V, VLoc, PFS)) {
3696 delete LP;
3697 return true;
3698 }
3699
Bill Wendling746c8822011-08-12 20:52:25 +00003700 // A 'catch' type expects a non-array constant. A filter clause expects an
3701 // array constant.
3702 if (CT == LandingPadInst::Catch) {
3703 if (isa<ArrayType>(V->getType()))
3704 Error(VLoc, "'catch' clause has an invalid type");
3705 } else {
3706 if (!isa<ArrayType>(V->getType()))
3707 Error(VLoc, "'filter' clause has an invalid type");
3708 }
3709
Bill Wendlinge6e88262011-08-12 20:24:12 +00003710 LP->addClause(V);
3711 }
3712
3713 Inst = LP;
3714 return false;
3715}
3716
Chris Lattnerdf986172009-01-02 07:01:27 +00003717/// ParseCall
3718/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3719/// ParameterList OptionalAttrs
3720bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3721 bool isTail) {
Bill Wendling702cc912012-10-15 20:35:56 +00003722 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003723 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003724 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003725 LocTy RetTypeLoc;
3726 ValID CalleeID;
3727 SmallVector<ParamInfo, 16> ArgList;
3728 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003729
Chris Lattnerdf986172009-01-02 07:01:27 +00003730 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3731 ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003732 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003733 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003734 ParseValID(CalleeID) ||
3735 ParseParameterList(ArgList, PFS) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003736 ParseOptionalFuncAttrs(FnAttrs))
Chris Lattnerdf986172009-01-02 07:01:27 +00003737 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003738
Chris Lattnerdf986172009-01-02 07:01:27 +00003739 // If RetType is a non-function pointer type, then this is the short syntax
3740 // for the call, which means that RetType is just the return type. Infer the
3741 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003742 PointerType *PFTy = 0;
3743 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003744 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3745 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3746 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003747 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003748 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3749 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003750
Chris Lattnerdf986172009-01-02 07:01:27 +00003751 if (!FunctionType::isValidReturnType(RetType))
3752 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003753
Owen Andersondebcb012009-07-29 22:17:13 +00003754 Ty = FunctionType::get(RetType, ParamTypes, false);
3755 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003757
Chris Lattnerdf986172009-01-02 07:01:27 +00003758 // Look up the callee.
3759 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003760 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003761
Bill Wendling034b94b2012-12-19 07:18:57 +00003762 // Set up the Attribute for the function.
Chris Lattnerdf986172009-01-02 07:01:27 +00003763 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003764 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003765 Attrs.push_back(
Bill Wendling99faa3b2012-12-07 23:16:57 +00003766 AttributeWithIndex::get(AttributeSet::ReturnIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003767 Attribute::get(Callee->getContext(),
Bill Wendling07aae2e2012-10-15 07:29:08 +00003768 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003769
Chris Lattnerdf986172009-01-02 07:01:27 +00003770 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003771
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 // Loop through FunctionType's arguments and ensure they are specified
3773 // correctly. Also, gather any parameter attributes.
3774 FunctionType::param_iterator I = Ty->param_begin();
3775 FunctionType::param_iterator E = Ty->param_end();
3776 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003777 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003778 if (I != E) {
3779 ExpectedTy = *I++;
3780 } else if (!Ty->isVarArg()) {
3781 return Error(ArgList[i].Loc, "too many arguments specified");
3782 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003783
Chris Lattnerdf986172009-01-02 07:01:27 +00003784 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3785 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003786 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003787 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003788 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003789 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3790 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003791
Chris Lattnerdf986172009-01-02 07:01:27 +00003792 if (I != E)
3793 return Error(CallLoc, "not enough parameters specified for call");
3794
Bill Wendlinge603fe42012-09-19 23:54:18 +00003795 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003796 Attrs.push_back(
Bill Wendling99faa3b2012-12-07 23:16:57 +00003797 AttributeWithIndex::get(AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003798 Attribute::get(Callee->getContext(),
Bill Wendling07aae2e2012-10-15 07:29:08 +00003799 FnAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00003800
Bill Wendling034b94b2012-12-19 07:18:57 +00003801 // Finish off the Attribute and check them
Bill Wendling99faa3b2012-12-07 23:16:57 +00003802 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003803
Jay Foada3efbb12011-07-15 08:37:34 +00003804 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003805 CI->setTailCall(isTail);
3806 CI->setCallingConv(CC);
3807 CI->setAttributes(PAL);
3808 Inst = CI;
3809 return false;
3810}
3811
3812//===----------------------------------------------------------------------===//
3813// Memory Instructions.
3814//===----------------------------------------------------------------------===//
3815
3816/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003817/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003818int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003819 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003820 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003821 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003822 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003823 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003824
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003825 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003826 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003827 if (Lex.getKind() == lltok::kw_align) {
3828 if (ParseOptionalAlignment(Alignment)) return true;
3829 } else if (Lex.getKind() == lltok::MetadataVar) {
3830 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003831 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003832 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3833 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3834 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003835 }
3836 }
3837
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003838 if (Size && !Size->getType()->isIntegerTy())
3839 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003840
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003841 Inst = new AllocaInst(Ty, Size, Alignment);
3842 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003843}
3844
3845/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003846/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman407a6162012-11-15 22:34:00 +00003847/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedmanf03bb262011-08-12 22:50:01 +00003848/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003849int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003850 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003851 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003852 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003853 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003854 AtomicOrdering Ordering = NotAtomic;
3855 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003856
3857 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003858 isAtomic = true;
3859 Lex.Lex();
3860 }
3861
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003862 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003863 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003864 isVolatile = true;
3865 Lex.Lex();
3866 }
3867
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003868 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003869 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003870 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3871 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003872
Duncan Sands1df98592010-02-16 11:11:14 +00003873 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003874 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3875 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003876 if (isAtomic && !Alignment)
3877 return Error(Loc, "atomic load must have explicit non-zero alignment");
3878 if (Ordering == Release || Ordering == AcquireRelease)
3879 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003880
Eli Friedman21006d42011-08-09 23:02:53 +00003881 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003882 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003883}
3884
3885/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003886
3887/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3888/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003889/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003890int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003891 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003892 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003893 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003894 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003895 AtomicOrdering Ordering = NotAtomic;
3896 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003897
3898 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003899 isAtomic = true;
3900 Lex.Lex();
3901 }
3902
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003903 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003904 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003905 isVolatile = true;
3906 Lex.Lex();
3907 }
3908
Chris Lattnerdf986172009-01-02 07:01:27 +00003909 if (ParseTypeAndValue(Val, Loc, PFS) ||
3910 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003911 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003912 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003913 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003914 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003915
Duncan Sands1df98592010-02-16 11:11:14 +00003916 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003917 return Error(PtrLoc, "store operand must be a pointer");
3918 if (!Val->getType()->isFirstClassType())
3919 return Error(Loc, "store operand must be a first class value");
3920 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3921 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003922 if (isAtomic && !Alignment)
3923 return Error(Loc, "atomic store must have explicit non-zero alignment");
3924 if (Ordering == Acquire || Ordering == AcquireRelease)
3925 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003926
Eli Friedman21006d42011-08-09 23:02:53 +00003927 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003928 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003929}
3930
Eli Friedmanff030482011-07-28 21:48:00 +00003931/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003932/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3933/// 'singlethread'? AtomicOrdering
3934int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003935 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3936 bool AteExtraComma = false;
3937 AtomicOrdering Ordering = NotAtomic;
3938 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003939 bool isVolatile = false;
3940
3941 if (EatIfPresent(lltok::kw_volatile))
3942 isVolatile = true;
3943
Eli Friedmanff030482011-07-28 21:48:00 +00003944 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3945 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3946 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3947 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3948 ParseTypeAndValue(New, NewLoc, PFS) ||
3949 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3950 return true;
3951
3952 if (Ordering == Unordered)
3953 return TokError("cmpxchg cannot be unordered");
3954 if (!Ptr->getType()->isPointerTy())
3955 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3956 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3957 return Error(CmpLoc, "compare value and pointer type do not match");
3958 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3959 return Error(NewLoc, "new value and pointer type do not match");
3960 if (!New->getType()->isIntegerTy())
3961 return Error(NewLoc, "cmpxchg operand must be an integer");
3962 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3963 if (Size < 8 || (Size & (Size - 1)))
3964 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3965 " integer");
3966
3967 AtomicCmpXchgInst *CXI =
3968 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3969 CXI->setVolatile(isVolatile);
3970 Inst = CXI;
3971 return AteExtraComma ? InstExtraComma : InstNormal;
3972}
3973
3974/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003975/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3976/// 'singlethread'? AtomicOrdering
3977int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003978 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3979 bool AteExtraComma = false;
3980 AtomicOrdering Ordering = NotAtomic;
3981 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003982 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003983 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003984
3985 if (EatIfPresent(lltok::kw_volatile))
3986 isVolatile = true;
3987
Eli Friedmanff030482011-07-28 21:48:00 +00003988 switch (Lex.getKind()) {
3989 default: return TokError("expected binary operation in atomicrmw");
3990 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3991 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3992 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3993 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3994 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3995 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3996 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3997 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3998 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3999 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4000 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4001 }
4002 Lex.Lex(); // Eat the operation.
4003
4004 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4005 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4006 ParseTypeAndValue(Val, ValLoc, PFS) ||
4007 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4008 return true;
4009
4010 if (Ordering == Unordered)
4011 return TokError("atomicrmw cannot be unordered");
4012 if (!Ptr->getType()->isPointerTy())
4013 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4014 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4015 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4016 if (!Val->getType()->isIntegerTy())
4017 return Error(ValLoc, "atomicrmw operand must be an integer");
4018 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4019 if (Size < 8 || (Size & (Size - 1)))
4020 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4021 " integer");
4022
4023 AtomicRMWInst *RMWI =
4024 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4025 RMWI->setVolatile(isVolatile);
4026 Inst = RMWI;
4027 return AteExtraComma ? InstExtraComma : InstNormal;
4028}
4029
Eli Friedman47f35132011-07-25 23:16:38 +00004030/// ParseFence
4031/// ::= 'fence' 'singlethread'? AtomicOrdering
4032int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4033 AtomicOrdering Ordering = NotAtomic;
4034 SynchronizationScope Scope = CrossThread;
4035 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4036 return true;
4037
4038 if (Ordering == Unordered)
4039 return TokError("fence cannot be unordered");
4040 if (Ordering == Monotonic)
4041 return TokError("fence cannot be monotonic");
4042
4043 Inst = new FenceInst(Context, Ordering, Scope);
4044 return InstNormal;
4045}
4046
Chris Lattnerdf986172009-01-02 07:01:27 +00004047/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00004048/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004049int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00004050 Value *Ptr = 0;
4051 Value *Val = 0;
4052 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00004053
Dan Gohmandcb40a32009-07-29 15:58:36 +00004054 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004055
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004056 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00004057
Nadav Rotem16087692011-12-05 06:29:09 +00004058 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004059 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004060
Chris Lattnerdf986172009-01-02 07:01:27 +00004061 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004062 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004063 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004064 if (Lex.getKind() == lltok::MetadataVar) {
4065 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00004066 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004067 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004068 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00004069 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004070 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00004071 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4072 return Error(EltLoc, "getelementptr index type missmatch");
4073 if (Val->getType()->isVectorTy()) {
4074 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4075 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4076 if (ValNumEl != PtrNumEl)
4077 return Error(EltLoc,
4078 "getelementptr vector index has a wrong number of elements");
4079 }
Chris Lattnerdf986172009-01-02 07:01:27 +00004080 Indices.push_back(Val);
4081 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00004082
Jay Foada9203102011-07-25 09:48:08 +00004083 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004084 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004085 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004086 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004087 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004088 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004089}
4090
4091/// ParseExtractValue
4092/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004093int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004094 Value *Val; LocTy Loc;
4095 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004096 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004097 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004098 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004099 return true;
4100
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004101 if (!Val->getType()->isAggregateType())
4102 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004103
Jay Foadfc6d3a42011-07-13 10:26:04 +00004104 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004105 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004106 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004107 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004108}
4109
4110/// ParseInsertValue
4111/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004112int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004113 Value *Val0, *Val1; LocTy Loc0, Loc1;
4114 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004115 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004116 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4117 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4118 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004119 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004120 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00004121
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004122 if (!Val0->getType()->isAggregateType())
4123 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004124
Jay Foadfc6d3a42011-07-13 10:26:04 +00004125 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004126 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004127 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004128 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004129}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004130
4131//===----------------------------------------------------------------------===//
4132// Embedded metadata.
4133//===----------------------------------------------------------------------===//
4134
4135/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004136/// ::= Element (',' Element)*
4137/// Element
4138/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004139bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004140 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004141 // Check for an empty list.
4142 if (Lex.getKind() == lltok::rbrace)
4143 return false;
4144
Nick Lewycky21cc4462009-04-04 07:22:01 +00004145 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004146 // Null is a special case since it is typeless.
4147 if (EatIfPresent(lltok::kw_null)) {
4148 Elts.push_back(0);
4149 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004150 }
Michael Ilseman407a6162012-11-15 22:34:00 +00004151
Chris Lattnera7352392009-12-30 04:42:57 +00004152 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004153 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004154 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004155 } while (EatIfPresent(lltok::comma));
4156
4157 return false;
4158}