blob: 0ad921ae4befea24c09165ef453a2e35ea0b14f6 [file] [log] [blame]
Chris Lattnerac161bf2009-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 Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-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"
Manman Ren209b17c2013-09-28 00:22:27 +000022#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000028#include "llvm/Support/raw_ostream.h"
29using namespace llvm;
30
Chris Lattner229907c2011-07-18 04:54:35 +000031static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000032 std::string Result;
33 raw_string_ostream Tmp(Result);
34 Tmp << *T;
35 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000036}
37
Chris Lattner3822f632009-01-02 08:05:26 +000038/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000039bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000040 // Prime the lexer.
41 Lex.Lex();
42
Chris Lattnerad6f3352009-01-04 20:44:11 +000043 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000045}
46
47/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48/// module.
49bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000050 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
51 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
52
Bill Wendlingb32b0412013-02-08 06:32:06 +000053 // Handle any function attribute group forward references.
54 for (std::map<Value*, std::vector<unsigned> >::iterator
55 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
56 I != E; ++I) {
57 Value *V = I->first;
58 std::vector<unsigned> &Vec = I->second;
59 AttrBuilder B;
60
61 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
62 VI != VE; ++VI)
63 B.merge(NumberedAttrBuilders[*VI]);
64
65 if (Function *Fn = dyn_cast<Function>(V)) {
66 AttributeSet AS = Fn->getAttributes();
67 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
68 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
69 AS.getFnAttributes());
70
71 FnAttrs.merge(B);
72
73 // If the alignment was parsed as an attribute, move to the alignment
74 // field.
75 if (FnAttrs.hasAlignmentAttr()) {
76 Fn->setAlignment(FnAttrs.getAlignment());
77 FnAttrs.removeAttribute(Attribute::Alignment);
78 }
79
80 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
81 AttributeSet::get(Context,
82 AttributeSet::FunctionIndex,
83 FnAttrs));
84 Fn->setAttributes(AS);
85 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
86 AttributeSet AS = CI->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000090 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000091 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
92 AttributeSet::get(Context,
93 AttributeSet::FunctionIndex,
94 FnAttrs));
95 CI->setAttributes(AS);
96 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
97 AttributeSet AS = II->getAttributes();
98 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000101 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000102 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
103 AttributeSet::get(Context,
104 AttributeSet::FunctionIndex,
105 FnAttrs));
106 II->setAttributes(AS);
107 } else {
108 llvm_unreachable("invalid object with forward attribute group reference");
109 }
110 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000111
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000112 // If there are entries in ForwardRefBlockAddresses at this point, the
113 // function was never defined.
114 if (!ForwardRefBlockAddresses.empty())
115 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
116 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000118 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
119 if (NumberedTypes[i].second.isValid())
120 return Error(NumberedTypes[i].second,
121 "use of undefined type '%" + Twine(i) + "'");
122
123 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
124 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
125 if (I->second.second.isValid())
126 return Error(I->second.second,
127 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000128
David Majnemerdad0a642014-06-27 18:19:56 +0000129 if (!ForwardRefComdats.empty())
130 return Error(ForwardRefComdats.begin()->second,
131 "use of undefined comdat '$" +
132 ForwardRefComdats.begin()->first + "'");
133
Chris Lattnerac161bf2009-01-02 07:01:27 +0000134 if (!ForwardRefVals.empty())
135 return Error(ForwardRefVals.begin()->second.second,
136 "use of undefined value '@" + ForwardRefVals.begin()->first +
137 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000138
Chris Lattnerac161bf2009-01-02 07:01:27 +0000139 if (!ForwardRefValIDs.empty())
140 return Error(ForwardRefValIDs.begin()->second.second,
141 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000142 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000143
Devang Pateld2541152009-07-08 19:23:54 +0000144 if (!ForwardRefMDNodes.empty())
145 return Error(ForwardRefMDNodes.begin()->second.second,
146 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000147 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000148
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000149 // Resolve metadata cycles.
150 for (auto &N : NumberedMetadata)
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000151 if (N && !N->isResolved())
152 N->resolveCycles();
Devang Pateld2541152009-07-08 19:23:54 +0000153
Chris Lattnerac161bf2009-01-02 07:01:27 +0000154 // Look for intrinsic functions and CallInst that need to be upgraded
155 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
156 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000157
Manman Ren8b4306c2013-12-02 21:29:56 +0000158 UpgradeDebugInfo(*M);
159
Chris Lattnerac161bf2009-01-02 07:01:27 +0000160 return false;
161}
162
163//===----------------------------------------------------------------------===//
164// Top-Level Entities
165//===----------------------------------------------------------------------===//
166
167bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000168 while (1) {
169 switch (Lex.getKind()) {
170 default: return TokError("expected top-level entity");
171 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000172 case lltok::kw_declare: if (ParseDeclare()) return true; break;
173 case lltok::kw_define: if (ParseDefine()) return true; break;
174 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
175 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000176 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000177 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000178 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000179 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000180 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000181 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000183 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
188 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000189 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000190 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000191 case lltok::kw_internal: // OptionalLinkage
192 case lltok::kw_weak: // OptionalLinkage
193 case lltok::kw_weak_odr: // OptionalLinkage
194 case lltok::kw_linkonce: // OptionalLinkage
195 case lltok::kw_linkonce_odr: // OptionalLinkage
196 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000197 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000198 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000199 case lltok::kw_external: // OptionalLinkage
200 case lltok::kw_default: // OptionalVisibility
201 case lltok::kw_hidden: // OptionalVisibility
202 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000203 case lltok::kw_dllimport: // OptionalDLLStorageClass
204 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000205 case lltok::kw_thread_local: // OptionalThreadLocal
206 case lltok::kw_addrspace: // OptionalAddrSpace
207 case lltok::kw_constant: // GlobalType
208 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000209 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000210 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000211 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000212 bool HasLinkage;
213 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000214 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000215 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000216 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000217 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000218 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000219 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000220 return true;
221 break;
222 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000223
224 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000225 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
226 case lltok::kw_uselistorder_bb:
227 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000228 }
229 }
230}
231
232
233/// toplevelentity
234/// ::= 'module' 'asm' STRINGCONSTANT
235bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
237 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000238
239 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000242
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000243 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000244 return false;
245}
246
247/// toplevelentity
248/// ::= 'target' 'triple' '=' STRINGCONSTANT
249/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000252 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000253 switch (Lex.Lex()) {
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
256 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000260 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 return false;
262 case lltok::kw_datalayout:
263 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000264 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
265 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000267 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 return false;
269 }
270}
271
Bill Wendling706d3d62012-11-28 08:41:48 +0000272/// toplevelentity
273/// ::= 'deplibs' '=' '[' ']'
274/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
275/// FIXME: Remove in 4.0. Currently parse, but ignore.
276bool LLParser::ParseDepLibs() {
277 assert(Lex.getKind() == lltok::kw_deplibs);
278 Lex.Lex();
279 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
280 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
281 return true;
282
283 if (EatIfPresent(lltok::rsquare))
284 return false;
285
286 do {
287 std::string Str;
288 if (ParseStringConstant(Str)) return true;
289 } while (EatIfPresent(lltok::comma));
290
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
292}
293
Dan Gohman466876b2009-08-12 23:32:33 +0000294/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000295/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000296bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000297 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000298 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000299 Lex.Lex(); // eat LocalVarID;
300
301 if (ParseToken(lltok::equal, "expected '=' after name") ||
302 ParseToken(lltok::kw_type, "expected 'type' after '='"))
303 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000305 if (TypeID >= NumberedTypes.size())
306 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000307
Craig Topper2617dcc2014-04-15 06:32:26 +0000308 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000309 if (ParseStructDefinition(TypeLoc, "",
310 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000312 if (!isa<StructType>(Result)) {
313 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
314 if (Entry.first)
315 return Error(TypeLoc, "non-struct types may not be recursive");
316 Entry.first = Result;
317 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000319
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return false;
321}
322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000323
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324/// toplevelentity
325/// ::= LocalVar '=' 'type' type
326bool LLParser::ParseNamedType() {
327 std::string Name = Lex.getStrVal();
328 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000329 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000330
Chris Lattner3822f632009-01-02 08:05:26 +0000331 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000332 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000333 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000334
Craig Topper2617dcc2014-04-15 06:32:26 +0000335 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000336 if (ParseStructDefinition(NameLoc, Name,
337 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000339 if (!isa<StructType>(Result)) {
340 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
341 if (Entry.first)
342 return Error(NameLoc, "non-struct types may not be recursive");
343 Entry.first = Result;
344 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000347 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000348}
349
350
351/// toplevelentity
352/// ::= 'declare' FunctionHeader
353bool LLParser::ParseDeclare() {
354 assert(Lex.getKind() == lltok::kw_declare);
355 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000356
Chris Lattnerac161bf2009-01-02 07:01:27 +0000357 Function *F;
358 return ParseFunctionHeader(F, false);
359}
360
361/// toplevelentity
362/// ::= 'define' FunctionHeader '{' ...
363bool LLParser::ParseDefine() {
364 assert(Lex.getKind() == lltok::kw_define);
365 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000368 return ParseFunctionHeader(F, true) ||
369 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370}
371
Chris Lattner3822f632009-01-02 08:05:26 +0000372/// ParseGlobalType
373/// ::= 'constant'
374/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000375bool LLParser::ParseGlobalType(bool &IsConstant) {
376 if (Lex.getKind() == lltok::kw_constant)
377 IsConstant = true;
378 else if (Lex.getKind() == lltok::kw_global)
379 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000380 else {
381 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000382 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000383 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 Lex.Lex();
385 return false;
386}
387
Dan Gohman466876b2009-08-12 23:32:33 +0000388/// ParseUnnamedGlobal:
389/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000390/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
391/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000392/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000393/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
394/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000395bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
397 std::string Name;
398 LocTy NameLoc = Lex.getLoc();
399
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000404 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000405 Lex.Lex(); // eat GlobalID;
406
407 if (ParseToken(lltok::equal, "expected '=' after name"))
408 return true;
409 }
410
411 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000412 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000413 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000414 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000415 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000416 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000417 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000418 ParseOptionalThreadLocal(TLM) ||
419 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000420 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000421
Rafael Espindola464fe022014-07-30 22:51:54 +0000422 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000423 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000424 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000425 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000426 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000427}
428
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429/// ParseNamedGlobal:
430/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000431/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
432/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000433bool LLParser::ParseNamedGlobal() {
434 assert(Lex.getKind() == lltok::GlobalVar);
435 LocTy NameLoc = Lex.getLoc();
436 std::string Name = Lex.getStrVal();
437 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000438
Chris Lattnerac161bf2009-01-02 07:01:27 +0000439 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000440 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000441 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000442 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
444 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000445 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000446 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000447 ParseOptionalThreadLocal(TLM) ||
448 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000450
Rafael Espindola464fe022014-07-30 22:51:54 +0000451 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000452 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000453 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000454
455 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000456 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000457}
458
David Majnemerdad0a642014-06-27 18:19:56 +0000459bool LLParser::parseComdat() {
460 assert(Lex.getKind() == lltok::ComdatVar);
461 std::string Name = Lex.getStrVal();
462 LocTy NameLoc = Lex.getLoc();
463 Lex.Lex();
464
465 if (ParseToken(lltok::equal, "expected '=' here"))
466 return true;
467
468 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
469 return TokError("expected comdat type");
470
471 Comdat::SelectionKind SK;
472 switch (Lex.getKind()) {
473 default:
474 return TokError("unknown selection kind");
475 case lltok::kw_any:
476 SK = Comdat::Any;
477 break;
478 case lltok::kw_exactmatch:
479 SK = Comdat::ExactMatch;
480 break;
481 case lltok::kw_largest:
482 SK = Comdat::Largest;
483 break;
484 case lltok::kw_noduplicates:
485 SK = Comdat::NoDuplicates;
486 break;
487 case lltok::kw_samesize:
488 SK = Comdat::SameSize;
489 break;
490 }
491 Lex.Lex();
492
493 // See if the comdat was forward referenced, if so, use the comdat.
494 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
495 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
496 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
497 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
498
499 Comdat *C;
500 if (I != ComdatSymTab.end())
501 C = &I->second;
502 else
503 C = M->getOrInsertComdat(Name);
504 C->setSelectionKind(SK);
505
506 return false;
507}
508
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000509// MDString:
510// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000511bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000512 std::string Str;
513 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000514 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000515 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000516 return false;
517}
518
519// MDNode:
520// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000521bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000522 // !{ ..., !42, ... }
523 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000524 if (ParseUInt32(MID))
525 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Chris Lattner8eff0152010-04-01 05:14:45 +0000527 // If not a forward reference, just return it now.
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000528 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
529 Result = NumberedMetadata[MID];
530 return false;
531 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000532
Chris Lattner8eff0152010-04-01 05:14:45 +0000533 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000534 auto &FwdRef = ForwardRefMDNodes[MID];
535 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000536
Chris Lattnerfc58af22009-12-30 04:51:58 +0000537 if (NumberedMetadata.size() <= MID)
538 NumberedMetadata.resize(MID+1);
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000539 Result = FwdRef.first.get();
540 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000541 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000542}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000544/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000545/// !foo = !{ !1, !2 }
546bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000547 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000548 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000549 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000550
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000551 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000552 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000553 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000554 return true;
555
Dan Gohman2637cc12010-07-21 23:38:33 +0000556 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000557 if (Lex.getKind() != lltok::rbrace)
558 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000559 if (ParseToken(lltok::exclaim, "Expected '!' here"))
560 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000561
Craig Topper2617dcc2014-04-15 06:32:26 +0000562 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000563 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000564 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000565 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000566
567 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
568 return true;
569
Devang Patelbe626972009-07-29 00:34:02 +0000570 return false;
571}
572
Devang Patel39e64d42009-07-01 19:21:12 +0000573/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000574/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000575bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000576 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000577 Lex.Lex();
578 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000579
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000580 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000581 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000582 ParseToken(lltok::equal, "expected '=' here"))
583 return true;
584
585 // Detect common error, from old metadata syntax.
586 if (Lex.getKind() == lltok::Type)
587 return TokError("unexpected type in metadata definition");
588
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000589 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000590 if (Lex.getKind() == lltok::MetadataVar) {
591 if (ParseSpecializedMDNode(Init, IsDistinct))
592 return true;
593 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
594 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000595 return true;
596
Chris Lattnerfc58af22009-12-30 04:51:58 +0000597 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000598 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000599 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000600 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000601 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000602
Chris Lattnerfc58af22009-12-30 04:51:58 +0000603 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
604 } else {
605 if (MetadataID >= NumberedMetadata.size())
606 NumberedMetadata.resize(MetadataID+1);
607
Craig Topper2617dcc2014-04-15 06:32:26 +0000608 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000609 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000610 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000611 }
612
Devang Patel39e64d42009-07-01 19:21:12 +0000613 return false;
614}
615
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000616static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
617 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
618 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
619}
620
Chris Lattnerac161bf2009-01-02 07:01:27 +0000621/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000622/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
623/// OptionalDLLStorageClass OptionalThreadLocal
624/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000625///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000626/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000627/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000628///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000629/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000630///
Rafael Espindola464fe022014-07-30 22:51:54 +0000631bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000632 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000633 GlobalVariable::ThreadLocalMode TLM,
634 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000635 assert(Lex.getKind() == lltok::kw_alias);
636 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000637
Rafael Espindola78527052013-10-06 15:10:43 +0000638 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
639
Rafael Espindolacaa43562013-10-09 16:07:32 +0000640 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000641 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000642
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000643 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000644 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000645 "symbol with local linkage must have default visibility");
646
Rafael Espindola64c1e182014-06-03 02:41:57 +0000647 Constant *Aliasee;
648 LocTy AliaseeLoc = Lex.getLoc();
649 if (Lex.getKind() != lltok::kw_bitcast &&
650 Lex.getKind() != lltok::kw_getelementptr &&
651 Lex.getKind() != lltok::kw_addrspacecast &&
652 Lex.getKind() != lltok::kw_inttoptr) {
653 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000654 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000655 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000656 // The bitcast dest type is not present, it is implied by the dest type.
657 ValID ID;
658 if (ParseValID(ID))
659 return true;
660 if (ID.Kind != ValID::t_Constant)
661 return Error(AliaseeLoc, "invalid aliasee");
662 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000663 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000664
Rafael Espindola64c1e182014-06-03 02:41:57 +0000665 Type *AliaseeType = Aliasee->getType();
666 auto *PTy = dyn_cast<PointerType>(AliaseeType);
667 if (!PTy)
668 return Error(AliaseeLoc, "An alias must have pointer type");
669 Type *Ty = PTy->getElementType();
670 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000671
672 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000673 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000674 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
675 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000676 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000678 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000679 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000680
Chris Lattnerac161bf2009-01-02 07:01:27 +0000681 // See if this value already exists in the symbol table. If so, it is either
682 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000683 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000684 // See if this was a redefinition. If so, there is no entry in
685 // ForwardRefVals.
686 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefVals.find(Name);
688 if (I == ForwardRefVals.end())
689 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
690
691 // Otherwise, this was a definition of forward ref. Verify that types
692 // agree.
693 if (Val->getType() != GA->getType())
694 return Error(NameLoc,
695 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000696
Chris Lattnerac161bf2009-01-02 07:01:27 +0000697 // If they agree, just RAUW the old value with the alias and remove the
698 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000699 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700 Val->eraseFromParent();
701 ForwardRefVals.erase(I);
702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000703
Chris Lattnerac161bf2009-01-02 07:01:27 +0000704 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000705 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000706 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000707
Rafael Espindolaaa273822014-05-09 21:49:17 +0000708 // The module owns this now
709 GA.release();
710
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711 return false;
712}
713
714/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000715/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000716/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000717/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000718/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000719/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000720/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000721///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000722/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000723/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724///
725bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
726 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000727 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000728 GlobalVariable::ThreadLocalMode TLM,
729 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000730 if (!isValidVisibilityForLinkage(Visibility, Linkage))
731 return Error(NameLoc,
732 "symbol with local linkage must have default visibility");
733
Chris Lattnerac161bf2009-01-02 07:01:27 +0000734 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000735 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000736 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000737 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000738
Craig Topper2617dcc2014-04-15 06:32:26 +0000739 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000740 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000741 ParseOptionalToken(lltok::kw_externally_initialized,
742 IsExternallyInitialized,
743 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000744 ParseGlobalType(IsConstant) ||
745 ParseType(Ty, TyLoc))
746 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000747
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 // If the linkage is specified and is external, then no initializer is
749 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000750 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000751 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752 Linkage != GlobalValue::ExternalLinkage)) {
753 if (ParseGlobalValue(Ty, Init))
754 return true;
755 }
756
Duncan Sands19d0b472010-02-16 11:11:14 +0000757 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000758 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000759
David Majnemer598bd052014-12-09 05:56:09 +0000760 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000761
762 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000763 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000764 GVal = M->getNamedValue(Name);
765 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000766 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
767 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000768 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000769 } else {
770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
771 I = ForwardRefValIDs.find(NumberedVals.size());
772 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000773 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000774 ForwardRefValIDs.erase(I);
775 }
776 }
777
David Majnemer598bd052014-12-09 05:56:09 +0000778 GlobalVariable *GV;
779 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000780 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
781 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000782 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000783 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000784 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000785 return Error(TyLoc,
786 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000787
David Majnemer598bd052014-12-09 05:56:09 +0000788 GV = cast<GlobalVariable>(GVal);
789
Chris Lattnerac161bf2009-01-02 07:01:27 +0000790 // Move the forward-reference to the correct spot in the module.
791 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
792 }
793
794 if (Name.empty())
795 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000796
Chris Lattnerac161bf2009-01-02 07:01:27 +0000797 // Set the parsed properties on the global.
798 if (Init)
799 GV->setInitializer(Init);
800 GV->setConstant(IsConstant);
801 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
802 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000803 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000804 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000805 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000806 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000807
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 // Parse attributes on the global.
809 while (Lex.getKind() == lltok::comma) {
810 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 if (Lex.getKind() == lltok::kw_section) {
813 Lex.Lex();
814 GV->setSection(Lex.getStrVal());
815 if (ParseToken(lltok::StringConstant, "expected global section string"))
816 return true;
817 } else if (Lex.getKind() == lltok::kw_align) {
818 unsigned Alignment;
819 if (ParseOptionalAlignment(Alignment)) return true;
820 GV->setAlignment(Alignment);
821 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000822 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000823 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000824 return true;
825 if (C)
826 GV->setComdat(C);
827 else
828 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000829 }
830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
Chris Lattnerac161bf2009-01-02 07:01:27 +0000832 return false;
833}
834
Bill Wendling63b88192013-02-06 06:52:58 +0000835/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000836/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000837bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000838 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000839 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000840 Lex.Lex();
841
David Majnemerb39e22b2014-12-09 18:33:57 +0000842 if (Lex.getKind() != lltok::AttrGrpID)
843 return TokError("expected attribute group id");
844
Bill Wendling63b88192013-02-06 06:52:58 +0000845 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000846 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000847 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000848 Lex.Lex();
849
850 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000851 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000852 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000853 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000854 ParseToken(lltok::rbrace, "expected end of attribute group"))
855 return true;
856
Bill Wendlingb32b0412013-02-08 06:32:06 +0000857 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000858 return Error(AttrGrpLoc, "attribute group has no attributes");
859
860 return false;
861}
862
Bill Wendling8b0321d2013-02-08 00:52:31 +0000863/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000864/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000865bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
866 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000867 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000868 bool HaveError = false;
869
870 B.clear();
871
Bill Wendling63b88192013-02-06 06:52:58 +0000872 while (true) {
873 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000874 if (Token == lltok::kw_builtin)
875 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000876 switch (Token) {
877 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000878 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000879 return Error(Lex.getLoc(), "unterminated attribute group");
880 case lltok::rbrace:
881 // Finished.
882 return false;
883
Bill Wendlingb32b0412013-02-08 06:32:06 +0000884 case lltok::AttrGrpID: {
885 // Allow a function to reference an attribute group:
886 //
887 // define void @foo() #1 { ... }
888 if (inAttrGrp)
889 HaveError |=
890 Error(Lex.getLoc(),
891 "cannot have an attribute group reference in an attribute group");
892
893 unsigned AttrGrpNum = Lex.getUIntVal();
894 if (inAttrGrp) break;
895
896 // Save the reference to the attribute group. We'll fill it in later.
897 FwdRefAttrGrps.push_back(AttrGrpNum);
898 break;
899 }
Bill Wendling63b88192013-02-06 06:52:58 +0000900 // Target-dependent attributes:
901 case lltok::StringConstant: {
902 std::string Attr = Lex.getStrVal();
903 Lex.Lex();
904 std::string Val;
905 if (EatIfPresent(lltok::equal) &&
906 ParseStringConstant(Val))
907 return true;
908
909 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000910 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000911 }
912
913 // Target-independent attributes:
914 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000915 // As a hack, we allow function alignment to be initially parsed as an
916 // attribute on a function declaration/definition or added to an attribute
917 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000918 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000919 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000920 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000921 if (ParseToken(lltok::equal, "expected '=' here") ||
922 ParseUInt32(Alignment))
923 return true;
924 } else {
925 if (ParseOptionalAlignment(Alignment))
926 return true;
927 }
Bill Wendling63b88192013-02-06 06:52:58 +0000928 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000929 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000930 }
931 case lltok::kw_alignstack: {
932 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000933 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000934 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000935 if (ParseToken(lltok::equal, "expected '=' here") ||
936 ParseUInt32(Alignment))
937 return true;
938 } else {
939 if (ParseOptionalStackAlignment(Alignment))
940 return true;
941 }
Bill Wendling63b88192013-02-06 06:52:58 +0000942 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000943 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000944 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000945 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000946 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000947 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000948 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000949 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000950 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
951 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
952 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
953 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
954 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
955 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
956 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
957 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
958 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
959 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000960 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000961 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
962 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
963 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
964 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
965 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
966 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
967 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
968 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
969 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
970 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
971 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000972
973 // Error handling.
974 case lltok::kw_inreg:
975 case lltok::kw_signext:
976 case lltok::kw_zeroext:
977 HaveError |=
978 Error(Lex.getLoc(),
979 "invalid use of attribute on a function");
980 break;
981 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000982 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +0000983 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984 case lltok::kw_nest:
985 case lltok::kw_noalias:
986 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000987 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000988 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000989 case lltok::kw_sret:
990 HaveError |=
991 Error(Lex.getLoc(),
992 "invalid use of parameter-only attribute on a function");
993 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000994 }
995
996 Lex.Lex();
997 }
998}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000999
1000//===----------------------------------------------------------------------===//
1001// GlobalValue Reference/Resolution Routines.
1002//===----------------------------------------------------------------------===//
1003
1004/// GetGlobalVal - Get a value with the specified name or ID, creating a
1005/// forward reference record if needed. This can return null if the value
1006/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001007GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001008 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001009 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001010 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001011 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001012 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001013 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001014
Chris Lattnerac161bf2009-01-02 07:01:27 +00001015 // Look this name up in the normal function symbol table.
1016 GlobalValue *Val =
1017 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001018
Chris Lattnerac161bf2009-01-02 07:01:27 +00001019 // If this is a forward reference for the value, see if we already created a
1020 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001021 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001022 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1023 I = ForwardRefVals.find(Name);
1024 if (I != ForwardRefVals.end())
1025 Val = I->second.first;
1026 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001027
Chris Lattnerac161bf2009-01-02 07:01:27 +00001028 // If we have the value in the symbol table or fwd-ref table, return it.
1029 if (Val) {
1030 if (Val->getType() == Ty) return Val;
1031 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001032 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001033 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001034 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001035
Chris Lattnerac161bf2009-01-02 07:01:27 +00001036 // Otherwise, create a new forward reference for this value and remember it.
1037 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001038 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001039 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001040 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001041 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001042 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1043 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001044 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattnerac161bf2009-01-02 07:01:27 +00001046 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1047 return FwdVal;
1048}
1049
Chris Lattner229907c2011-07-18 04:54:35 +00001050GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1051 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001054 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001056
Craig Topper2617dcc2014-04-15 06:32:26 +00001057 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001058
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 // If this is a forward reference for the value, see if we already created a
1060 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001061 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001062 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1063 I = ForwardRefValIDs.find(ID);
1064 if (I != ForwardRefValIDs.end())
1065 Val = I->second.first;
1066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001067
Chris Lattnerac161bf2009-01-02 07:01:27 +00001068 // If we have the value in the symbol table or fwd-ref table, return it.
1069 if (Val) {
1070 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001071 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001072 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001073 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001074 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001075
Chris Lattnerac161bf2009-01-02 07:01:27 +00001076 // Otherwise, create a new forward reference for this value and remember it.
1077 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001078 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001079 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001080 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001081 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001082 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001083
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1085 return FwdVal;
1086}
1087
1088
1089//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001090// Comdat Reference/Resolution Routines.
1091//===----------------------------------------------------------------------===//
1092
1093Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1094 // Look this name up in the comdat symbol table.
1095 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1096 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1097 if (I != ComdatSymTab.end())
1098 return &I->second;
1099
1100 // Otherwise, create a new forward reference for this value and remember it.
1101 Comdat *C = M->getOrInsertComdat(Name);
1102 ForwardRefComdats[Name] = Loc;
1103 return C;
1104}
1105
1106
1107//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001108// Helper Routines.
1109//===----------------------------------------------------------------------===//
1110
1111/// ParseToken - If the current token has the specified kind, eat it and return
1112/// success. Otherwise, emit the specified error and return failure.
1113bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1114 if (Lex.getKind() != T)
1115 return TokError(ErrMsg);
1116 Lex.Lex();
1117 return false;
1118}
1119
Chris Lattner3822f632009-01-02 08:05:26 +00001120/// ParseStringConstant
1121/// ::= StringConstant
1122bool LLParser::ParseStringConstant(std::string &Result) {
1123 if (Lex.getKind() != lltok::StringConstant)
1124 return TokError("expected string constant");
1125 Result = Lex.getStrVal();
1126 Lex.Lex();
1127 return false;
1128}
1129
1130/// ParseUInt32
1131/// ::= uint32
1132bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001133 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1134 return TokError("expected integer");
1135 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1136 if (Val64 != unsigned(Val64))
1137 return TokError("expected 32-bit integer (too large)");
1138 Val = Val64;
1139 Lex.Lex();
1140 return false;
1141}
1142
Hal Finkelb0407ba2014-07-18 15:51:28 +00001143/// ParseUInt64
1144/// ::= uint64
1145bool LLParser::ParseUInt64(uint64_t &Val) {
1146 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1147 return TokError("expected integer");
1148 Val = Lex.getAPSIntVal().getLimitedValue();
1149 Lex.Lex();
1150 return false;
1151}
1152
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001153/// ParseTLSModel
1154/// := 'localdynamic'
1155/// := 'initialexec'
1156/// := 'localexec'
1157bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1158 switch (Lex.getKind()) {
1159 default:
1160 return TokError("expected localdynamic, initialexec or localexec");
1161 case lltok::kw_localdynamic:
1162 TLM = GlobalVariable::LocalDynamicTLSModel;
1163 break;
1164 case lltok::kw_initialexec:
1165 TLM = GlobalVariable::InitialExecTLSModel;
1166 break;
1167 case lltok::kw_localexec:
1168 TLM = GlobalVariable::LocalExecTLSModel;
1169 break;
1170 }
1171
1172 Lex.Lex();
1173 return false;
1174}
1175
1176/// ParseOptionalThreadLocal
1177/// := /*empty*/
1178/// := 'thread_local'
1179/// := 'thread_local' '(' tlsmodel ')'
1180bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1181 TLM = GlobalVariable::NotThreadLocal;
1182 if (!EatIfPresent(lltok::kw_thread_local))
1183 return false;
1184
1185 TLM = GlobalVariable::GeneralDynamicTLSModel;
1186 if (Lex.getKind() == lltok::lparen) {
1187 Lex.Lex();
1188 return ParseTLSModel(TLM) ||
1189 ParseToken(lltok::rparen, "expected ')' after thread local model");
1190 }
1191 return false;
1192}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001193
1194/// ParseOptionalAddrSpace
1195/// := /*empty*/
1196/// := 'addrspace' '(' uint32 ')'
1197bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1198 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001199 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001202 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001204}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205
Bill Wendling34c2eb22012-12-04 23:40:58 +00001206/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1207bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1208 bool HaveError = false;
1209
1210 B.clear();
1211
1212 while (1) {
1213 lltok::Kind Token = Lex.getKind();
1214 switch (Token) {
1215 default: // End of attributes.
1216 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 case lltok::kw_align: {
1218 unsigned Alignment;
1219 if (ParseOptionalAlignment(Alignment))
1220 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001221 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 continue;
1223 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001224 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001225 case lltok::kw_dereferenceable: {
1226 uint64_t Bytes;
1227 if (ParseOptionalDereferenceableBytes(Bytes))
1228 return true;
1229 B.addDereferenceableAttr(Bytes);
1230 continue;
1231 }
Reid Klecknera534a382013-12-19 02:14:12 +00001232 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001233 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1234 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1235 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1236 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001237 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001238 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1239 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001240 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001241 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1242 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1243 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001244
Stephen Lin7577ed52013-04-20 13:16:13 +00001245 case lltok::kw_alignstack:
1246 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001247 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001248 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001249 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001250 case lltok::kw_minsize:
1251 case lltok::kw_naked:
1252 case lltok::kw_nobuiltin:
1253 case lltok::kw_noduplicate:
1254 case lltok::kw_noimplicitfloat:
1255 case lltok::kw_noinline:
1256 case lltok::kw_nonlazybind:
1257 case lltok::kw_noredzone:
1258 case lltok::kw_noreturn:
1259 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001260 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001261 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001262 case lltok::kw_returns_twice:
1263 case lltok::kw_sanitize_address:
1264 case lltok::kw_sanitize_memory:
1265 case lltok::kw_sanitize_thread:
1266 case lltok::kw_ssp:
1267 case lltok::kw_sspreq:
1268 case lltok::kw_sspstrong:
1269 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001270 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1271 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001272 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001273
Bill Wendling34c2eb22012-12-04 23:40:58 +00001274 Lex.Lex();
1275 }
1276}
1277
1278/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1279bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1280 bool HaveError = false;
1281
1282 B.clear();
1283
1284 while (1) {
1285 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001286 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001287 default: // End of attributes.
1288 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001289 case lltok::kw_dereferenceable: {
1290 uint64_t Bytes;
1291 if (ParseOptionalDereferenceableBytes(Bytes))
1292 return true;
1293 B.addDereferenceableAttr(Bytes);
1294 continue;
1295 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001296 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1297 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001298 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001299 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1300 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001301
Bill Wendling34c2eb22012-12-04 23:40:58 +00001302 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001303 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001304 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001305 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001306 case lltok::kw_nest:
1307 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001308 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001309 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001310 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001311 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001312
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001313 case lltok::kw_alignstack:
1314 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001315 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001316 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001317 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001318 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001319 case lltok::kw_minsize:
1320 case lltok::kw_naked:
1321 case lltok::kw_nobuiltin:
1322 case lltok::kw_noduplicate:
1323 case lltok::kw_noimplicitfloat:
1324 case lltok::kw_noinline:
1325 case lltok::kw_nonlazybind:
1326 case lltok::kw_noredzone:
1327 case lltok::kw_noreturn:
1328 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001329 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001330 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001331 case lltok::kw_returns_twice:
1332 case lltok::kw_sanitize_address:
1333 case lltok::kw_sanitize_memory:
1334 case lltok::kw_sanitize_thread:
1335 case lltok::kw_ssp:
1336 case lltok::kw_sspreq:
1337 case lltok::kw_sspstrong:
1338 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001339 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001340 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001341
1342 case lltok::kw_readnone:
1343 case lltok::kw_readonly:
1344 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001345 }
1346
Chris Lattnerac161bf2009-01-02 07:01:27 +00001347 Lex.Lex();
1348 }
1349}
1350
1351/// ParseOptionalLinkage
1352/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001353/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001354/// ::= 'internal'
1355/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001356/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001358/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001359/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001360/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362/// ::= 'extern_weak'
1363/// ::= 'external'
1364bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1365 HasLinkage = false;
1366 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001367 default: Res=GlobalValue::ExternalLinkage; return false;
1368 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001369 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1370 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1371 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1372 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1373 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001374 case lltok::kw_available_externally:
1375 Res = GlobalValue::AvailableExternallyLinkage;
1376 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001377 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001378 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001379 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1380 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381 }
1382 Lex.Lex();
1383 HasLinkage = true;
1384 return false;
1385}
1386
1387/// ParseOptionalVisibility
1388/// ::= /*empty*/
1389/// ::= 'default'
1390/// ::= 'hidden'
1391/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001392///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001393bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1394 switch (Lex.getKind()) {
1395 default: Res = GlobalValue::DefaultVisibility; return false;
1396 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1397 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1398 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1399 }
1400 Lex.Lex();
1401 return false;
1402}
1403
Nico Rieck7157bb72014-01-14 15:22:47 +00001404/// ParseOptionalDLLStorageClass
1405/// ::= /*empty*/
1406/// ::= 'dllimport'
1407/// ::= 'dllexport'
1408///
1409bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1410 switch (Lex.getKind()) {
1411 default: Res = GlobalValue::DefaultStorageClass; return false;
1412 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1413 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1414 }
1415 Lex.Lex();
1416 return false;
1417}
1418
Chris Lattnerac161bf2009-01-02 07:01:27 +00001419/// ParseOptionalCallingConv
1420/// ::= /*empty*/
1421/// ::= 'ccc'
1422/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001423/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001424/// ::= 'coldcc'
1425/// ::= 'x86_stdcallcc'
1426/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001427/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001428/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001429/// ::= 'arm_apcscc'
1430/// ::= 'arm_aapcscc'
1431/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001432/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001433/// ::= 'ptx_kernel'
1434/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001435/// ::= 'spir_func'
1436/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001437/// ::= 'x86_64_sysvcc'
1438/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001439/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001440/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001441/// ::= 'preserve_mostcc'
1442/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001443/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001444/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001445///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001446bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001447 switch (Lex.getKind()) {
1448 default: CC = CallingConv::C; return false;
1449 case lltok::kw_ccc: CC = CallingConv::C; break;
1450 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1451 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1452 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1453 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001454 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001455 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001456 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1457 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1458 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001459 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001460 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1461 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001462 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1463 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001464 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001465 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1466 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001467 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001468 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001469 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1470 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001471 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001472 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001473 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001474 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001475 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001476 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001477
Chris Lattnerac161bf2009-01-02 07:01:27 +00001478 Lex.Lex();
1479 return false;
1480}
1481
Chris Lattner5c427632009-12-30 05:31:19 +00001482/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001483/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001484bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1485 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001486 do {
1487 if (Lex.getKind() != lltok::MetadataVar)
1488 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001489
Chris Lattner596760d2009-12-29 21:25:40 +00001490 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001491 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001492 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001493
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001494 MDNode *N;
1495 if (ParseMDNode(N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001496 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001497
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001498 Inst->setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001499 if (MDK == LLVMContext::MD_tbaa)
1500 InstsWithTBAATag.push_back(Inst);
1501
Chris Lattner596760d2009-12-29 21:25:40 +00001502 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001503 } while (EatIfPresent(lltok::comma));
1504 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001505}
1506
Chris Lattnerac161bf2009-01-02 07:01:27 +00001507/// ParseOptionalAlignment
1508/// ::= /* empty */
1509/// ::= 'align' 4
1510bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1511 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001512 if (!EatIfPresent(lltok::kw_align))
1513 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001514 LocTy AlignLoc = Lex.getLoc();
1515 if (ParseUInt32(Alignment)) return true;
1516 if (!isPowerOf2_32(Alignment))
1517 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001518 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001519 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001520 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001521}
1522
Hal Finkelb0407ba2014-07-18 15:51:28 +00001523/// ParseOptionalDereferenceableBytes
1524/// ::= /* empty */
1525/// ::= 'dereferenceable' '(' 4 ')'
1526bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1527 Bytes = 0;
1528 if (!EatIfPresent(lltok::kw_dereferenceable))
1529 return false;
1530 LocTy ParenLoc = Lex.getLoc();
1531 if (!EatIfPresent(lltok::lparen))
1532 return Error(ParenLoc, "expected '('");
1533 LocTy DerefLoc = Lex.getLoc();
1534 if (ParseUInt64(Bytes)) return true;
1535 ParenLoc = Lex.getLoc();
1536 if (!EatIfPresent(lltok::rparen))
1537 return Error(ParenLoc, "expected ')'");
1538 if (!Bytes)
1539 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1540 return false;
1541}
1542
Chris Lattnerb2f39502009-12-30 05:44:30 +00001543/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001544/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001545/// ::= ',' align 4
1546///
1547/// This returns with AteExtraComma set to true if it ate an excess comma at the
1548/// end.
1549bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1550 bool &AteExtraComma) {
1551 AteExtraComma = false;
1552 while (EatIfPresent(lltok::comma)) {
1553 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001554 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001555 AteExtraComma = true;
1556 return false;
1557 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001558
Chris Lattner95b0ff42010-04-23 00:50:50 +00001559 if (Lex.getKind() != lltok::kw_align)
1560 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001561
Chris Lattner95b0ff42010-04-23 00:50:50 +00001562 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001564
Devang Patelea8a4b92009-09-17 23:04:48 +00001565 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001566}
1567
Eli Friedmanfee02c62011-07-25 23:16:38 +00001568/// ParseScopeAndOrdering
1569/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1570/// else: ::=
1571///
1572/// This sets Scope and Ordering to the parsed values.
1573bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1574 AtomicOrdering &Ordering) {
1575 if (!isAtomic)
1576 return false;
1577
1578 Scope = CrossThread;
1579 if (EatIfPresent(lltok::kw_singlethread))
1580 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001581
1582 return ParseOrdering(Ordering);
1583}
1584
1585/// ParseOrdering
1586/// ::= AtomicOrdering
1587///
1588/// This sets Ordering to the parsed value.
1589bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001590 switch (Lex.getKind()) {
1591 default: return TokError("Expected ordering on atomic instruction");
1592 case lltok::kw_unordered: Ordering = Unordered; break;
1593 case lltok::kw_monotonic: Ordering = Monotonic; break;
1594 case lltok::kw_acquire: Ordering = Acquire; break;
1595 case lltok::kw_release: Ordering = Release; break;
1596 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1597 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1598 }
1599 Lex.Lex();
1600 return false;
1601}
1602
Charles Davisbe5557e2010-02-12 00:31:15 +00001603/// ParseOptionalStackAlignment
1604/// ::= /* empty */
1605/// ::= 'alignstack' '(' 4 ')'
1606bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1607 Alignment = 0;
1608 if (!EatIfPresent(lltok::kw_alignstack))
1609 return false;
1610 LocTy ParenLoc = Lex.getLoc();
1611 if (!EatIfPresent(lltok::lparen))
1612 return Error(ParenLoc, "expected '('");
1613 LocTy AlignLoc = Lex.getLoc();
1614 if (ParseUInt32(Alignment)) return true;
1615 ParenLoc = Lex.getLoc();
1616 if (!EatIfPresent(lltok::rparen))
1617 return Error(ParenLoc, "expected ')'");
1618 if (!isPowerOf2_32(Alignment))
1619 return Error(AlignLoc, "stack alignment is not a power of two");
1620 return false;
1621}
Devang Patelea8a4b92009-09-17 23:04:48 +00001622
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001623/// ParseIndexList - This parses the index list for an insert/extractvalue
1624/// instruction. This sets AteExtraComma in the case where we eat an extra
1625/// comma at the end of the line and find that it is followed by metadata.
1626/// Clients that don't allow metadata can call the version of this function that
1627/// only takes one argument.
1628///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001629/// ParseIndexList
1630/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001631///
1632bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1633 bool &AteExtraComma) {
1634 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001635
Chris Lattnerac161bf2009-01-02 07:01:27 +00001636 if (Lex.getKind() != lltok::comma)
1637 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001638
Chris Lattner3822f632009-01-02 08:05:26 +00001639 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001640 if (Lex.getKind() == lltok::MetadataVar) {
1641 AteExtraComma = true;
1642 return false;
1643 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001644 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001645 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646 Indices.push_back(Idx);
1647 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001648
Chris Lattnerac161bf2009-01-02 07:01:27 +00001649 return false;
1650}
1651
1652//===----------------------------------------------------------------------===//
1653// Type Parsing.
1654//===----------------------------------------------------------------------===//
1655
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001656/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001657bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001658 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001659 switch (Lex.getKind()) {
1660 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001661 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001662 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001663 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001664 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001665 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001666 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001667 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001668 // Type ::= StructType
1669 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001670 return true;
1671 break;
1672 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001673 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001674 Lex.Lex(); // eat the lsquare.
1675 if (ParseArrayVectorType(Result, false))
1676 return true;
1677 break;
1678 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001680 Lex.Lex();
1681 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001682 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001683 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001684 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 } else if (ParseArrayVectorType(Result, true))
1686 return true;
1687 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001688 case lltok::LocalVar: {
1689 // Type ::= %foo
1690 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001691
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001692 // If the type hasn't been defined yet, create a forward definition and
1693 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001694 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001695 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001696 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001697 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001698 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001699 Lex.Lex();
1700 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001702
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001703 case lltok::LocalVarID: {
1704 // Type ::= %4
1705 if (Lex.getUIntVal() >= NumberedTypes.size())
1706 NumberedTypes.resize(Lex.getUIntVal()+1);
1707 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001708
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001709 // If the type hasn't been defined yet, create a forward definition and
1710 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001711 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001712 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001714 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001716 Lex.Lex();
1717 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001718 }
1719 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001720
1721 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 while (1) {
1723 switch (Lex.getKind()) {
1724 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001725 default:
1726 if (!AllowVoid && Result->isVoidTy())
1727 return Error(TypeLoc, "void type only allowed for function results");
1728 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001730 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001731 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001733 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001734 if (Result->isVoidTy())
1735 return TokError("pointers to void are invalid - use i8* instead");
1736 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001737 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001738 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 Lex.Lex();
1740 break;
1741
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001743 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001744 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001745 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001746 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001747 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001748 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001749 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001750 unsigned AddrSpace;
1751 if (ParseOptionalAddrSpace(AddrSpace) ||
1752 ParseToken(lltok::star, "expected '*' in address space"))
1753 return true;
1754
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001755 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756 break;
1757 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001758
Chris Lattnerac161bf2009-01-02 07:01:27 +00001759 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1760 case lltok::lparen:
1761 if (ParseFunctionType(Result))
1762 return true;
1763 break;
1764 }
1765 }
1766}
1767
1768/// ParseParameterList
1769/// ::= '(' ')'
1770/// ::= '(' Arg (',' Arg)* ')'
1771/// Arg
1772/// ::= Type OptionalAttributes Value OptionalAttributes
1773bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001774 PerFunctionState &PFS, bool IsMustTailCall,
1775 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776 if (ParseToken(lltok::lparen, "expected '(' in call"))
1777 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001778
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001779 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001780 while (Lex.getKind() != lltok::rparen) {
1781 // If this isn't the first argument, we need a comma.
1782 if (!ArgList.empty() &&
1783 ParseToken(lltok::comma, "expected ',' in argument list"))
1784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001785
Reid Kleckner83498642014-08-26 00:33:28 +00001786 // Parse an ellipsis if this is a musttail call in a variadic function.
1787 if (Lex.getKind() == lltok::dotdotdot) {
1788 const char *Msg = "unexpected ellipsis in argument list for ";
1789 if (!IsMustTailCall)
1790 return TokError(Twine(Msg) + "non-musttail call");
1791 if (!InVarArgsFunc)
1792 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1793 Lex.Lex(); // Lex the '...', it is purely for readability.
1794 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1795 }
1796
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797 // Parse the argument.
1798 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001799 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001800 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001802 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001804
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001805 if (ArgTy->isMetadataTy()) {
1806 if (ParseMetadataAsValue(V, PFS))
1807 return true;
1808 } else {
1809 // Otherwise, handle normal operands.
1810 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1811 return true;
1812 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001813 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1814 AttrIndex++,
1815 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001816 }
1817
Reid Kleckner83498642014-08-26 00:33:28 +00001818 if (IsMustTailCall && InVarArgsFunc)
1819 return TokError("expected '...' at end of argument list for musttail call "
1820 "in varargs function");
1821
Chris Lattnerac161bf2009-01-02 07:01:27 +00001822 Lex.Lex(); // Lex the ')'.
1823 return false;
1824}
1825
1826
1827
Chris Lattner2ed06b42009-01-05 18:34:07 +00001828/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001829/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001830/// ::= '(' ArgTypeListI ')'
1831/// ArgTypeListI
1832/// ::= /*empty*/
1833/// ::= '...'
1834/// ::= ArgTypeList ',' '...'
1835/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001836///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001837bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1838 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839 isVarArg = false;
1840 assert(Lex.getKind() == lltok::lparen);
1841 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001842
Chris Lattnerac161bf2009-01-02 07:01:27 +00001843 if (Lex.getKind() == lltok::rparen) {
1844 // empty
1845 } else if (Lex.getKind() == lltok::dotdotdot) {
1846 isVarArg = true;
1847 Lex.Lex();
1848 } else {
1849 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001850 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001851 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001852 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001853
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001854 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001855 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001856
Chris Lattnerfdd87902009-10-05 05:54:46 +00001857 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001858 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001859
Chris Lattnerdef19492011-06-17 06:36:20 +00001860 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001861 Name = Lex.getStrVal();
1862 Lex.Lex();
1863 }
Chris Lattner3822f632009-01-02 08:05:26 +00001864
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001865 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001866 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001867
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001868 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001869 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001870 AttributeSet::get(ArgTy->getContext(),
1871 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001872
Chris Lattner3822f632009-01-02 08:05:26 +00001873 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001874 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001875 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001877 break;
1878 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001879
Chris Lattnerac161bf2009-01-02 07:01:27 +00001880 // Otherwise must be an argument type.
1881 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001882 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001883
Chris Lattnerfdd87902009-10-05 05:54:46 +00001884 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001885 return Error(TypeLoc, "argument can not have void type");
1886
Chris Lattnerdef19492011-06-17 06:36:20 +00001887 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001888 Name = Lex.getStrVal();
1889 Lex.Lex();
1890 } else {
1891 Name = "";
1892 }
Chris Lattner3822f632009-01-02 08:05:26 +00001893
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001894 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001895 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001896
Bill Wendlingd079a442012-10-15 04:46:55 +00001897 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001898 AttributeSet::get(ArgTy->getContext(),
1899 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001900 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001901 }
1902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001903
Chris Lattner3822f632009-01-02 08:05:26 +00001904 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001905}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001906
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907/// ParseFunctionType
1908/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001909bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001910 assert(Lex.getKind() == lltok::lparen);
1911
Chris Lattnerce473c72009-01-05 08:04:33 +00001912 if (!FunctionType::isValidReturnType(Result))
1913 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001914
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001915 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001916 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001919
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920 // Reject names on the arguments lists.
1921 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1922 if (!ArgList[i].Name.empty())
1923 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001924 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001925 return Error(ArgList[i].Loc,
1926 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001928
Jay Foadb804a2b2011-07-12 14:06:48 +00001929 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001934 return false;
1935}
1936
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001937/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1938/// other structs.
1939bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1940 SmallVector<Type*, 8> Elts;
1941 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001942
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001943 Result = StructType::get(Context, Elts, Packed);
1944 return false;
1945}
1946
1947/// ParseStructDefinition - Parse a struct in a 'type' definition.
1948bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1949 std::pair<Type*, LocTy> &Entry,
1950 Type *&ResultTy) {
1951 // If the type was already defined, diagnose the redefinition.
1952 if (Entry.first && !Entry.second.isValid())
1953 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001954
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955 // If we have opaque, just return without filling in the definition for the
1956 // struct. This counts as a definition as far as the .ll file goes.
1957 if (EatIfPresent(lltok::kw_opaque)) {
1958 // This type is being defined, so clear the location to indicate this.
1959 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001960
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001961 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001962 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001963 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001964 ResultTy = Entry.first;
1965 return false;
1966 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001967
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001968 // If the type starts with '<', then it is either a packed struct or a vector.
1969 bool isPacked = EatIfPresent(lltok::less);
1970
1971 // If we don't have a struct, then we have a random type alias, which we
1972 // accept for compatibility with old files. These types are not allowed to be
1973 // forward referenced and not allowed to be recursive.
1974 if (Lex.getKind() != lltok::lbrace) {
1975 if (Entry.first)
1976 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001977
Craig Topper2617dcc2014-04-15 06:32:26 +00001978 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001979 if (isPacked)
1980 return ParseArrayVectorType(ResultTy, true);
1981 return ParseType(ResultTy);
1982 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 // This type is being defined, so clear the location to indicate this.
1985 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001986
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001988 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001989 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001990
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001991 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 SmallVector<Type*, 8> Body;
1994 if (ParseStructBody(Body) ||
1995 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1996 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001997
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001998 STy->setBody(Body, isPacked);
1999 ResultTy = STy;
2000 return false;
2001}
2002
2003
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009/// ::= '<' '{' Type (',' Type)* '}' '>'
2010bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 assert(Lex.getKind() == lltok::lbrace);
2012 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 // Handle the empty struct.
2015 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002016 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002017
Chris Lattnerf880ca22009-03-09 04:49:14 +00002018 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002019 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002020 if (ParseType(Ty)) return true;
2021 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002022
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002024 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002025
Chris Lattner3822f632009-01-02 08:05:26 +00002026 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002027 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002031 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002033 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002034 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002035
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002036 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002037}
2038
2039/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2040/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002041/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042/// ::= '[' APSINTVAL 'x' Types ']'
2043/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002044bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002045 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2046 Lex.getAPSIntVal().getBitWidth() > 64)
2047 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002048
Chris Lattnerac161bf2009-01-02 07:01:27 +00002049 LocTy SizeLoc = Lex.getLoc();
2050 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002051 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002052
Chris Lattner3822f632009-01-02 08:05:26 +00002053 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2054 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055
2056 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002057 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002059
Chris Lattner3822f632009-01-02 08:05:26 +00002060 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2061 "expected end of sequential type"))
2062 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002063
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002065 if (Size == 0)
2066 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 if ((unsigned)Size != Size)
2068 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002069 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002070 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002071 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002073 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002074 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002075 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076 }
2077 return false;
2078}
2079
2080//===----------------------------------------------------------------------===//
2081// Function Semantic Analysis.
2082//===----------------------------------------------------------------------===//
2083
Chris Lattner3432c622009-10-28 03:39:23 +00002084LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2085 int functionNumber)
2086 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087
2088 // Insert unnamed arguments into the NumberedVals list.
2089 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2090 AI != E; ++AI)
2091 if (!AI->hasName())
2092 NumberedVals.push_back(AI);
2093}
2094
2095LLParser::PerFunctionState::~PerFunctionState() {
2096 // If there were any forward referenced non-basicblock values, delete them.
2097 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2098 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2099 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002100 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002101 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002103 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002105
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2107 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2108 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002109 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002110 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002112 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 }
2114}
2115
Chris Lattner3432c622009-10-28 03:39:23 +00002116bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 if (!ForwardRefVals.empty())
2118 return P.Error(ForwardRefVals.begin()->second.second,
2119 "use of undefined value '%" + ForwardRefVals.begin()->first +
2120 "'");
2121 if (!ForwardRefValIDs.empty())
2122 return P.Error(ForwardRefValIDs.begin()->second.second,
2123 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002124 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 return false;
2126}
2127
2128
2129/// GetVal - Get a value with the specified name or ID, creating a
2130/// forward reference record if needed. This can return null if the value
2131/// exists but does not have the right type.
2132Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002133 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 // Look this name up in the normal function symbol table.
2135 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002136
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 // If this is a forward reference for the value, see if we already created a
2138 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002139 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2141 I = ForwardRefVals.find(Name);
2142 if (I != ForwardRefVals.end())
2143 Val = I->second.first;
2144 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002145
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 // If we have the value in the symbol table or fwd-ref table, return it.
2147 if (Val) {
2148 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002149 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 P.Error(Loc, "'%" + Name + "' is not a basic block");
2151 else
2152 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002153 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002154 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002158 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002160 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002161 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002162
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 // Otherwise, create a new forward reference for this value and remember it.
2164 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002165 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002166 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 else
2168 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002169
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2171 return FwdVal;
2172}
2173
Chris Lattner229907c2011-07-18 04:54:35 +00002174Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 LocTy Loc) {
2176 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002177 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002178
Chris Lattnerac161bf2009-01-02 07:01:27 +00002179 // If this is a forward reference for the value, see if we already created a
2180 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002181 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2183 I = ForwardRefValIDs.find(ID);
2184 if (I != ForwardRefValIDs.end())
2185 Val = I->second.first;
2186 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002187
Chris Lattnerac161bf2009-01-02 07:01:27 +00002188 // If we have the value in the symbol table or fwd-ref table, return it.
2189 if (Val) {
2190 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002191 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002192 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002194 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002195 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002196 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002198
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002199 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002201 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002203
Chris Lattnerac161bf2009-01-02 07:01:27 +00002204 // Otherwise, create a new forward reference for this value and remember it.
2205 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002206 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002207 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 else
2209 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattnerac161bf2009-01-02 07:01:27 +00002211 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2212 return FwdVal;
2213}
2214
2215/// SetInstName - After an instruction is parsed and inserted into its
2216/// basic block, this installs its name.
2217bool LLParser::PerFunctionState::SetInstName(int NameID,
2218 const std::string &NameStr,
2219 LocTy NameLoc, Instruction *Inst) {
2220 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002221 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 if (NameID != -1 || !NameStr.empty())
2223 return P.Error(NameLoc, "instructions returning void cannot have a name");
2224 return false;
2225 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattnerac161bf2009-01-02 07:01:27 +00002227 // If this was a numbered instruction, verify that the instruction is the
2228 // expected value and resolve any forward references.
2229 if (NameStr.empty()) {
2230 // If neither a name nor an ID was specified, just use the next ID.
2231 if (NameID == -1)
2232 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 if (unsigned(NameID) != NumberedVals.size())
2235 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002236 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002237
Chris Lattnerac161bf2009-01-02 07:01:27 +00002238 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2239 ForwardRefValIDs.find(NameID);
2240 if (FI != ForwardRefValIDs.end()) {
2241 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002242 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002243 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002245 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 ForwardRefValIDs.erase(FI);
2247 }
2248
2249 NumberedVals.push_back(Inst);
2250 return false;
2251 }
2252
2253 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2254 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2255 FI = ForwardRefVals.find(NameStr);
2256 if (FI != ForwardRefVals.end()) {
2257 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002258 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002259 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002261 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 ForwardRefVals.erase(FI);
2263 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002264
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 // Set the name on the instruction.
2266 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002267
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002268 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002269 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 NameStr + "'");
2271 return false;
2272}
2273
2274/// GetBB - Get a basic block with the specified name or ID, creating a
2275/// forward reference record if needed.
2276BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2277 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002278 return cast_or_null<BasicBlock>(GetVal(Name,
2279 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280}
2281
2282BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002283 return cast_or_null<BasicBlock>(GetVal(ID,
2284 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285}
2286
2287/// DefineBB - Define the specified basic block, which is either named or
2288/// unnamed. If there is an error, this returns null otherwise it returns
2289/// the block being defined.
2290BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2291 LocTy Loc) {
2292 BasicBlock *BB;
2293 if (Name.empty())
2294 BB = GetBB(NumberedVals.size(), Loc);
2295 else
2296 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002297 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 // Move the block to the end of the function. Forward ref'd blocks are
2300 // inserted wherever they happen to be referenced.
2301 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303 // Remove the block from forward ref sets.
2304 if (Name.empty()) {
2305 ForwardRefValIDs.erase(NumberedVals.size());
2306 NumberedVals.push_back(BB);
2307 } else {
2308 // BB forward references are already in the function symbol table.
2309 ForwardRefVals.erase(Name);
2310 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002311
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 return BB;
2313}
2314
2315//===----------------------------------------------------------------------===//
2316// Constants.
2317//===----------------------------------------------------------------------===//
2318
2319/// ParseValID - Parse an abstract value that doesn't necessarily have a
2320/// type implied. For example, if we parse "4" we don't know what integer type
2321/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002322/// sanity. PFS is used to convert function-local operands of metadata (since
2323/// metadata operands are not just parsed here but also converted to values).
2324/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002325bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 ID.Loc = Lex.getLoc();
2327 switch (Lex.getKind()) {
2328 default: return TokError("expected value token");
2329 case lltok::GlobalID: // @42
2330 ID.UIntVal = Lex.getUIntVal();
2331 ID.Kind = ValID::t_GlobalID;
2332 break;
2333 case lltok::GlobalVar: // @foo
2334 ID.StrVal = Lex.getStrVal();
2335 ID.Kind = ValID::t_GlobalName;
2336 break;
2337 case lltok::LocalVarID: // %42
2338 ID.UIntVal = Lex.getUIntVal();
2339 ID.Kind = ValID::t_LocalID;
2340 break;
2341 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 ID.StrVal = Lex.getStrVal();
2343 ID.Kind = ValID::t_LocalName;
2344 break;
2345 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002346 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002347 ID.Kind = ValID::t_APSInt;
2348 break;
2349 case lltok::APFloat:
2350 ID.APFloatVal = Lex.getAPFloatVal();
2351 ID.Kind = ValID::t_APFloat;
2352 break;
2353 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002354 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002355 ID.Kind = ValID::t_Constant;
2356 break;
2357 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002358 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 ID.Kind = ValID::t_Constant;
2360 break;
2361 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2362 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2363 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002364
Chris Lattnerac161bf2009-01-02 07:01:27 +00002365 case lltok::lbrace: {
2366 // ValID ::= '{' ConstVector '}'
2367 Lex.Lex();
2368 SmallVector<Constant*, 16> Elts;
2369 if (ParseGlobalValueVector(Elts) ||
2370 ParseToken(lltok::rbrace, "expected end of struct constant"))
2371 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002372
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002373 ID.ConstantStructElts = new Constant*[Elts.size()];
2374 ID.UIntVal = Elts.size();
2375 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2376 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377 return false;
2378 }
2379 case lltok::less: {
2380 // ValID ::= '<' ConstVector '>' --> Vector.
2381 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2382 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002383 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 SmallVector<Constant*, 16> Elts;
2386 LocTy FirstEltLoc = Lex.getLoc();
2387 if (ParseGlobalValueVector(Elts) ||
2388 (isPackedStruct &&
2389 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2390 ParseToken(lltok::greater, "expected end of constant"))
2391 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002392
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002394 ID.ConstantStructElts = new Constant*[Elts.size()];
2395 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2396 ID.UIntVal = Elts.size();
2397 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 return false;
2399 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002400
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401 if (Elts.empty())
2402 return Error(ID.Loc, "constant vector must not be empty");
2403
Duncan Sands9dff9be2010-02-15 16:12:20 +00002404 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002405 !Elts[0]->getType()->isFloatingPointTy() &&
2406 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002408 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002409
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 // Verify that all the vector elements have the same type.
2411 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2412 if (Elts[i]->getType() != Elts[0]->getType())
2413 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002414 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002415 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattner69229312011-02-15 00:14:00 +00002417 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002418 ID.Kind = ValID::t_Constant;
2419 return false;
2420 }
2421 case lltok::lsquare: { // Array Constant
2422 Lex.Lex();
2423 SmallVector<Constant*, 16> Elts;
2424 LocTy FirstEltLoc = Lex.getLoc();
2425 if (ParseGlobalValueVector(Elts) ||
2426 ParseToken(lltok::rsquare, "expected end of array constant"))
2427 return true;
2428
2429 // Handle empty element.
2430 if (Elts.empty()) {
2431 // Use undef instead of an array because it's inconvenient to determine
2432 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002433 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434 return false;
2435 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002436
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002438 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002439 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002440
Owen Anderson4056ca92009-07-29 22:17:13 +00002441 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002444 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 if (Elts[i]->getType() != Elts[0]->getType())
2446 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002447 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002448 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002450
Jay Foad83be3612011-06-22 09:24:39 +00002451 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 ID.Kind = ValID::t_Constant;
2453 return false;
2454 }
2455 case lltok::kw_c: // c "foo"
2456 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002457 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2458 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2460 ID.Kind = ValID::t_Constant;
2461 return false;
2462
2463 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002464 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2465 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002466 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 Lex.Lex();
2468 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002469 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002470 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002471 ParseStringConstant(ID.StrVal) ||
2472 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 ParseToken(lltok::StringConstant, "expected constraint string"))
2474 return true;
2475 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002476 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002477 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 ID.Kind = ValID::t_InlineAsm;
2479 return false;
2480 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002481
Chris Lattner3432c622009-10-28 03:39:23 +00002482 case lltok::kw_blockaddress: {
2483 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2484 Lex.Lex();
2485
2486 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002487
Chris Lattner3432c622009-10-28 03:39:23 +00002488 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2489 ParseValID(Fn) ||
2490 ParseToken(lltok::comma, "expected comma in block address expression")||
2491 ParseValID(Label) ||
2492 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2493 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002494
Chris Lattner3432c622009-10-28 03:39:23 +00002495 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2496 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002497 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002498 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002499
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002500 // Try to find the function (but skip it if it's forward-referenced).
2501 GlobalValue *GV = nullptr;
2502 if (Fn.Kind == ValID::t_GlobalID) {
2503 if (Fn.UIntVal < NumberedVals.size())
2504 GV = NumberedVals[Fn.UIntVal];
2505 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2506 GV = M->getNamedValue(Fn.StrVal);
2507 }
2508 Function *F = nullptr;
2509 if (GV) {
2510 // Confirm that it's actually a function with a definition.
2511 if (!isa<Function>(GV))
2512 return Error(Fn.Loc, "expected function name in blockaddress");
2513 F = cast<Function>(GV);
2514 if (F->isDeclaration())
2515 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2516 }
2517
2518 if (!F) {
2519 // Make a global variable as a placeholder for this reference.
2520 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2521 if (!FwdRef)
2522 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2523 GlobalValue::InternalLinkage, nullptr, "");
2524 ID.ConstantVal = FwdRef;
2525 ID.Kind = ValID::t_Constant;
2526 return false;
2527 }
2528
2529 // We found the function; now find the basic block. Don't use PFS, since we
2530 // might be inside a constant expression.
2531 BasicBlock *BB;
2532 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2533 if (Label.Kind == ValID::t_LocalID)
2534 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2535 else
2536 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2537 if (!BB)
2538 return Error(Label.Loc, "referenced value is not a basic block");
2539 } else {
2540 if (Label.Kind == ValID::t_LocalID)
2541 return Error(Label.Loc, "cannot take address of numeric label after "
2542 "the function is defined");
2543 BB = dyn_cast_or_null<BasicBlock>(
2544 F->getValueSymbolTable().lookup(Label.StrVal));
2545 if (!BB)
2546 return Error(Label.Loc, "referenced value is not a basic block");
2547 }
2548
2549 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002550 ID.Kind = ValID::t_Constant;
2551 return false;
2552 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002553
Chris Lattnerac161bf2009-01-02 07:01:27 +00002554 case lltok::kw_trunc:
2555 case lltok::kw_zext:
2556 case lltok::kw_sext:
2557 case lltok::kw_fptrunc:
2558 case lltok::kw_fpext:
2559 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002560 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 case lltok::kw_uitofp:
2562 case lltok::kw_sitofp:
2563 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002564 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002568 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 Constant *SrcVal;
2570 Lex.Lex();
2571 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2572 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002573 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 ParseType(DestTy) ||
2575 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2576 return true;
2577 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2578 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002579 getTypeString(SrcVal->getType()) + "' to '" +
2580 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002581 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002582 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002583 ID.Kind = ValID::t_Constant;
2584 return false;
2585 }
2586 case lltok::kw_extractvalue: {
2587 Lex.Lex();
2588 Constant *Val;
2589 SmallVector<unsigned, 4> Indices;
2590 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2591 ParseGlobalTypeAndValue(Val) ||
2592 ParseIndexList(Indices) ||
2593 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2594 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002595
Chris Lattner392be582010-02-12 20:49:41 +00002596 if (!Val->getType()->isAggregateType())
2597 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002598 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002600 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002601 ID.Kind = ValID::t_Constant;
2602 return false;
2603 }
2604 case lltok::kw_insertvalue: {
2605 Lex.Lex();
2606 Constant *Val0, *Val1;
2607 SmallVector<unsigned, 4> Indices;
2608 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2609 ParseGlobalTypeAndValue(Val0) ||
2610 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2611 ParseGlobalTypeAndValue(Val1) ||
2612 ParseIndexList(Indices) ||
2613 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2614 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002615 if (!Val0->getType()->isAggregateType())
2616 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002617 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002618 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002619 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 ID.Kind = ValID::t_Constant;
2621 return false;
2622 }
2623 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002624 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002625 unsigned PredVal, Opc = Lex.getUIntVal();
2626 Constant *Val0, *Val1;
2627 Lex.Lex();
2628 if (ParseCmpPredicate(PredVal, Opc) ||
2629 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2630 ParseGlobalTypeAndValue(Val0) ||
2631 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2632 ParseGlobalTypeAndValue(Val1) ||
2633 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2634 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002635
Chris Lattnerac161bf2009-01-02 07:01:27 +00002636 if (Val0->getType() != Val1->getType())
2637 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002638
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002640
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002642 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002644 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002645 } else {
2646 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002647 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002648 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002650 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 }
2652 ID.Kind = ValID::t_Constant;
2653 return false;
2654 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002655
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656 // Binary Operators.
2657 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002658 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002660 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002662 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 case lltok::kw_udiv:
2664 case lltok::kw_sdiv:
2665 case lltok::kw_fdiv:
2666 case lltok::kw_urem:
2667 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002668 case lltok::kw_frem:
2669 case lltok::kw_shl:
2670 case lltok::kw_lshr:
2671 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002672 bool NUW = false;
2673 bool NSW = false;
2674 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 unsigned Opc = Lex.getUIntVal();
2676 Constant *Val0, *Val1;
2677 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002678 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002679 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2680 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002681 if (EatIfPresent(lltok::kw_nuw))
2682 NUW = true;
2683 if (EatIfPresent(lltok::kw_nsw)) {
2684 NSW = true;
2685 if (EatIfPresent(lltok::kw_nuw))
2686 NUW = true;
2687 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002688 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2689 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002690 if (EatIfPresent(lltok::kw_exact))
2691 Exact = true;
2692 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2694 ParseGlobalTypeAndValue(Val0) ||
2695 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2696 ParseGlobalTypeAndValue(Val1) ||
2697 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2698 return true;
2699 if (Val0->getType() != Val1->getType())
2700 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002701 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002702 if (NUW)
2703 return Error(ModifierLoc, "nuw only applies to integer operations");
2704 if (NSW)
2705 return Error(ModifierLoc, "nsw only applies to integer operations");
2706 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002707 // Check that the type is valid for the operator.
2708 switch (Opc) {
2709 case Instruction::Add:
2710 case Instruction::Sub:
2711 case Instruction::Mul:
2712 case Instruction::UDiv:
2713 case Instruction::SDiv:
2714 case Instruction::URem:
2715 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002716 case Instruction::Shl:
2717 case Instruction::AShr:
2718 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002719 if (!Val0->getType()->isIntOrIntVectorTy())
2720 return Error(ID.Loc, "constexpr requires integer operands");
2721 break;
2722 case Instruction::FAdd:
2723 case Instruction::FSub:
2724 case Instruction::FMul:
2725 case Instruction::FDiv:
2726 case Instruction::FRem:
2727 if (!Val0->getType()->isFPOrFPVectorTy())
2728 return Error(ID.Loc, "constexpr requires fp operands");
2729 break;
2730 default: llvm_unreachable("Unknown binary operator!");
2731 }
Dan Gohman1b849082009-09-07 23:54:19 +00002732 unsigned Flags = 0;
2733 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2734 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002735 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002736 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002737 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002738 ID.Kind = ValID::t_Constant;
2739 return false;
2740 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 case lltok::kw_and:
2744 case lltok::kw_or:
2745 case lltok::kw_xor: {
2746 unsigned Opc = Lex.getUIntVal();
2747 Constant *Val0, *Val1;
2748 Lex.Lex();
2749 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2750 ParseGlobalTypeAndValue(Val0) ||
2751 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2752 ParseGlobalTypeAndValue(Val1) ||
2753 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2754 return true;
2755 if (Val0->getType() != Val1->getType())
2756 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002757 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 return Error(ID.Loc,
2759 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002760 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 ID.Kind = ValID::t_Constant;
2762 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002763 }
2764
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 case lltok::kw_getelementptr:
2766 case lltok::kw_shufflevector:
2767 case lltok::kw_insertelement:
2768 case lltok::kw_extractelement:
2769 case lltok::kw_select: {
2770 unsigned Opc = Lex.getUIntVal();
2771 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002772 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002773 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002774 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002775 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2777 ParseGlobalValueVector(Elts) ||
2778 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2779 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002780
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002782 if (Elts.size() == 0 ||
2783 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002785
Jay Foaded8db7d2011-07-21 14:31:17 +00002786 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002787 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002789 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2790 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 } else if (Opc == Instruction::Select) {
2792 if (Elts.size() != 3)
2793 return Error(ID.Loc, "expected three operands to select");
2794 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2795 Elts[2]))
2796 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002797 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002798 } else if (Opc == Instruction::ShuffleVector) {
2799 if (Elts.size() != 3)
2800 return Error(ID.Loc, "expected three operands to shufflevector");
2801 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2802 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002803 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002804 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 } else if (Opc == Instruction::ExtractElement) {
2806 if (Elts.size() != 2)
2807 return Error(ID.Loc, "expected two operands to extractelement");
2808 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2809 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002810 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 } else {
2812 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2813 if (Elts.size() != 3)
2814 return Error(ID.Loc, "expected three operands to insertelement");
2815 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2816 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002817 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002818 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002819 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002820
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 ID.Kind = ValID::t_Constant;
2822 return false;
2823 }
2824 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002825
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 Lex.Lex();
2827 return false;
2828}
2829
2830/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002831bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002832 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002834 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002835 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002836 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002837 if (V && !(C = dyn_cast<Constant>(V)))
2838 return Error(ID.Loc, "global values must be constants");
2839 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840}
2841
Victor Hernandez9d75c962010-01-11 22:31:58 +00002842bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002843 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002844 return ParseType(Ty) ||
2845 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002846}
2847
Rafael Espindola83a362c2015-01-06 22:55:16 +00002848bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002849 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002850
2851 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002852 if (!EatIfPresent(lltok::kw_comdat))
2853 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002854
2855 if (EatIfPresent(lltok::lparen)) {
2856 if (Lex.getKind() != lltok::ComdatVar)
2857 return TokError("expected comdat variable");
2858 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2859 Lex.Lex();
2860 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2861 return true;
2862 } else {
2863 if (GlobalName.empty())
2864 return TokError("comdat cannot be unnamed");
2865 C = getComdat(GlobalName, KwLoc);
2866 }
2867
David Majnemerdad0a642014-06-27 18:19:56 +00002868 return false;
2869}
2870
Victor Hernandez9d75c962010-01-11 22:31:58 +00002871/// ParseGlobalValueVector
2872/// ::= /*empty*/
2873/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002874bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002875 // Empty list.
2876 if (Lex.getKind() == lltok::rbrace ||
2877 Lex.getKind() == lltok::rsquare ||
2878 Lex.getKind() == lltok::greater ||
2879 Lex.getKind() == lltok::rparen)
2880 return false;
2881
2882 Constant *C;
2883 if (ParseGlobalTypeAndValue(C)) return true;
2884 Elts.push_back(C);
2885
2886 while (EatIfPresent(lltok::comma)) {
2887 if (ParseGlobalTypeAndValue(C)) return true;
2888 Elts.push_back(C);
2889 }
2890
2891 return false;
2892}
2893
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002894bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002895 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002896 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002897 return true;
2898
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002899 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002900 return false;
2901}
2902
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002903/// MDNode:
2904/// ::= !{ ... }
2905/// ::= !7
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002906/// ::= !MDLocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002907bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002908 if (Lex.getKind() == lltok::MetadataVar)
2909 return ParseSpecializedMDNode(N);
2910
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002911 return ParseToken(lltok::exclaim, "expected '!' here") ||
2912 ParseMDNodeTail(N);
2913}
2914
2915bool LLParser::ParseMDNodeTail(MDNode *&N) {
2916 // !{ ... }
2917 if (Lex.getKind() == lltok::lbrace)
2918 return ParseMDTuple(N);
2919
2920 // !42
2921 return ParseMDNodeID(N);
2922}
2923
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002924bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
2925 MDUnsignedField<uint32_t> &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002926 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2927 return TokError("expected unsigned integer");
2928 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(Result.Max + 1ull);
2929
2930 if (Val64 > Result.Max)
2931 return TokError("value for '" + Name + "' too large, limit is " +
2932 Twine(Result.Max));
2933 Result.assign(Val64);
2934 Lex.Lex();
2935 return false;
2936}
2937
2938bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002939 Metadata *MD;
2940 if (ParseMetadata(MD, nullptr))
2941 return true;
2942
2943 Result.assign(MD);
2944 return false;
2945}
2946
2947template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00002948bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002949 do {
2950 if (Lex.getKind() != lltok::LabelStr)
2951 return TokError("expected field label here");
2952
2953 if (parseField())
2954 return true;
2955 } while (EatIfPresent(lltok::comma));
2956
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00002957 return false;
2958}
2959
2960template <class ParserTy>
2961bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
2962 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
2963 Lex.Lex();
2964
2965 if (ParseToken(lltok::lparen, "expected '(' here"))
2966 return true;
2967 if (Lex.getKind() != lltok::rparen)
2968 if (ParseMDFieldsImplBody(parseField))
2969 return true;
2970
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00002971 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002972 return ParseToken(lltok::rparen, "expected ')' here");
2973}
2974
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00002975template <class FieldTy>
2976bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
2977 if (Result.Seen)
2978 return TokError("field '" + Name + "' cannot be specified more than once");
2979
2980 LocTy Loc = Lex.getLoc();
2981 Lex.Lex();
2982 return ParseMDField(Loc, Name, Result);
2983}
2984
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002985bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
2986 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
2987#define DISPATCH_TO_PARSER(CLASS) \
2988 if (Lex.getStrVal() == #CLASS) \
2989 return Parse##CLASS(N, IsDistinct);
2990
2991 DISPATCH_TO_PARSER(MDLocation);
2992#undef DISPATCH_TO_PARSER
2993
2994 return TokError("expected metadata type");
2995}
2996
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00002997#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
2998#define NOP_FIELD(NAME, TYPE, INIT)
2999#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3000 if (!NAME.Seen) \
3001 return Error(ClosingLoc, "missing required field '" #NAME "'");
3002#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003003 if (Lex.getStrVal() == #NAME) \
3004 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003005#define PARSE_MD_FIELDS() \
3006 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3007 do { \
3008 LocTy ClosingLoc; \
3009 if (ParseMDFieldsImpl([&]() -> bool { \
3010 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3011 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3012 }, ClosingLoc)) \
3013 return true; \
3014 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3015 } while (false)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003016
3017/// ParseMDLocationFields:
3018/// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3019bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003020#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3021 OPTIONAL(line, MDUnsignedField<uint32_t>, (0, ~0u >> 8)); \
3022 OPTIONAL(column, MDUnsignedField<uint32_t>, (0, ~0u >> 16)); \
3023 REQUIRED(scope, MDField, ); \
3024 OPTIONAL(inlinedAt, MDField, );
3025 PARSE_MD_FIELDS();
3026#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003027
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003028 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3029 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3030 return false;
3031}
3032#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003033#undef NOP_FIELD
3034#undef REQUIRE_FIELD
3035#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003036
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003037/// ParseMetadataAsValue
3038/// ::= metadata i32 %local
3039/// ::= metadata i32 @global
3040/// ::= metadata i32 7
3041/// ::= metadata !0
3042/// ::= metadata !{...}
3043/// ::= metadata !"string"
3044bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3045 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003046 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003047 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003048 return true;
3049
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003050 V = MetadataAsValue::get(Context, MD);
3051 return false;
3052}
3053
3054/// ParseValueAsMetadata
3055/// ::= i32 %local
3056/// ::= i32 @global
3057/// ::= i32 7
3058bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
3059 Type *Ty;
3060 LocTy Loc;
3061 if (ParseType(Ty, "expected metadata operand", Loc))
3062 return true;
3063 if (Ty->isMetadataTy())
3064 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3065
3066 Value *V;
3067 if (ParseValue(Ty, V, PFS))
3068 return true;
3069
3070 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003071 return false;
3072}
3073
3074/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003075/// ::= i32 %local
3076/// ::= i32 @global
3077/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003078/// ::= !42
3079/// ::= !{...}
3080/// ::= !"string"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003081/// ::= !MDLocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003082bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003083 if (Lex.getKind() == lltok::MetadataVar) {
3084 MDNode *N;
3085 if (ParseSpecializedMDNode(N))
3086 return true;
3087 MD = N;
3088 return false;
3089 }
3090
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003091 // ValueAsMetadata:
3092 // <type> <value>
3093 if (Lex.getKind() != lltok::exclaim)
3094 return ParseValueAsMetadata(MD, PFS);
3095
3096 // '!'.
3097 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3098 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003099
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003100 // MDString:
3101 // ::= '!' STRINGCONSTANT
3102 if (Lex.getKind() == lltok::StringConstant) {
3103 MDString *S;
3104 if (ParseMDString(S))
3105 return true;
3106 MD = S;
3107 return false;
3108 }
3109
Dan Gohman8939ba332010-07-14 18:26:50 +00003110 // MDNode:
3111 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003112 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003113 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003114 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003115 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003116 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003117 return false;
3118}
3119
Victor Hernandez9d75c962010-01-11 22:31:58 +00003120
3121//===----------------------------------------------------------------------===//
3122// Function Parsing.
3123//===----------------------------------------------------------------------===//
3124
Chris Lattner229907c2011-07-18 04:54:35 +00003125bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003126 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003127 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003128 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003129
Chris Lattnerac161bf2009-01-02 07:01:27 +00003130 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003131 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003132 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3133 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003134 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003135 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003136 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3137 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003138 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003139 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003140 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003141 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003142 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003143 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3144 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003145 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003146 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003147 return false;
3148 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003149 case ValID::t_GlobalName:
3150 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003151 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003152 case ValID::t_GlobalID:
3153 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003154 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003155 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003156 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003157 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003158 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003159 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003160 return false;
3161 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003162 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003163 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3164 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003165
Dan Gohman518cda42011-12-17 00:04:22 +00003166 // The lexer has no type info, so builds all half, float, and double FP
3167 // constants as double. Fix this here. Long double does not need this.
3168 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003169 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003170 if (Ty->isHalfTy())
3171 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3172 &Ignored);
3173 else if (Ty->isFloatTy())
3174 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3175 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003177 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003178
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003179 if (V->getType() != Ty)
3180 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003181 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003182
Chris Lattnerac161bf2009-01-02 07:01:27 +00003183 return false;
3184 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003185 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003186 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003187 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003188 return false;
3189 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003190 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003191 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003192 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003193 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003194 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003195 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003196 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003197 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003198 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003199 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003201 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003202 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003204 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 return false;
3206 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003207 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003209
Chris Lattnerac161bf2009-01-02 07:01:27 +00003210 V = ID.ConstantVal;
3211 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003212 case ValID::t_ConstantStruct:
3213 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003214 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003215 if (ST->getNumElements() != ID.UIntVal)
3216 return Error(ID.Loc,
3217 "initializer with struct type has wrong # elements");
3218 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3219 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003220
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003221 // Verify that the elements are compatible with the structtype.
3222 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3223 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3224 return Error(ID.Loc, "element " + Twine(i) +
3225 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003226
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003227 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3228 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003229 } else
3230 return Error(ID.Loc, "constant expression type mismatch");
3231 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003232 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003233 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003234}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003235
Chris Lattner229907c2011-07-18 04:54:35 +00003236bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003237 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003238 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003239 return ParseValID(ID, PFS) ||
3240 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241}
3242
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003243bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003244 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003245 return ParseType(Ty) ||
3246 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247}
3248
Chris Lattner3ed871f2009-10-27 19:13:16 +00003249bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3250 PerFunctionState &PFS) {
3251 Value *V;
3252 Loc = Lex.getLoc();
3253 if (ParseTypeAndValue(V, PFS)) return true;
3254 if (!isa<BasicBlock>(V))
3255 return Error(Loc, "expected a basic block");
3256 BB = cast<BasicBlock>(V);
3257 return false;
3258}
3259
3260
Chris Lattnerac161bf2009-01-02 07:01:27 +00003261/// FunctionHeader
3262/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003263/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003264/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003265bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3266 // Parse the linkage.
3267 LocTy LinkageLoc = Lex.getLoc();
3268 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003269
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003270 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003271 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003272 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003273 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003274 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003275 LocTy RetTypeLoc = Lex.getLoc();
3276 if (ParseOptionalLinkage(Linkage) ||
3277 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003278 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003279 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003280 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003281 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003282 return true;
3283
3284 // Verify that the linkage is ok.
3285 switch ((GlobalValue::LinkageTypes)Linkage) {
3286 case GlobalValue::ExternalLinkage:
3287 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003288 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003289 if (isDefine)
3290 return Error(LinkageLoc, "invalid linkage for function definition");
3291 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003292 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003293 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003294 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003295 case GlobalValue::LinkOnceAnyLinkage:
3296 case GlobalValue::LinkOnceODRLinkage:
3297 case GlobalValue::WeakAnyLinkage:
3298 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003299 if (!isDefine)
3300 return Error(LinkageLoc, "invalid linkage for function declaration");
3301 break;
3302 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003303 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003304 return Error(LinkageLoc, "invalid function linkage type");
3305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003306
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003307 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3308 return Error(LinkageLoc,
3309 "symbol with local linkage must have default visibility");
3310
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003311 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003312 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003313
Chris Lattnerac161bf2009-01-02 07:01:27 +00003314 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003315
3316 std::string FunctionName;
3317 if (Lex.getKind() == lltok::GlobalVar) {
3318 FunctionName = Lex.getStrVal();
3319 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3320 unsigned NameID = Lex.getUIntVal();
3321
3322 if (NameID != NumberedVals.size())
3323 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003324 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003325 } else {
3326 return TokError("expected function name");
3327 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003328
Chris Lattner3822f632009-01-02 08:05:26 +00003329 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003330
Chris Lattner3822f632009-01-02 08:05:26 +00003331 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003332 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003333
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003334 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003335 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003336 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003337 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003338 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003339 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003341 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003342 bool UnnamedAddr;
3343 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003344 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003345 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003346 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003348 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003349 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3350 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003351 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003352 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003353 (EatIfPresent(lltok::kw_section) &&
3354 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00003355 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003356 ParseOptionalAlignment(Alignment) ||
3357 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003358 ParseStringConstant(GC)) ||
3359 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003360 ParseGlobalTypeAndValue(Prefix)) ||
3361 (EatIfPresent(lltok::kw_prologue) &&
3362 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003363 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003364
Michael Gottesman41748d72013-06-27 00:25:01 +00003365 if (FuncAttrs.contains(Attribute::Builtin))
3366 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003367
Chris Lattnerac161bf2009-01-02 07:01:27 +00003368 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003369 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003370 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003371 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003372 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003373
Chris Lattnerac161bf2009-01-02 07:01:27 +00003374 // Okay, if we got here, the function is syntactically valid. Convert types
3375 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003376 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003377 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003378
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003379 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003380 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3381 AttributeSet::ReturnIndex,
3382 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003383
Chris Lattnerac161bf2009-01-02 07:01:27 +00003384 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003385 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003386 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3387 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003388 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3389 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003390 }
3391
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003392 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003393 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3394 AttributeSet::FunctionIndex,
3395 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003396
Bill Wendlinge94d8432012-12-07 23:16:57 +00003397 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003398
Bill Wendling749a43d2012-12-30 13:50:49 +00003399 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003400 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3401
Chris Lattner229907c2011-07-18 04:54:35 +00003402 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003403 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003404 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003405
Craig Topper2617dcc2014-04-15 06:32:26 +00003406 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003407 if (!FunctionName.empty()) {
3408 // If this was a definition of a forward reference, remove the definition
3409 // from the forward reference table and fill in the forward ref.
3410 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3411 ForwardRefVals.find(FunctionName);
3412 if (FRVI != ForwardRefVals.end()) {
3413 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003414 if (!Fn)
3415 return Error(FRVI->second.second, "invalid forward reference to "
3416 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003417 if (Fn->getType() != PFT)
3418 return Error(FRVI->second.second, "invalid forward reference to "
3419 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003420
Chris Lattnerac161bf2009-01-02 07:01:27 +00003421 ForwardRefVals.erase(FRVI);
3422 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003423 // Reject redefinitions.
3424 return Error(NameLoc, "invalid redefinition of function '" +
3425 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003426 } else if (M->getNamedValue(FunctionName)) {
3427 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003428 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003429
Dan Gohman399d6ae2009-08-29 23:37:49 +00003430 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003431 // If this is a definition of a forward referenced function, make sure the
3432 // types agree.
3433 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3434 = ForwardRefValIDs.find(NumberedVals.size());
3435 if (I != ForwardRefValIDs.end()) {
3436 Fn = cast<Function>(I->second.first);
3437 if (Fn->getType() != PFT)
3438 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003439 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003440 ForwardRefValIDs.erase(I);
3441 }
3442 }
3443
Craig Topper2617dcc2014-04-15 06:32:26 +00003444 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003445 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3446 else // Move the forward-reference to the correct spot in the module.
3447 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3448
3449 if (FunctionName.empty())
3450 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003451
Chris Lattnerac161bf2009-01-02 07:01:27 +00003452 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3453 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003454 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003455 Fn->setCallingConv(CC);
3456 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003457 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003458 Fn->setAlignment(Alignment);
3459 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003460 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003461 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003462 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003463 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003464 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003465
Chris Lattnerac161bf2009-01-02 07:01:27 +00003466 // Add all of the arguments we parsed to the function.
3467 Function::arg_iterator ArgIt = Fn->arg_begin();
3468 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3469 // If the argument has a name, insert it into the argument symbol table.
3470 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003471
Chris Lattnerac161bf2009-01-02 07:01:27 +00003472 // Set the name, if it conflicted, it will be auto-renamed.
3473 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003474
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003475 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003476 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3477 ArgList[i].Name + "'");
3478 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003479
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003480 if (isDefine)
3481 return false;
3482
Robin Morisset039781e2014-08-29 21:53:01 +00003483 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003484 ValID ID;
3485 if (FunctionName.empty()) {
3486 ID.Kind = ValID::t_GlobalID;
3487 ID.UIntVal = NumberedVals.size() - 1;
3488 } else {
3489 ID.Kind = ValID::t_GlobalName;
3490 ID.StrVal = FunctionName;
3491 }
3492 auto Blocks = ForwardRefBlockAddresses.find(ID);
3493 if (Blocks != ForwardRefBlockAddresses.end())
3494 return Error(Blocks->first.Loc,
3495 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003496 return false;
3497}
3498
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003499bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3500 ValID ID;
3501 if (FunctionNumber == -1) {
3502 ID.Kind = ValID::t_GlobalName;
3503 ID.StrVal = F.getName();
3504 } else {
3505 ID.Kind = ValID::t_GlobalID;
3506 ID.UIntVal = FunctionNumber;
3507 }
3508
3509 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3510 if (Blocks == P.ForwardRefBlockAddresses.end())
3511 return false;
3512
3513 for (const auto &I : Blocks->second) {
3514 const ValID &BBID = I.first;
3515 GlobalValue *GV = I.second;
3516
3517 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3518 "Expected local id or name");
3519 BasicBlock *BB;
3520 if (BBID.Kind == ValID::t_LocalName)
3521 BB = GetBB(BBID.StrVal, BBID.Loc);
3522 else
3523 BB = GetBB(BBID.UIntVal, BBID.Loc);
3524 if (!BB)
3525 return P.Error(BBID.Loc, "referenced value is not a basic block");
3526
3527 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3528 GV->eraseFromParent();
3529 }
3530
3531 P.ForwardRefBlockAddresses.erase(Blocks);
3532 return false;
3533}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003534
3535/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003536/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003537bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003538 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003539 return TokError("expected '{' in function body");
3540 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003541
Chris Lattner3432c622009-10-28 03:39:23 +00003542 int FunctionNumber = -1;
3543 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003544
Chris Lattner3432c622009-10-28 03:39:23 +00003545 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003546
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003547 // Resolve block addresses and allow basic blocks to be forward-declared
3548 // within this function.
3549 if (PFS.resolveForwardRefBlockAddresses())
3550 return true;
3551 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3552
Chris Lattnerbbddd962010-01-09 19:20:07 +00003553 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003554 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003555 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003556
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003557 while (Lex.getKind() != lltok::rbrace &&
3558 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003559 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003560
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003561 while (Lex.getKind() != lltok::rbrace)
3562 if (ParseUseListOrder(&PFS))
3563 return true;
3564
Chris Lattnerac161bf2009-01-02 07:01:27 +00003565 // Eat the }.
3566 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003567
Chris Lattnerac161bf2009-01-02 07:01:27 +00003568 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003569 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003570}
3571
3572/// ParseBasicBlock
3573/// ::= LabelStr? Instruction*
3574bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3575 // If this basic block starts out with a name, remember it.
3576 std::string Name;
3577 LocTy NameLoc = Lex.getLoc();
3578 if (Lex.getKind() == lltok::LabelStr) {
3579 Name = Lex.getStrVal();
3580 Lex.Lex();
3581 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003582
Chris Lattnerac161bf2009-01-02 07:01:27 +00003583 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003584 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003585
Chris Lattnerac161bf2009-01-02 07:01:27 +00003586 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003587
Chris Lattnerac161bf2009-01-02 07:01:27 +00003588 // Parse the instructions in this block until we get a terminator.
3589 Instruction *Inst;
3590 do {
3591 // This instruction may have three possibilities for a name: a) none
3592 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3593 LocTy NameLoc = Lex.getLoc();
3594 int NameID = -1;
3595 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003596
Chris Lattnerac161bf2009-01-02 07:01:27 +00003597 if (Lex.getKind() == lltok::LocalVarID) {
3598 NameID = Lex.getUIntVal();
3599 Lex.Lex();
3600 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3601 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003602 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003603 NameStr = Lex.getStrVal();
3604 Lex.Lex();
3605 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3606 return true;
3607 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003608
Chris Lattner77b89dc2009-12-30 05:23:43 +00003609 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003610 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003611 case InstError: return true;
3612 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003613 BB->getInstList().push_back(Inst);
3614
Chris Lattner77b89dc2009-12-30 05:23:43 +00003615 // With a normal result, we check to see if the instruction is followed by
3616 // a comma and metadata.
3617 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003618 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003619 return true;
3620 break;
3621 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003622 BB->getInstList().push_back(Inst);
3623
Chris Lattner77b89dc2009-12-30 05:23:43 +00003624 // If the instruction parser ate an extra comma at the end of it, it
3625 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003626 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003627 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003628 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003629 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003630
Chris Lattnerac161bf2009-01-02 07:01:27 +00003631 // Set the name on the instruction.
3632 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3633 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003634
Chris Lattnerac161bf2009-01-02 07:01:27 +00003635 return false;
3636}
3637
3638//===----------------------------------------------------------------------===//
3639// Instruction Parsing.
3640//===----------------------------------------------------------------------===//
3641
3642/// ParseInstruction - Parse one of the many different instructions.
3643///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003644int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3645 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003646 lltok::Kind Token = Lex.getKind();
3647 if (Token == lltok::Eof)
3648 return TokError("found end of file when expecting more instructions");
3649 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003650 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003651 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003652
Chris Lattnerac161bf2009-01-02 07:01:27 +00003653 switch (Token) {
3654 default: return Error(Loc, "expected instruction opcode");
3655 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003656 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003657 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3658 case lltok::kw_br: return ParseBr(Inst, PFS);
3659 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003660 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003661 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003662 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003663 // Binary Operators.
3664 case lltok::kw_add:
3665 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003666 case lltok::kw_mul:
3667 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003668 bool NUW = EatIfPresent(lltok::kw_nuw);
3669 bool NSW = EatIfPresent(lltok::kw_nsw);
3670 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003671
Chris Lattnera676c0f2011-02-07 16:40:21 +00003672 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003673
Chris Lattnera676c0f2011-02-07 16:40:21 +00003674 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3675 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3676 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003677 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003678 case lltok::kw_fadd:
3679 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003680 case lltok::kw_fmul:
3681 case lltok::kw_fdiv:
3682 case lltok::kw_frem: {
3683 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3684 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3685 if (Res != 0)
3686 return Res;
3687 if (FMF.any())
3688 Inst->setFastMathFlags(FMF);
3689 return 0;
3690 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003691
Chris Lattner35315d02011-02-06 21:44:57 +00003692 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003693 case lltok::kw_udiv:
3694 case lltok::kw_lshr:
3695 case lltok::kw_ashr: {
3696 bool Exact = EatIfPresent(lltok::kw_exact);
3697
3698 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3699 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3700 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003701 }
3702
Chris Lattnerac161bf2009-01-02 07:01:27 +00003703 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003704 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003705 case lltok::kw_and:
3706 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003707 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003708 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003709 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003710 // Casts.
3711 case lltok::kw_trunc:
3712 case lltok::kw_zext:
3713 case lltok::kw_sext:
3714 case lltok::kw_fptrunc:
3715 case lltok::kw_fpext:
3716 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003717 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003718 case lltok::kw_uitofp:
3719 case lltok::kw_sitofp:
3720 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003721 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003722 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003723 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003724 // Other.
3725 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003726 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003727 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3728 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3729 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3730 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003731 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003732 // Call.
3733 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3734 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3735 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003736 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003737 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003738 case lltok::kw_load: return ParseLoad(Inst, PFS);
3739 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003740 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3741 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003742 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003743 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3744 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3745 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3746 }
3747}
3748
3749/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3750bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003751 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003752 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003753 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003754 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3755 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3756 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3757 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3758 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3759 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3760 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3761 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3762 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3763 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3764 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3765 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3766 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3767 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3768 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3769 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3770 }
3771 } else {
3772 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003773 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003774 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3775 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3776 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3777 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3778 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3779 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3780 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3781 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3782 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3783 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3784 }
3785 }
3786 Lex.Lex();
3787 return false;
3788}
3789
3790//===----------------------------------------------------------------------===//
3791// Terminator Instructions.
3792//===----------------------------------------------------------------------===//
3793
3794/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003795/// ::= 'ret' void (',' !dbg, !1)*
3796/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003797bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003798 PerFunctionState &PFS) {
3799 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003800 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003801 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003802
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003803 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003804
Chris Lattnerfdd87902009-10-05 05:54:46 +00003805 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003806 if (!ResType->isVoidTy())
3807 return Error(TypeLoc, "value doesn't match function result type '" +
3808 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003809
Owen Anderson55f1c092009-08-13 21:58:54 +00003810 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003811 return false;
3812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003813
Chris Lattnerac161bf2009-01-02 07:01:27 +00003814 Value *RV;
3815 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003816
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003817 if (ResType != RV->getType())
3818 return Error(TypeLoc, "value doesn't match function result type '" +
3819 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003820
Owen Anderson55f1c092009-08-13 21:58:54 +00003821 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003822 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003823}
3824
3825
3826/// ParseBr
3827/// ::= 'br' TypeAndValue
3828/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3829bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3830 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003831 Value *Op0;
3832 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003833 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003834
Chris Lattnerac161bf2009-01-02 07:01:27 +00003835 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3836 Inst = BranchInst::Create(BB);
3837 return false;
3838 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003839
Owen Anderson55f1c092009-08-13 21:58:54 +00003840 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003841 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003842
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003844 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003845 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003846 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003847 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003848
Chris Lattner3ed871f2009-10-27 19:13:16 +00003849 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003850 return false;
3851}
3852
3853/// ParseSwitch
3854/// Instruction
3855/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3856/// JumpTable
3857/// ::= (TypeAndValue ',' TypeAndValue)*
3858bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3859 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003860 Value *Cond;
3861 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003862 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3863 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003864 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003865 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3866 return true;
3867
Duncan Sands19d0b472010-02-16 11:11:14 +00003868 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003869 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003870
Chris Lattnerac161bf2009-01-02 07:01:27 +00003871 // Parse the jump table pairs.
3872 SmallPtrSet<Value*, 32> SeenCases;
3873 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3874 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003875 Value *Constant;
3876 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003877
Chris Lattnerac161bf2009-01-02 07:01:27 +00003878 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3879 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003880 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003881 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003882
David Blaikie70573dc2014-11-19 07:49:26 +00003883 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 return Error(CondLoc, "duplicate case value in switch");
3885 if (!isa<ConstantInt>(Constant))
3886 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003887
Chris Lattner3ed871f2009-10-27 19:13:16 +00003888 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003890
Chris Lattnerac161bf2009-01-02 07:01:27 +00003891 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003892
Chris Lattner3ed871f2009-10-27 19:13:16 +00003893 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003894 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3895 SI->addCase(Table[i].first, Table[i].second);
3896 Inst = SI;
3897 return false;
3898}
3899
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003900/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003901/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003902/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3903bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003904 LocTy AddrLoc;
3905 Value *Address;
3906 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003907 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3908 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003909 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003910
Duncan Sands19d0b472010-02-16 11:11:14 +00003911 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003912 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003913
Chris Lattner3ed871f2009-10-27 19:13:16 +00003914 // Parse the destination list.
3915 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003916
Chris Lattner3ed871f2009-10-27 19:13:16 +00003917 if (Lex.getKind() != lltok::rsquare) {
3918 BasicBlock *DestBB;
3919 if (ParseTypeAndBasicBlock(DestBB, PFS))
3920 return true;
3921 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003922
Chris Lattner3ed871f2009-10-27 19:13:16 +00003923 while (EatIfPresent(lltok::comma)) {
3924 if (ParseTypeAndBasicBlock(DestBB, PFS))
3925 return true;
3926 DestList.push_back(DestBB);
3927 }
3928 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003929
Chris Lattner3ed871f2009-10-27 19:13:16 +00003930 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3931 return true;
3932
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003933 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003934 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3935 IBI->addDestination(DestList[i]);
3936 Inst = IBI;
3937 return false;
3938}
3939
3940
Chris Lattnerac161bf2009-01-02 07:01:27 +00003941/// ParseInvoke
3942/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3943/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3944bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3945 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003946 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003947 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003948 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003949 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003950 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003951 LocTy RetTypeLoc;
3952 ValID CalleeID;
3953 SmallVector<ParamInfo, 16> ArgList;
3954
Chris Lattner3ed871f2009-10-27 19:13:16 +00003955 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003956 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003957 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003958 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003959 ParseValID(CalleeID) ||
3960 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003961 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3962 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003963 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003964 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003965 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003966 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003967 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003968
Chris Lattnerac161bf2009-01-02 07:01:27 +00003969 // If RetType is a non-function pointer type, then this is the short syntax
3970 // for the call, which means that RetType is just the return type. Infer the
3971 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003972 PointerType *PFTy = nullptr;
3973 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003974 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3975 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3976 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003977 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3979 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003980
Chris Lattnerac161bf2009-01-02 07:01:27 +00003981 if (!FunctionType::isValidReturnType(RetType))
3982 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003983
Owen Anderson4056ca92009-07-29 22:17:13 +00003984 Ty = FunctionType::get(RetType, ParamTypes, false);
3985 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003987
Chris Lattnerac161bf2009-01-02 07:01:27 +00003988 // Look up the callee.
3989 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003990 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003991
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003992 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003993 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003994 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003995 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3996 AttributeSet::ReturnIndex,
3997 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003998
Chris Lattnerac161bf2009-01-02 07:01:27 +00003999 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004000
Chris Lattnerac161bf2009-01-02 07:01:27 +00004001 // Loop through FunctionType's arguments and ensure they are specified
4002 // correctly. Also, gather any parameter attributes.
4003 FunctionType::param_iterator I = Ty->param_begin();
4004 FunctionType::param_iterator E = Ty->param_end();
4005 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004006 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004007 if (I != E) {
4008 ExpectedTy = *I++;
4009 } else if (!Ty->isVarArg()) {
4010 return Error(ArgList[i].Loc, "too many arguments specified");
4011 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004012
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4014 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004015 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004016 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004017 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4018 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004019 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4020 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004021 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004022
Chris Lattnerac161bf2009-01-02 07:01:27 +00004023 if (I != E)
4024 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004025
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004026 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004027 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4028 AttributeSet::FunctionIndex,
4029 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004030
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004031 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004032 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004033
Jay Foad5bd375a2011-07-15 08:37:34 +00004034 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004035 II->setCallingConv(CC);
4036 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004037 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038 Inst = II;
4039 return false;
4040}
4041
Bill Wendlingf891bf82011-07-31 06:30:59 +00004042/// ParseResume
4043/// ::= 'resume' TypeAndValue
4044bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4045 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004046 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4047 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004048
Bill Wendlingf891bf82011-07-31 06:30:59 +00004049 ResumeInst *RI = ResumeInst::Create(Exn);
4050 Inst = RI;
4051 return false;
4052}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053
4054//===----------------------------------------------------------------------===//
4055// Binary Operators.
4056//===----------------------------------------------------------------------===//
4057
4058/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004059/// ::= ArithmeticOps TypeAndValue ',' Value
4060///
4061/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4062/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004063bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004064 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004065 LocTy Loc; Value *LHS, *RHS;
4066 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4067 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4068 ParseValue(LHS->getType(), RHS, PFS))
4069 return true;
4070
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004071 bool Valid;
4072 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004073 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004074 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004075 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4076 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004077 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004078 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4079 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004081
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004082 if (!Valid)
4083 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004084
Chris Lattnerac161bf2009-01-02 07:01:27 +00004085 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4086 return false;
4087}
4088
4089/// ParseLogical
4090/// ::= ArithmeticOps TypeAndValue ',' Value {
4091bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4092 unsigned Opc) {
4093 LocTy Loc; Value *LHS, *RHS;
4094 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4095 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4096 ParseValue(LHS->getType(), RHS, PFS))
4097 return true;
4098
Duncan Sands9dff9be2010-02-15 16:12:20 +00004099 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004100 return Error(Loc,"instruction requires integer or integer vector operands");
4101
4102 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4103 return false;
4104}
4105
4106
4107/// ParseCompare
4108/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4109/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004110bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4111 unsigned Opc) {
4112 // Parse the integer/fp comparison predicate.
4113 LocTy Loc;
4114 unsigned Pred;
4115 Value *LHS, *RHS;
4116 if (ParseCmpPredicate(Pred, Opc) ||
4117 ParseTypeAndValue(LHS, Loc, PFS) ||
4118 ParseToken(lltok::comma, "expected ',' after compare value") ||
4119 ParseValue(LHS->getType(), RHS, PFS))
4120 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004121
Chris Lattnerac161bf2009-01-02 07:01:27 +00004122 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004123 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004124 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004125 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004126 } else {
4127 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004128 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004129 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004130 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004131 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004132 }
4133 return false;
4134}
4135
4136//===----------------------------------------------------------------------===//
4137// Other Instructions.
4138//===----------------------------------------------------------------------===//
4139
4140
4141/// ParseCast
4142/// ::= CastOpc TypeAndValue 'to' Type
4143bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4144 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004145 LocTy Loc;
4146 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004147 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004148 if (ParseTypeAndValue(Op, Loc, PFS) ||
4149 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4150 ParseType(DestTy))
4151 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004152
Chris Lattner89d856e2009-03-01 00:53:13 +00004153 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4154 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004155 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004156 getTypeString(Op->getType()) + "' to '" +
4157 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004158 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004159 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4160 return false;
4161}
4162
4163/// ParseSelect
4164/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4165bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4166 LocTy Loc;
4167 Value *Op0, *Op1, *Op2;
4168 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4169 ParseToken(lltok::comma, "expected ',' after select condition") ||
4170 ParseTypeAndValue(Op1, PFS) ||
4171 ParseToken(lltok::comma, "expected ',' after select value") ||
4172 ParseTypeAndValue(Op2, PFS))
4173 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004174
Chris Lattnerac161bf2009-01-02 07:01:27 +00004175 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4176 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004177
Chris Lattnerac161bf2009-01-02 07:01:27 +00004178 Inst = SelectInst::Create(Op0, Op1, Op2);
4179 return false;
4180}
4181
Chris Lattnerb55ab542009-01-05 08:18:44 +00004182/// ParseVA_Arg
4183/// ::= 'va_arg' TypeAndValue ',' Type
4184bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004185 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004186 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004187 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004188 if (ParseTypeAndValue(Op, PFS) ||
4189 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004190 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004191 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004192
Chris Lattnerb55ab542009-01-05 08:18:44 +00004193 if (!EltTy->isFirstClassType())
4194 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004195
4196 Inst = new VAArgInst(Op, EltTy);
4197 return false;
4198}
4199
4200/// ParseExtractElement
4201/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4202bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4203 LocTy Loc;
4204 Value *Op0, *Op1;
4205 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4206 ParseToken(lltok::comma, "expected ',' after extract value") ||
4207 ParseTypeAndValue(Op1, PFS))
4208 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004209
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4211 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004212
Eric Christopherc9742252009-07-25 02:28:41 +00004213 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004214 return false;
4215}
4216
4217/// ParseInsertElement
4218/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4219bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4220 LocTy Loc;
4221 Value *Op0, *Op1, *Op2;
4222 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4223 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4224 ParseTypeAndValue(Op1, PFS) ||
4225 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4226 ParseTypeAndValue(Op2, PFS))
4227 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004228
Chris Lattnerac161bf2009-01-02 07:01:27 +00004229 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004230 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004231
Chris Lattnerac161bf2009-01-02 07:01:27 +00004232 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4233 return false;
4234}
4235
4236/// ParseShuffleVector
4237/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4238bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4239 LocTy Loc;
4240 Value *Op0, *Op1, *Op2;
4241 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4242 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4243 ParseTypeAndValue(Op1, PFS) ||
4244 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4245 ParseTypeAndValue(Op2, PFS))
4246 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004247
Chris Lattnerac161bf2009-01-02 07:01:27 +00004248 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004249 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004250
Chris Lattnerac161bf2009-01-02 07:01:27 +00004251 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4252 return false;
4253}
4254
4255/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004256/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004257int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004258 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004259 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004261 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004262 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4263 ParseValue(Ty, Op0, PFS) ||
4264 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004265 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4267 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004268
Chris Lattnerf4f03422009-12-30 05:27:33 +00004269 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004270 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4271 while (1) {
4272 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004273
Chris Lattner3822f632009-01-02 08:05:26 +00004274 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004275 break;
4276
Chris Lattnerf4f03422009-12-30 05:27:33 +00004277 if (Lex.getKind() == lltok::MetadataVar) {
4278 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004279 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004280 }
Devang Patel8f842d32009-10-16 18:45:49 +00004281
Chris Lattner3822f632009-01-02 08:05:26 +00004282 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004283 ParseValue(Ty, Op0, PFS) ||
4284 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004285 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004286 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4287 return true;
4288 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004289
Chris Lattnerac161bf2009-01-02 07:01:27 +00004290 if (!Ty->isFirstClassType())
4291 return Error(TypeLoc, "phi node must have first class type");
4292
Jay Foad52131342011-03-30 11:28:46 +00004293 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004294 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4295 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4296 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004297 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004298}
4299
Bill Wendlingfae14752011-08-12 20:24:12 +00004300/// ParseLandingPad
4301/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4302/// Clause
4303/// ::= 'catch' TypeAndValue
4304/// ::= 'filter'
4305/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4306bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004307 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004308 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004309
4310 if (ParseType(Ty, TyLoc) ||
4311 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4312 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4313 return true;
4314
4315 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4316 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4317
4318 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4319 LandingPadInst::ClauseType CT;
4320 if (EatIfPresent(lltok::kw_catch))
4321 CT = LandingPadInst::Catch;
4322 else if (EatIfPresent(lltok::kw_filter))
4323 CT = LandingPadInst::Filter;
4324 else
4325 return TokError("expected 'catch' or 'filter' clause type");
4326
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004327 Value *V;
4328 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004329 if (ParseTypeAndValue(V, VLoc, PFS)) {
4330 delete LP;
4331 return true;
4332 }
4333
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004334 // A 'catch' type expects a non-array constant. A filter clause expects an
4335 // array constant.
4336 if (CT == LandingPadInst::Catch) {
4337 if (isa<ArrayType>(V->getType()))
4338 Error(VLoc, "'catch' clause has an invalid type");
4339 } else {
4340 if (!isa<ArrayType>(V->getType()))
4341 Error(VLoc, "'filter' clause has an invalid type");
4342 }
4343
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004344 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004345 }
4346
4347 Inst = LP;
4348 return false;
4349}
4350
Chris Lattnerac161bf2009-01-02 07:01:27 +00004351/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004352/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4353/// ParameterList OptionalAttrs
4354/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4355/// ParameterList OptionalAttrs
4356/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357/// ParameterList OptionalAttrs
4358bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004359 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004360 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004361 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004362 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004363 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004364 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004365 LocTy RetTypeLoc;
4366 ValID CalleeID;
4367 SmallVector<ParamInfo, 16> ArgList;
4368 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004369
Reid Kleckner5772b772014-04-24 20:14:34 +00004370 if ((TCK != CallInst::TCK_None &&
4371 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004372 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004373 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004374 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004375 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004376 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4377 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004378 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004379 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004380 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004381
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 // If RetType is a non-function pointer type, then this is the short syntax
4383 // for the call, which means that RetType is just the return type. Infer the
4384 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004385 PointerType *PFTy = nullptr;
4386 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004387 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4388 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4389 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004390 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004391 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4392 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004393
Chris Lattnerac161bf2009-01-02 07:01:27 +00004394 if (!FunctionType::isValidReturnType(RetType))
4395 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004396
Owen Anderson4056ca92009-07-29 22:17:13 +00004397 Ty = FunctionType::get(RetType, ParamTypes, false);
4398 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004399 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004400
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 // Look up the callee.
4402 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004403 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004404
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004405 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004406 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004407 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004408 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4409 AttributeSet::ReturnIndex,
4410 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004411
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004413
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414 // Loop through FunctionType's arguments and ensure they are specified
4415 // correctly. Also, gather any parameter attributes.
4416 FunctionType::param_iterator I = Ty->param_begin();
4417 FunctionType::param_iterator E = Ty->param_end();
4418 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004419 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004420 if (I != E) {
4421 ExpectedTy = *I++;
4422 } else if (!Ty->isVarArg()) {
4423 return Error(ArgList[i].Loc, "too many arguments specified");
4424 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004425
Chris Lattnerac161bf2009-01-02 07:01:27 +00004426 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4427 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004428 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004429 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004430 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4431 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004432 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4433 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004434 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004435
Chris Lattnerac161bf2009-01-02 07:01:27 +00004436 if (I != E)
4437 return Error(CallLoc, "not enough parameters specified for call");
4438
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004439 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004440 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4441 AttributeSet::FunctionIndex,
4442 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004443
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004444 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004445 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004446
Jay Foad5bd375a2011-07-15 08:37:34 +00004447 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004448 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449 CI->setCallingConv(CC);
4450 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004451 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004452 Inst = CI;
4453 return false;
4454}
4455
4456//===----------------------------------------------------------------------===//
4457// Memory Instructions.
4458//===----------------------------------------------------------------------===//
4459
4460/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004461/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004462int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004463 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004464 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004465 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004466 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004467
4468 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4469
Chris Lattner3822f632009-01-02 08:05:26 +00004470 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004471
Chris Lattnerb2f39502009-12-30 05:44:30 +00004472 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004473 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004474 if (Lex.getKind() == lltok::kw_align) {
4475 if (ParseOptionalAlignment(Alignment)) return true;
4476 } else if (Lex.getKind() == lltok::MetadataVar) {
4477 AteExtraComma = true;
4478 } else {
4479 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4480 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4481 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 }
4483 }
4484
Dan Gohman2140a742010-05-28 01:14:11 +00004485 if (Size && !Size->getType()->isIntegerTy())
4486 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487
Reid Kleckner436c42e2014-01-17 23:58:17 +00004488 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4489 AI->setUsedWithInAlloca(IsInAlloca);
4490 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004491 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492}
4493
4494/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004495/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004496/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004497/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004498int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004500 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004501 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004502 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004503 AtomicOrdering Ordering = NotAtomic;
4504 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004505
4506 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004507 isAtomic = true;
4508 Lex.Lex();
4509 }
4510
Chris Lattnerbc639292011-11-27 06:56:53 +00004511 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004512 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004513 isVolatile = true;
4514 Lex.Lex();
4515 }
4516
Chris Lattnerb2f39502009-12-30 05:44:30 +00004517 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004518 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004519 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4520 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004521
Duncan Sands19d0b472010-02-16 11:11:14 +00004522 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4524 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004525 if (isAtomic && !Alignment)
4526 return Error(Loc, "atomic load must have explicit non-zero alignment");
4527 if (Ordering == Release || Ordering == AcquireRelease)
4528 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004529
Eli Friedman59b66882011-08-09 23:02:53 +00004530 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004531 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004532}
4533
4534/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004535
4536/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4537/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004538/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004539int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004541 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004542 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004543 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004544 AtomicOrdering Ordering = NotAtomic;
4545 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004546
4547 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004548 isAtomic = true;
4549 Lex.Lex();
4550 }
4551
Chris Lattnerbc639292011-11-27 06:56:53 +00004552 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004553 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004554 isVolatile = true;
4555 Lex.Lex();
4556 }
4557
Chris Lattnerac161bf2009-01-02 07:01:27 +00004558 if (ParseTypeAndValue(Val, Loc, PFS) ||
4559 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004560 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004561 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004562 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004564
Duncan Sands19d0b472010-02-16 11:11:14 +00004565 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004566 return Error(PtrLoc, "store operand must be a pointer");
4567 if (!Val->getType()->isFirstClassType())
4568 return Error(Loc, "store operand must be a first class value");
4569 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4570 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004571 if (isAtomic && !Alignment)
4572 return Error(Loc, "atomic store must have explicit non-zero alignment");
4573 if (Ordering == Acquire || Ordering == AcquireRelease)
4574 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004575
Eli Friedman59b66882011-08-09 23:02:53 +00004576 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004577 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578}
4579
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004580/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004581/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4582/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004583int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004584 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4585 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004586 AtomicOrdering SuccessOrdering = NotAtomic;
4587 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004588 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004589 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004590 bool isWeak = false;
4591
4592 if (EatIfPresent(lltok::kw_weak))
4593 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004594
4595 if (EatIfPresent(lltok::kw_volatile))
4596 isVolatile = true;
4597
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004598 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4599 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4600 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4601 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4602 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004603 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4604 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004605 return true;
4606
Tim Northovere94a5182014-03-11 10:48:52 +00004607 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004608 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004609 if (SuccessOrdering < FailureOrdering)
4610 return TokError("cmpxchg must be at least as ordered on success as failure");
4611 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4612 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004613 if (!Ptr->getType()->isPointerTy())
4614 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4615 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4616 return Error(CmpLoc, "compare value and pointer type do not match");
4617 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4618 return Error(NewLoc, "new value and pointer type do not match");
4619 if (!New->getType()->isIntegerTy())
4620 return Error(NewLoc, "cmpxchg operand must be an integer");
4621 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4622 if (Size < 8 || (Size & (Size - 1)))
4623 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4624 " integer");
4625
Tim Northover420a2162014-06-13 14:24:07 +00004626 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4627 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004628 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004629 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004630 Inst = CXI;
4631 return AteExtraComma ? InstExtraComma : InstNormal;
4632}
4633
4634/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004635/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4636/// 'singlethread'? AtomicOrdering
4637int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004638 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4639 bool AteExtraComma = false;
4640 AtomicOrdering Ordering = NotAtomic;
4641 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004642 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004643 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004644
4645 if (EatIfPresent(lltok::kw_volatile))
4646 isVolatile = true;
4647
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004648 switch (Lex.getKind()) {
4649 default: return TokError("expected binary operation in atomicrmw");
4650 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4651 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4652 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4653 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4654 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4655 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4656 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4657 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4658 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4659 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4660 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4661 }
4662 Lex.Lex(); // Eat the operation.
4663
4664 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4665 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4666 ParseTypeAndValue(Val, ValLoc, PFS) ||
4667 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4668 return true;
4669
4670 if (Ordering == Unordered)
4671 return TokError("atomicrmw cannot be unordered");
4672 if (!Ptr->getType()->isPointerTy())
4673 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4674 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4675 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4676 if (!Val->getType()->isIntegerTy())
4677 return Error(ValLoc, "atomicrmw operand must be an integer");
4678 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4679 if (Size < 8 || (Size & (Size - 1)))
4680 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4681 " integer");
4682
4683 AtomicRMWInst *RMWI =
4684 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4685 RMWI->setVolatile(isVolatile);
4686 Inst = RMWI;
4687 return AteExtraComma ? InstExtraComma : InstNormal;
4688}
4689
Eli Friedmanfee02c62011-07-25 23:16:38 +00004690/// ParseFence
4691/// ::= 'fence' 'singlethread'? AtomicOrdering
4692int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4693 AtomicOrdering Ordering = NotAtomic;
4694 SynchronizationScope Scope = CrossThread;
4695 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4696 return true;
4697
4698 if (Ordering == Unordered)
4699 return TokError("fence cannot be unordered");
4700 if (Ordering == Monotonic)
4701 return TokError("fence cannot be monotonic");
4702
4703 Inst = new FenceInst(Context, Ordering, Scope);
4704 return InstNormal;
4705}
4706
Chris Lattnerac161bf2009-01-02 07:01:27 +00004707/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004708/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004709int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004710 Value *Ptr = nullptr;
4711 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004712 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004713
Dan Gohman16cbbe42009-07-29 15:58:36 +00004714 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004715
Chris Lattner3822f632009-01-02 08:05:26 +00004716 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004717
Eli Benderskyd9806682013-04-22 17:03:42 +00004718 Type *BaseType = Ptr->getType();
4719 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4720 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004721 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004722
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004724 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004725 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004726 if (Lex.getKind() == lltok::MetadataVar) {
4727 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004728 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004729 }
Chris Lattner3822f632009-01-02 08:05:26 +00004730 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004731 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004733 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4734 return Error(EltLoc, "getelementptr index type missmatch");
4735 if (Val->getType()->isVectorTy()) {
4736 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4737 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4738 if (ValNumEl != PtrNumEl)
4739 return Error(EltLoc,
4740 "getelementptr vector index has a wrong number of elements");
4741 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004742 Indices.push_back(Val);
4743 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004744
Eli Benderskyd9806682013-04-22 17:03:42 +00004745 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4746 return Error(Loc, "base element of getelementptr must be sized");
4747
4748 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004749 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004750 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004751 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004752 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004753 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004754}
4755
4756/// ParseExtractValue
4757/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004758int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 Value *Val; LocTy Loc;
4760 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004761 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004763 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004764 return true;
4765
Chris Lattner392be582010-02-12 20:49:41 +00004766 if (!Val->getType()->isAggregateType())
4767 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004768
Jay Foad57aa6362011-07-13 10:26:04 +00004769 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004771 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004772 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004773}
4774
4775/// ParseInsertValue
4776/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004777int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 Value *Val0, *Val1; LocTy Loc0, Loc1;
4779 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004780 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4782 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4783 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004784 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004786
Chris Lattner392be582010-02-12 20:49:41 +00004787 if (!Val0->getType()->isAggregateType())
4788 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004789
Jay Foad57aa6362011-07-13 10:26:04 +00004790 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004792 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004793 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794}
Nick Lewycky49f89192009-04-04 07:22:01 +00004795
4796//===----------------------------------------------------------------------===//
4797// Embedded metadata.
4798//===----------------------------------------------------------------------===//
4799
4800/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004801/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004802/// Element
4803/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004804bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00004805 if (ParseToken(lltok::lbrace, "expected '{' here"))
4806 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004807
Dan Gohman1e0213a2010-07-13 19:33:27 +00004808 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004809 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004810 return false;
4811
Nick Lewycky49f89192009-04-04 07:22:01 +00004812 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004813 // Null is a special case since it is typeless.
4814 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004815 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004816 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004817 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004818
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004819 Metadata *MD;
4820 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004821 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004822 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00004823 } while (EatIfPresent(lltok::comma));
4824
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004825 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004826}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004827
4828//===----------------------------------------------------------------------===//
4829// Use-list order directives.
4830//===----------------------------------------------------------------------===//
4831bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4832 SMLoc Loc) {
4833 if (V->use_empty())
4834 return Error(Loc, "value has no uses");
4835
4836 unsigned NumUses = 0;
4837 SmallDenseMap<const Use *, unsigned, 16> Order;
4838 for (const Use &U : V->uses()) {
4839 if (++NumUses > Indexes.size())
4840 break;
4841 Order[&U] = Indexes[NumUses - 1];
4842 }
4843 if (NumUses < 2)
4844 return Error(Loc, "value only has one use");
4845 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4846 return Error(Loc, "wrong number of indexes, expected " +
4847 Twine(std::distance(V->use_begin(), V->use_end())));
4848
4849 V->sortUseList([&](const Use &L, const Use &R) {
4850 return Order.lookup(&L) < Order.lookup(&R);
4851 });
4852 return false;
4853}
4854
4855/// ParseUseListOrderIndexes
4856/// ::= '{' uint32 (',' uint32)+ '}'
4857bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4858 SMLoc Loc = Lex.getLoc();
4859 if (ParseToken(lltok::lbrace, "expected '{' here"))
4860 return true;
4861 if (Lex.getKind() == lltok::rbrace)
4862 return Lex.Error("expected non-empty list of uselistorder indexes");
4863
4864 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4865 // indexes should be distinct numbers in the range [0, size-1], and should
4866 // not be in order.
4867 unsigned Offset = 0;
4868 unsigned Max = 0;
4869 bool IsOrdered = true;
4870 assert(Indexes.empty() && "Expected empty order vector");
4871 do {
4872 unsigned Index;
4873 if (ParseUInt32(Index))
4874 return true;
4875
4876 // Update consistency checks.
4877 Offset += Index - Indexes.size();
4878 Max = std::max(Max, Index);
4879 IsOrdered &= Index == Indexes.size();
4880
4881 Indexes.push_back(Index);
4882 } while (EatIfPresent(lltok::comma));
4883
4884 if (ParseToken(lltok::rbrace, "expected '}' here"))
4885 return true;
4886
4887 if (Indexes.size() < 2)
4888 return Error(Loc, "expected >= 2 uselistorder indexes");
4889 if (Offset != 0 || Max >= Indexes.size())
4890 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4891 if (IsOrdered)
4892 return Error(Loc, "expected uselistorder indexes to change the order");
4893
4894 return false;
4895}
4896
4897/// ParseUseListOrder
4898/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4899bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4900 SMLoc Loc = Lex.getLoc();
4901 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4902 return true;
4903
4904 Value *V;
4905 SmallVector<unsigned, 16> Indexes;
4906 if (ParseTypeAndValue(V, PFS) ||
4907 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4908 ParseUseListOrderIndexes(Indexes))
4909 return true;
4910
4911 return sortUseListOrder(V, Indexes, Loc);
4912}
4913
4914/// ParseUseListOrderBB
4915/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4916bool LLParser::ParseUseListOrderBB() {
4917 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4918 SMLoc Loc = Lex.getLoc();
4919 Lex.Lex();
4920
4921 ValID Fn, Label;
4922 SmallVector<unsigned, 16> Indexes;
4923 if (ParseValID(Fn) ||
4924 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4925 ParseValID(Label) ||
4926 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4927 ParseUseListOrderIndexes(Indexes))
4928 return true;
4929
4930 // Check the function.
4931 GlobalValue *GV;
4932 if (Fn.Kind == ValID::t_GlobalName)
4933 GV = M->getNamedValue(Fn.StrVal);
4934 else if (Fn.Kind == ValID::t_GlobalID)
4935 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4936 else
4937 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4938 if (!GV)
4939 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4940 auto *F = dyn_cast<Function>(GV);
4941 if (!F)
4942 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4943 if (F->isDeclaration())
4944 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4945
4946 // Check the basic block.
4947 if (Label.Kind == ValID::t_LocalID)
4948 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4949 if (Label.Kind != ValID::t_LocalName)
4950 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4951 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4952 if (!V)
4953 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4954 if (!isa<BasicBlock>(V))
4955 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4956
4957 return sortUseListOrder(V, Indexes, Loc);
4958}