blob: 427b38ee3b8b6f3c6866cd2f025e35254ef6c20b [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"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000019#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/InlineAsm.h"
22#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000023#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000027#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000029#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000030#include "llvm/Support/raw_ostream.h"
31using namespace llvm;
32
Chris Lattner229907c2011-07-18 04:54:35 +000033static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000034 std::string Result;
35 raw_string_ostream Tmp(Result);
36 Tmp << *T;
37 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000038}
39
Chris Lattner3822f632009-01-02 08:05:26 +000040/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000041bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000042 // Prime the lexer.
43 Lex.Lex();
44
Chris Lattnerad6f3352009-01-04 20:44:11 +000045 return ParseTopLevelEntities() ||
46 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000047}
48
49/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
50/// module.
51bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000052 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
53 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
54
Bill Wendlingb32b0412013-02-08 06:32:06 +000055 // Handle any function attribute group forward references.
56 for (std::map<Value*, std::vector<unsigned> >::iterator
57 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
58 I != E; ++I) {
59 Value *V = I->first;
60 std::vector<unsigned> &Vec = I->second;
61 AttrBuilder B;
62
63 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
64 VI != VE; ++VI)
65 B.merge(NumberedAttrBuilders[*VI]);
66
67 if (Function *Fn = dyn_cast<Function>(V)) {
68 AttributeSet AS = Fn->getAttributes();
69 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
70 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
71 AS.getFnAttributes());
72
73 FnAttrs.merge(B);
74
75 // If the alignment was parsed as an attribute, move to the alignment
76 // field.
77 if (FnAttrs.hasAlignmentAttr()) {
78 Fn->setAlignment(FnAttrs.getAlignment());
79 FnAttrs.removeAttribute(Attribute::Alignment);
80 }
81
82 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
83 AttributeSet::get(Context,
84 AttributeSet::FunctionIndex,
85 FnAttrs));
86 Fn->setAttributes(AS);
87 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
88 AttributeSet AS = CI->getAttributes();
89 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
90 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
91 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000092 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000093 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
94 AttributeSet::get(Context,
95 AttributeSet::FunctionIndex,
96 FnAttrs));
97 CI->setAttributes(AS);
98 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
99 AttributeSet AS = II->getAttributes();
100 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
101 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
102 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000103 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000104 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
105 AttributeSet::get(Context,
106 AttributeSet::FunctionIndex,
107 FnAttrs));
108 II->setAttributes(AS);
109 } else {
110 llvm_unreachable("invalid object with forward attribute group reference");
111 }
112 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000113
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000114 // If there are entries in ForwardRefBlockAddresses at this point, the
115 // function was never defined.
116 if (!ForwardRefBlockAddresses.empty())
117 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
118 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000119
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000120 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
121 if (NumberedTypes[i].second.isValid())
122 return Error(NumberedTypes[i].second,
123 "use of undefined type '%" + Twine(i) + "'");
124
125 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
126 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
127 if (I->second.second.isValid())
128 return Error(I->second.second,
129 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000130
David Majnemerdad0a642014-06-27 18:19:56 +0000131 if (!ForwardRefComdats.empty())
132 return Error(ForwardRefComdats.begin()->second,
133 "use of undefined comdat '$" +
134 ForwardRefComdats.begin()->first + "'");
135
Chris Lattnerac161bf2009-01-02 07:01:27 +0000136 if (!ForwardRefVals.empty())
137 return Error(ForwardRefVals.begin()->second.second,
138 "use of undefined value '@" + ForwardRefVals.begin()->first +
139 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000140
Chris Lattnerac161bf2009-01-02 07:01:27 +0000141 if (!ForwardRefValIDs.empty())
142 return Error(ForwardRefValIDs.begin()->second.second,
143 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000144 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000145
Devang Pateld2541152009-07-08 19:23:54 +0000146 if (!ForwardRefMDNodes.empty())
147 return Error(ForwardRefMDNodes.begin()->second.second,
148 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000149 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000150
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000151 // Resolve metadata cycles.
152 for (auto &N : NumberedMetadata)
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000153 if (N && !N->isResolved())
154 N->resolveCycles();
Devang Pateld2541152009-07-08 19:23:54 +0000155
Chris Lattnerac161bf2009-01-02 07:01:27 +0000156 // Look for intrinsic functions and CallInst that need to be upgraded
157 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
158 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000159
Manman Ren8b4306c2013-12-02 21:29:56 +0000160 UpgradeDebugInfo(*M);
161
Chris Lattnerac161bf2009-01-02 07:01:27 +0000162 return false;
163}
164
165//===----------------------------------------------------------------------===//
166// Top-Level Entities
167//===----------------------------------------------------------------------===//
168
169bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000170 while (1) {
171 switch (Lex.getKind()) {
172 default: return TokError("expected top-level entity");
173 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000174 case lltok::kw_declare: if (ParseDeclare()) return true; break;
175 case lltok::kw_define: if (ParseDefine()) return true; break;
176 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
177 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000178 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000179 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000180 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000181 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000182 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000183 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000184 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000185 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000186
187 // The Global variable production with no name can have many different
188 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000189 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
190 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000191 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000192 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000193 case lltok::kw_internal: // OptionalLinkage
194 case lltok::kw_weak: // OptionalLinkage
195 case lltok::kw_weak_odr: // OptionalLinkage
196 case lltok::kw_linkonce: // OptionalLinkage
197 case lltok::kw_linkonce_odr: // OptionalLinkage
198 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000199 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000200 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000201 case lltok::kw_external: // OptionalLinkage
202 case lltok::kw_default: // OptionalVisibility
203 case lltok::kw_hidden: // OptionalVisibility
204 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000205 case lltok::kw_dllimport: // OptionalDLLStorageClass
206 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000207 case lltok::kw_thread_local: // OptionalThreadLocal
208 case lltok::kw_addrspace: // OptionalAddrSpace
209 case lltok::kw_constant: // GlobalType
210 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000211 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000212 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000213 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000214 bool HasLinkage;
215 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000216 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000217 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000218 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000219 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000220 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000221 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000222 return true;
223 break;
224 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000225
226 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000227 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
228 case lltok::kw_uselistorder_bb:
229 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000230 }
231 }
232}
233
234
235/// toplevelentity
236/// ::= 'module' 'asm' STRINGCONSTANT
237bool LLParser::ParseModuleAsm() {
238 assert(Lex.getKind() == lltok::kw_module);
239 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000240
241 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000242 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
243 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000244
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000245 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000246 return false;
247}
248
249/// toplevelentity
250/// ::= 'target' 'triple' '=' STRINGCONSTANT
251/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
252bool LLParser::ParseTargetDefinition() {
253 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000254 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000255 switch (Lex.Lex()) {
256 default: return TokError("unknown target property");
257 case lltok::kw_triple:
258 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000259 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
260 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000262 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000263 return false;
264 case lltok::kw_datalayout:
265 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000266 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
267 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000269 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000270 return false;
271 }
272}
273
Bill Wendling706d3d62012-11-28 08:41:48 +0000274/// toplevelentity
275/// ::= 'deplibs' '=' '[' ']'
276/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
277/// FIXME: Remove in 4.0. Currently parse, but ignore.
278bool LLParser::ParseDepLibs() {
279 assert(Lex.getKind() == lltok::kw_deplibs);
280 Lex.Lex();
281 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
282 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
283 return true;
284
285 if (EatIfPresent(lltok::rsquare))
286 return false;
287
288 do {
289 std::string Str;
290 if (ParseStringConstant(Str)) return true;
291 } while (EatIfPresent(lltok::comma));
292
293 return ParseToken(lltok::rsquare, "expected ']' at end of list");
294}
295
Dan Gohman466876b2009-08-12 23:32:33 +0000296/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000297/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000298bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000299 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000300 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000301 Lex.Lex(); // eat LocalVarID;
302
303 if (ParseToken(lltok::equal, "expected '=' after name") ||
304 ParseToken(lltok::kw_type, "expected 'type' after '='"))
305 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000306
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000307 if (TypeID >= NumberedTypes.size())
308 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000309
Craig Topper2617dcc2014-04-15 06:32:26 +0000310 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000311 if (ParseStructDefinition(TypeLoc, "",
312 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000313
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000314 if (!isa<StructType>(Result)) {
315 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
316 if (Entry.first)
317 return Error(TypeLoc, "non-struct types may not be recursive");
318 Entry.first = Result;
319 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000321
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return false;
323}
324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000325
Chris Lattnerac161bf2009-01-02 07:01:27 +0000326/// toplevelentity
327/// ::= LocalVar '=' 'type' type
328bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000331 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000332
Chris Lattner3822f632009-01-02 08:05:26 +0000333 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000334 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000335 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000336
Craig Topper2617dcc2014-04-15 06:32:26 +0000337 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000338 if (ParseStructDefinition(NameLoc, Name,
339 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000341 if (!isa<StructType>(Result)) {
342 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
343 if (Entry.first)
344 return Error(NameLoc, "non-struct types may not be recursive");
345 Entry.first = Result;
346 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000347 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000348
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000349 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000350}
351
352
353/// toplevelentity
354/// ::= 'declare' FunctionHeader
355bool LLParser::ParseDeclare() {
356 assert(Lex.getKind() == lltok::kw_declare);
357 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000358
Chris Lattnerac161bf2009-01-02 07:01:27 +0000359 Function *F;
360 return ParseFunctionHeader(F, false);
361}
362
363/// toplevelentity
364/// ::= 'define' FunctionHeader '{' ...
365bool LLParser::ParseDefine() {
366 assert(Lex.getKind() == lltok::kw_define);
367 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000368
Chris Lattnerac161bf2009-01-02 07:01:27 +0000369 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000370 return ParseFunctionHeader(F, true) ||
371 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000372}
373
Chris Lattner3822f632009-01-02 08:05:26 +0000374/// ParseGlobalType
375/// ::= 'constant'
376/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377bool LLParser::ParseGlobalType(bool &IsConstant) {
378 if (Lex.getKind() == lltok::kw_constant)
379 IsConstant = true;
380 else if (Lex.getKind() == lltok::kw_global)
381 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000382 else {
383 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000385 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000386 Lex.Lex();
387 return false;
388}
389
Dan Gohman466876b2009-08-12 23:32:33 +0000390/// ParseUnnamedGlobal:
391/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000392/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
393/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000394/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000395/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
396/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000397bool LLParser::ParseUnnamedGlobal() {
398 unsigned VarID = NumberedVals.size();
399 std::string Name;
400 LocTy NameLoc = Lex.getLoc();
401
402 // Handle the GlobalID form.
403 if (Lex.getKind() == lltok::GlobalID) {
404 if (Lex.getUIntVal() != VarID)
405 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000406 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000407 Lex.Lex(); // eat GlobalID;
408
409 if (ParseToken(lltok::equal, "expected '=' after name"))
410 return true;
411 }
412
413 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000414 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000415 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000416 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000417 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000418 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000419 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000420 ParseOptionalThreadLocal(TLM) ||
421 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000422 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000423
Rafael Espindola464fe022014-07-30 22:51:54 +0000424 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000425 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000426 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000427 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000428 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000429}
430
Chris Lattnerac161bf2009-01-02 07:01:27 +0000431/// ParseNamedGlobal:
432/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000433/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000435bool LLParser::ParseNamedGlobal() {
436 assert(Lex.getKind() == lltok::GlobalVar);
437 LocTy NameLoc = Lex.getLoc();
438 std::string Name = Lex.getStrVal();
439 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000440
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000442 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000443 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000444 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
446 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000447 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000448 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000449 ParseOptionalThreadLocal(TLM) ||
450 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000452
Rafael Espindola464fe022014-07-30 22:51:54 +0000453 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000454 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000455 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000456
457 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000458 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000459}
460
David Majnemerdad0a642014-06-27 18:19:56 +0000461bool LLParser::parseComdat() {
462 assert(Lex.getKind() == lltok::ComdatVar);
463 std::string Name = Lex.getStrVal();
464 LocTy NameLoc = Lex.getLoc();
465 Lex.Lex();
466
467 if (ParseToken(lltok::equal, "expected '=' here"))
468 return true;
469
470 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
471 return TokError("expected comdat type");
472
473 Comdat::SelectionKind SK;
474 switch (Lex.getKind()) {
475 default:
476 return TokError("unknown selection kind");
477 case lltok::kw_any:
478 SK = Comdat::Any;
479 break;
480 case lltok::kw_exactmatch:
481 SK = Comdat::ExactMatch;
482 break;
483 case lltok::kw_largest:
484 SK = Comdat::Largest;
485 break;
486 case lltok::kw_noduplicates:
487 SK = Comdat::NoDuplicates;
488 break;
489 case lltok::kw_samesize:
490 SK = Comdat::SameSize;
491 break;
492 }
493 Lex.Lex();
494
495 // See if the comdat was forward referenced, if so, use the comdat.
496 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
497 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
498 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
499 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
500
501 Comdat *C;
502 if (I != ComdatSymTab.end())
503 C = &I->second;
504 else
505 C = M->getOrInsertComdat(Name);
506 C->setSelectionKind(SK);
507
508 return false;
509}
510
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000511// MDString:
512// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000513bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000514 std::string Str;
515 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000516 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000517 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000518 return false;
519}
520
521// MDNode:
522// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000523bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000524 // !{ ..., !42, ... }
525 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000526 if (ParseUInt32(MID))
527 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000528
Chris Lattner8eff0152010-04-01 05:14:45 +0000529 // If not a forward reference, just return it now.
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000530 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
531 Result = NumberedMetadata[MID];
532 return false;
533 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000534
Chris Lattner8eff0152010-04-01 05:14:45 +0000535 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000536 auto &FwdRef = ForwardRefMDNodes[MID];
537 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000538
Chris Lattnerfc58af22009-12-30 04:51:58 +0000539 if (NumberedMetadata.size() <= MID)
540 NumberedMetadata.resize(MID+1);
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000541 Result = FwdRef.first.get();
542 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000544}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000545
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000546/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000547/// !foo = !{ !1, !2 }
548bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000549 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000550 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000551 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000552
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000553 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000554 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000555 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000556 return true;
557
Dan Gohman2637cc12010-07-21 23:38:33 +0000558 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000559 if (Lex.getKind() != lltok::rbrace)
560 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000561 if (ParseToken(lltok::exclaim, "Expected '!' here"))
562 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000563
Craig Topper2617dcc2014-04-15 06:32:26 +0000564 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000565 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000566 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000567 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000568
569 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
570 return true;
571
Devang Patelbe626972009-07-29 00:34:02 +0000572 return false;
573}
574
Devang Patel39e64d42009-07-01 19:21:12 +0000575/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000576/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000577bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000578 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000579 Lex.Lex();
580 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000581
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000582 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000583 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000584 ParseToken(lltok::equal, "expected '=' here"))
585 return true;
586
587 // Detect common error, from old metadata syntax.
588 if (Lex.getKind() == lltok::Type)
589 return TokError("unexpected type in metadata definition");
590
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000591 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000592 if (Lex.getKind() == lltok::MetadataVar) {
593 if (ParseSpecializedMDNode(Init, IsDistinct))
594 return true;
595 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
596 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000597 return true;
598
Chris Lattnerfc58af22009-12-30 04:51:58 +0000599 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000600 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000601 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000602 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000603 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000604
Chris Lattnerfc58af22009-12-30 04:51:58 +0000605 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
606 } else {
607 if (MetadataID >= NumberedMetadata.size())
608 NumberedMetadata.resize(MetadataID+1);
609
Craig Topper2617dcc2014-04-15 06:32:26 +0000610 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000611 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000612 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000613 }
614
Devang Patel39e64d42009-07-01 19:21:12 +0000615 return false;
616}
617
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000618static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
619 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
620 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
621}
622
Chris Lattnerac161bf2009-01-02 07:01:27 +0000623/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000624/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
625/// OptionalDLLStorageClass OptionalThreadLocal
626/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000627///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000628/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000629/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000630///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000631/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000632///
Rafael Espindola464fe022014-07-30 22:51:54 +0000633bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000634 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000635 GlobalVariable::ThreadLocalMode TLM,
636 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000637 assert(Lex.getKind() == lltok::kw_alias);
638 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000639
Rafael Espindola78527052013-10-06 15:10:43 +0000640 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
641
Rafael Espindolacaa43562013-10-09 16:07:32 +0000642 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000643 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000644
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000645 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000646 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000647 "symbol with local linkage must have default visibility");
648
Rafael Espindola64c1e182014-06-03 02:41:57 +0000649 Constant *Aliasee;
650 LocTy AliaseeLoc = Lex.getLoc();
651 if (Lex.getKind() != lltok::kw_bitcast &&
652 Lex.getKind() != lltok::kw_getelementptr &&
653 Lex.getKind() != lltok::kw_addrspacecast &&
654 Lex.getKind() != lltok::kw_inttoptr) {
655 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000656 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000657 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000658 // The bitcast dest type is not present, it is implied by the dest type.
659 ValID ID;
660 if (ParseValID(ID))
661 return true;
662 if (ID.Kind != ValID::t_Constant)
663 return Error(AliaseeLoc, "invalid aliasee");
664 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000666
Rafael Espindola64c1e182014-06-03 02:41:57 +0000667 Type *AliaseeType = Aliasee->getType();
668 auto *PTy = dyn_cast<PointerType>(AliaseeType);
669 if (!PTy)
670 return Error(AliaseeLoc, "An alias must have pointer type");
671 Type *Ty = PTy->getElementType();
672 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000673
674 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000675 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000676 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
677 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000678 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000679 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000680 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000681 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000682
Chris Lattnerac161bf2009-01-02 07:01:27 +0000683 // See if this value already exists in the symbol table. If so, it is either
684 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000685 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000686 // See if this was a redefinition. If so, there is no entry in
687 // ForwardRefVals.
688 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
689 I = ForwardRefVals.find(Name);
690 if (I == ForwardRefVals.end())
691 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
692
693 // Otherwise, this was a definition of forward ref. Verify that types
694 // agree.
695 if (Val->getType() != GA->getType())
696 return Error(NameLoc,
697 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000698
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 // If they agree, just RAUW the old value with the alias and remove the
700 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000701 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000702 Val->eraseFromParent();
703 ForwardRefVals.erase(I);
704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000705
Chris Lattnerac161bf2009-01-02 07:01:27 +0000706 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000707 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000708 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000709
Rafael Espindolaaa273822014-05-09 21:49:17 +0000710 // The module owns this now
711 GA.release();
712
Chris Lattnerac161bf2009-01-02 07:01:27 +0000713 return false;
714}
715
716/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000717/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000718/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000719/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000720/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000721/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000722/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000723///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000724/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000725/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726///
727bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
728 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000729 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000730 GlobalVariable::ThreadLocalMode TLM,
731 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000732 if (!isValidVisibilityForLinkage(Visibility, Linkage))
733 return Error(NameLoc,
734 "symbol with local linkage must have default visibility");
735
Chris Lattnerac161bf2009-01-02 07:01:27 +0000736 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000737 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000738 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000740
Craig Topper2617dcc2014-04-15 06:32:26 +0000741 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000742 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000743 ParseOptionalToken(lltok::kw_externally_initialized,
744 IsExternallyInitialized,
745 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000746 ParseGlobalType(IsConstant) ||
747 ParseType(Ty, TyLoc))
748 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000749
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750 // If the linkage is specified and is external, then no initializer is
751 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000752 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000753 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000754 Linkage != GlobalValue::ExternalLinkage)) {
755 if (ParseGlobalValue(Ty, Init))
756 return true;
757 }
758
Duncan Sands19d0b472010-02-16 11:11:14 +0000759 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000760 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000761
David Majnemer598bd052014-12-09 05:56:09 +0000762 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000763
764 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000765 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000766 GVal = M->getNamedValue(Name);
767 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000768 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
769 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000770 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000771 } else {
772 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
773 I = ForwardRefValIDs.find(NumberedVals.size());
774 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000775 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000776 ForwardRefValIDs.erase(I);
777 }
778 }
779
David Majnemer598bd052014-12-09 05:56:09 +0000780 GlobalVariable *GV;
781 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000782 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
783 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000784 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000785 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000786 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000787 return Error(TyLoc,
788 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000789
David Majnemer598bd052014-12-09 05:56:09 +0000790 GV = cast<GlobalVariable>(GVal);
791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Move the forward-reference to the correct spot in the module.
793 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
794 }
795
796 if (Name.empty())
797 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000798
Chris Lattnerac161bf2009-01-02 07:01:27 +0000799 // Set the parsed properties on the global.
800 if (Init)
801 GV->setInitializer(Init);
802 GV->setConstant(IsConstant);
803 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
804 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000805 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000806 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000807 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000808 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Chris Lattnerac161bf2009-01-02 07:01:27 +0000810 // Parse attributes on the global.
811 while (Lex.getKind() == lltok::comma) {
812 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000813
Chris Lattnerac161bf2009-01-02 07:01:27 +0000814 if (Lex.getKind() == lltok::kw_section) {
815 Lex.Lex();
816 GV->setSection(Lex.getStrVal());
817 if (ParseToken(lltok::StringConstant, "expected global section string"))
818 return true;
819 } else if (Lex.getKind() == lltok::kw_align) {
820 unsigned Alignment;
821 if (ParseOptionalAlignment(Alignment)) return true;
822 GV->setAlignment(Alignment);
823 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000824 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000825 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000826 return true;
827 if (C)
828 GV->setComdat(C);
829 else
830 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000831 }
832 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000833
Chris Lattnerac161bf2009-01-02 07:01:27 +0000834 return false;
835}
836
Bill Wendling63b88192013-02-06 06:52:58 +0000837/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000838/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000839bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000840 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000841 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000842 Lex.Lex();
843
David Majnemerb39e22b2014-12-09 18:33:57 +0000844 if (Lex.getKind() != lltok::AttrGrpID)
845 return TokError("expected attribute group id");
846
Bill Wendling63b88192013-02-06 06:52:58 +0000847 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000848 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000849 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000850 Lex.Lex();
851
852 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000853 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000854 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000855 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000856 ParseToken(lltok::rbrace, "expected end of attribute group"))
857 return true;
858
Bill Wendlingb32b0412013-02-08 06:32:06 +0000859 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000860 return Error(AttrGrpLoc, "attribute group has no attributes");
861
862 return false;
863}
864
Bill Wendling8b0321d2013-02-08 00:52:31 +0000865/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000866/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000867bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
868 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000869 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000870 bool HaveError = false;
871
872 B.clear();
873
Bill Wendling63b88192013-02-06 06:52:58 +0000874 while (true) {
875 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000876 if (Token == lltok::kw_builtin)
877 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000878 switch (Token) {
879 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000880 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000881 return Error(Lex.getLoc(), "unterminated attribute group");
882 case lltok::rbrace:
883 // Finished.
884 return false;
885
Bill Wendlingb32b0412013-02-08 06:32:06 +0000886 case lltok::AttrGrpID: {
887 // Allow a function to reference an attribute group:
888 //
889 // define void @foo() #1 { ... }
890 if (inAttrGrp)
891 HaveError |=
892 Error(Lex.getLoc(),
893 "cannot have an attribute group reference in an attribute group");
894
895 unsigned AttrGrpNum = Lex.getUIntVal();
896 if (inAttrGrp) break;
897
898 // Save the reference to the attribute group. We'll fill it in later.
899 FwdRefAttrGrps.push_back(AttrGrpNum);
900 break;
901 }
Bill Wendling63b88192013-02-06 06:52:58 +0000902 // Target-dependent attributes:
903 case lltok::StringConstant: {
904 std::string Attr = Lex.getStrVal();
905 Lex.Lex();
906 std::string Val;
907 if (EatIfPresent(lltok::equal) &&
908 ParseStringConstant(Val))
909 return true;
910
911 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000912 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000913 }
914
915 // Target-independent attributes:
916 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000917 // As a hack, we allow function alignment to be initially parsed as an
918 // attribute on a function declaration/definition or added to an attribute
919 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000920 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000921 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000922 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000923 if (ParseToken(lltok::equal, "expected '=' here") ||
924 ParseUInt32(Alignment))
925 return true;
926 } else {
927 if (ParseOptionalAlignment(Alignment))
928 return true;
929 }
Bill Wendling63b88192013-02-06 06:52:58 +0000930 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000931 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000932 }
933 case lltok::kw_alignstack: {
934 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000935 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000936 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000937 if (ParseToken(lltok::equal, "expected '=' here") ||
938 ParseUInt32(Alignment))
939 return true;
940 } else {
941 if (ParseOptionalStackAlignment(Alignment))
942 return true;
943 }
Bill Wendling63b88192013-02-06 06:52:58 +0000944 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000945 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000946 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000947 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000948 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000949 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000950 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000951 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000952 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
953 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
954 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
955 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
956 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
957 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
958 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
959 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
960 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
961 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000962 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000963 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
964 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
965 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
966 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
967 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
968 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
969 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
970 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
971 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
972 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
973 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000974
975 // Error handling.
976 case lltok::kw_inreg:
977 case lltok::kw_signext:
978 case lltok::kw_zeroext:
979 HaveError |=
980 Error(Lex.getLoc(),
981 "invalid use of attribute on a function");
982 break;
983 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000984 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +0000985 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000986 case lltok::kw_nest:
987 case lltok::kw_noalias:
988 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000989 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000990 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000991 case lltok::kw_sret:
992 HaveError |=
993 Error(Lex.getLoc(),
994 "invalid use of parameter-only attribute on a function");
995 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000996 }
997
998 Lex.Lex();
999 }
1000}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001001
1002//===----------------------------------------------------------------------===//
1003// GlobalValue Reference/Resolution Routines.
1004//===----------------------------------------------------------------------===//
1005
1006/// GetGlobalVal - Get a value with the specified name or ID, creating a
1007/// forward reference record if needed. This can return null if the value
1008/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001009GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001010 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001011 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001012 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001013 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001014 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001015 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001016
Chris Lattnerac161bf2009-01-02 07:01:27 +00001017 // Look this name up in the normal function symbol table.
1018 GlobalValue *Val =
1019 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001020
Chris Lattnerac161bf2009-01-02 07:01:27 +00001021 // If this is a forward reference for the value, see if we already created a
1022 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001023 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001024 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1025 I = ForwardRefVals.find(Name);
1026 if (I != ForwardRefVals.end())
1027 Val = I->second.first;
1028 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
Chris Lattnerac161bf2009-01-02 07:01:27 +00001030 // If we have the value in the symbol table or fwd-ref table, return it.
1031 if (Val) {
1032 if (Val->getType() == Ty) return Val;
1033 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001034 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001035 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001037
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 // Otherwise, create a new forward reference for this value and remember it.
1039 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001040 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001041 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001042 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001043 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001044 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1045 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001046 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001047
Chris Lattnerac161bf2009-01-02 07:01:27 +00001048 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1049 return FwdVal;
1050}
1051
Chris Lattner229907c2011-07-18 04:54:35 +00001052GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1053 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001054 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001056 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001057 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001058
Craig Topper2617dcc2014-04-15 06:32:26 +00001059 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060
Chris Lattnerac161bf2009-01-02 07:01:27 +00001061 // If this is a forward reference for the value, see if we already created a
1062 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001063 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001064 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1065 I = ForwardRefValIDs.find(ID);
1066 if (I != ForwardRefValIDs.end())
1067 Val = I->second.first;
1068 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001069
Chris Lattnerac161bf2009-01-02 07:01:27 +00001070 // If we have the value in the symbol table or fwd-ref table, return it.
1071 if (Val) {
1072 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001073 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001074 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001075 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 // Otherwise, create a new forward reference for this value and remember it.
1079 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001080 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001081 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001082 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001083 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001084 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001085
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1087 return FwdVal;
1088}
1089
1090
1091//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001092// Comdat Reference/Resolution Routines.
1093//===----------------------------------------------------------------------===//
1094
1095Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1096 // Look this name up in the comdat symbol table.
1097 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1098 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1099 if (I != ComdatSymTab.end())
1100 return &I->second;
1101
1102 // Otherwise, create a new forward reference for this value and remember it.
1103 Comdat *C = M->getOrInsertComdat(Name);
1104 ForwardRefComdats[Name] = Loc;
1105 return C;
1106}
1107
1108
1109//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001110// Helper Routines.
1111//===----------------------------------------------------------------------===//
1112
1113/// ParseToken - If the current token has the specified kind, eat it and return
1114/// success. Otherwise, emit the specified error and return failure.
1115bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1116 if (Lex.getKind() != T)
1117 return TokError(ErrMsg);
1118 Lex.Lex();
1119 return false;
1120}
1121
Chris Lattner3822f632009-01-02 08:05:26 +00001122/// ParseStringConstant
1123/// ::= StringConstant
1124bool LLParser::ParseStringConstant(std::string &Result) {
1125 if (Lex.getKind() != lltok::StringConstant)
1126 return TokError("expected string constant");
1127 Result = Lex.getStrVal();
1128 Lex.Lex();
1129 return false;
1130}
1131
1132/// ParseUInt32
1133/// ::= uint32
1134bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1136 return TokError("expected integer");
1137 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1138 if (Val64 != unsigned(Val64))
1139 return TokError("expected 32-bit integer (too large)");
1140 Val = Val64;
1141 Lex.Lex();
1142 return false;
1143}
1144
Hal Finkelb0407ba2014-07-18 15:51:28 +00001145/// ParseUInt64
1146/// ::= uint64
1147bool LLParser::ParseUInt64(uint64_t &Val) {
1148 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1149 return TokError("expected integer");
1150 Val = Lex.getAPSIntVal().getLimitedValue();
1151 Lex.Lex();
1152 return false;
1153}
1154
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001155/// ParseTLSModel
1156/// := 'localdynamic'
1157/// := 'initialexec'
1158/// := 'localexec'
1159bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1160 switch (Lex.getKind()) {
1161 default:
1162 return TokError("expected localdynamic, initialexec or localexec");
1163 case lltok::kw_localdynamic:
1164 TLM = GlobalVariable::LocalDynamicTLSModel;
1165 break;
1166 case lltok::kw_initialexec:
1167 TLM = GlobalVariable::InitialExecTLSModel;
1168 break;
1169 case lltok::kw_localexec:
1170 TLM = GlobalVariable::LocalExecTLSModel;
1171 break;
1172 }
1173
1174 Lex.Lex();
1175 return false;
1176}
1177
1178/// ParseOptionalThreadLocal
1179/// := /*empty*/
1180/// := 'thread_local'
1181/// := 'thread_local' '(' tlsmodel ')'
1182bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1183 TLM = GlobalVariable::NotThreadLocal;
1184 if (!EatIfPresent(lltok::kw_thread_local))
1185 return false;
1186
1187 TLM = GlobalVariable::GeneralDynamicTLSModel;
1188 if (Lex.getKind() == lltok::lparen) {
1189 Lex.Lex();
1190 return ParseTLSModel(TLM) ||
1191 ParseToken(lltok::rparen, "expected ')' after thread local model");
1192 }
1193 return false;
1194}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195
1196/// ParseOptionalAddrSpace
1197/// := /*empty*/
1198/// := 'addrspace' '(' uint32 ')'
1199bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1200 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001201 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001204 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001206}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001207
Bill Wendling34c2eb22012-12-04 23:40:58 +00001208/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1209bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1210 bool HaveError = false;
1211
1212 B.clear();
1213
1214 while (1) {
1215 lltok::Kind Token = Lex.getKind();
1216 switch (Token) {
1217 default: // End of attributes.
1218 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219 case lltok::kw_align: {
1220 unsigned Alignment;
1221 if (ParseOptionalAlignment(Alignment))
1222 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001223 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224 continue;
1225 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001226 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001227 case lltok::kw_dereferenceable: {
1228 uint64_t Bytes;
1229 if (ParseOptionalDereferenceableBytes(Bytes))
1230 return true;
1231 B.addDereferenceableAttr(Bytes);
1232 continue;
1233 }
Reid Klecknera534a382013-12-19 02:14:12 +00001234 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001235 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1236 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1237 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1238 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001239 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001240 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1241 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001242 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001243 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1244 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1245 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001246
Stephen Lin7577ed52013-04-20 13:16:13 +00001247 case lltok::kw_alignstack:
1248 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001249 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001250 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001251 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001252 case lltok::kw_minsize:
1253 case lltok::kw_naked:
1254 case lltok::kw_nobuiltin:
1255 case lltok::kw_noduplicate:
1256 case lltok::kw_noimplicitfloat:
1257 case lltok::kw_noinline:
1258 case lltok::kw_nonlazybind:
1259 case lltok::kw_noredzone:
1260 case lltok::kw_noreturn:
1261 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001262 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001263 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001264 case lltok::kw_returns_twice:
1265 case lltok::kw_sanitize_address:
1266 case lltok::kw_sanitize_memory:
1267 case lltok::kw_sanitize_thread:
1268 case lltok::kw_ssp:
1269 case lltok::kw_sspreq:
1270 case lltok::kw_sspstrong:
1271 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001272 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1273 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001275
Bill Wendling34c2eb22012-12-04 23:40:58 +00001276 Lex.Lex();
1277 }
1278}
1279
1280/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1281bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1282 bool HaveError = false;
1283
1284 B.clear();
1285
1286 while (1) {
1287 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001288 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001289 default: // End of attributes.
1290 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001291 case lltok::kw_dereferenceable: {
1292 uint64_t Bytes;
1293 if (ParseOptionalDereferenceableBytes(Bytes))
1294 return true;
1295 B.addDereferenceableAttr(Bytes);
1296 continue;
1297 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001298 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1299 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001300 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001301 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1302 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001303
Bill Wendling34c2eb22012-12-04 23:40:58 +00001304 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001305 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001306 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001307 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001308 case lltok::kw_nest:
1309 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001310 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001311 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001312 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001313 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001314
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001315 case lltok::kw_alignstack:
1316 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001317 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001318 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001319 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001320 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001321 case lltok::kw_minsize:
1322 case lltok::kw_naked:
1323 case lltok::kw_nobuiltin:
1324 case lltok::kw_noduplicate:
1325 case lltok::kw_noimplicitfloat:
1326 case lltok::kw_noinline:
1327 case lltok::kw_nonlazybind:
1328 case lltok::kw_noredzone:
1329 case lltok::kw_noreturn:
1330 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001331 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001332 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001333 case lltok::kw_returns_twice:
1334 case lltok::kw_sanitize_address:
1335 case lltok::kw_sanitize_memory:
1336 case lltok::kw_sanitize_thread:
1337 case lltok::kw_ssp:
1338 case lltok::kw_sspreq:
1339 case lltok::kw_sspstrong:
1340 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001341 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001342 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001343
1344 case lltok::kw_readnone:
1345 case lltok::kw_readonly:
1346 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001347 }
1348
Chris Lattnerac161bf2009-01-02 07:01:27 +00001349 Lex.Lex();
1350 }
1351}
1352
1353/// ParseOptionalLinkage
1354/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001355/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356/// ::= 'internal'
1357/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001358/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001359/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001360/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001361/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001363/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364/// ::= 'extern_weak'
1365/// ::= 'external'
1366bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1367 HasLinkage = false;
1368 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001369 default: Res=GlobalValue::ExternalLinkage; return false;
1370 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001371 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1372 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1373 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1374 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1375 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001376 case lltok::kw_available_externally:
1377 Res = GlobalValue::AvailableExternallyLinkage;
1378 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001379 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001380 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001381 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1382 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001383 }
1384 Lex.Lex();
1385 HasLinkage = true;
1386 return false;
1387}
1388
1389/// ParseOptionalVisibility
1390/// ::= /*empty*/
1391/// ::= 'default'
1392/// ::= 'hidden'
1393/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001394///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001395bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1396 switch (Lex.getKind()) {
1397 default: Res = GlobalValue::DefaultVisibility; return false;
1398 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1399 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1400 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1401 }
1402 Lex.Lex();
1403 return false;
1404}
1405
Nico Rieck7157bb72014-01-14 15:22:47 +00001406/// ParseOptionalDLLStorageClass
1407/// ::= /*empty*/
1408/// ::= 'dllimport'
1409/// ::= 'dllexport'
1410///
1411bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1412 switch (Lex.getKind()) {
1413 default: Res = GlobalValue::DefaultStorageClass; return false;
1414 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1415 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1416 }
1417 Lex.Lex();
1418 return false;
1419}
1420
Chris Lattnerac161bf2009-01-02 07:01:27 +00001421/// ParseOptionalCallingConv
1422/// ::= /*empty*/
1423/// ::= 'ccc'
1424/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001425/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001426/// ::= 'coldcc'
1427/// ::= 'x86_stdcallcc'
1428/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001429/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001430/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001431/// ::= 'arm_apcscc'
1432/// ::= 'arm_aapcscc'
1433/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001434/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001435/// ::= 'ptx_kernel'
1436/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001437/// ::= 'spir_func'
1438/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001439/// ::= 'x86_64_sysvcc'
1440/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001441/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001442/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001443/// ::= 'preserve_mostcc'
1444/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001445/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001446/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001447///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001448bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001449 switch (Lex.getKind()) {
1450 default: CC = CallingConv::C; return false;
1451 case lltok::kw_ccc: CC = CallingConv::C; break;
1452 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1453 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1454 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1455 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001456 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001457 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001458 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1459 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1460 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001461 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001462 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1463 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001464 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1465 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001466 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001467 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1468 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001469 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001470 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001471 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1472 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001473 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001474 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001475 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001476 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001477 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001478 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001479
Chris Lattnerac161bf2009-01-02 07:01:27 +00001480 Lex.Lex();
1481 return false;
1482}
1483
Chris Lattner5c427632009-12-30 05:31:19 +00001484/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001485/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001486bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1487 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001488 do {
1489 if (Lex.getKind() != lltok::MetadataVar)
1490 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001491
Chris Lattner596760d2009-12-29 21:25:40 +00001492 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001493 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001494 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001495
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001496 MDNode *N;
1497 if (ParseMDNode(N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001498 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001499
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001500 Inst->setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001501 if (MDK == LLVMContext::MD_tbaa)
1502 InstsWithTBAATag.push_back(Inst);
1503
Chris Lattner596760d2009-12-29 21:25:40 +00001504 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001505 } while (EatIfPresent(lltok::comma));
1506 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001507}
1508
Chris Lattnerac161bf2009-01-02 07:01:27 +00001509/// ParseOptionalAlignment
1510/// ::= /* empty */
1511/// ::= 'align' 4
1512bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1513 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001514 if (!EatIfPresent(lltok::kw_align))
1515 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001516 LocTy AlignLoc = Lex.getLoc();
1517 if (ParseUInt32(Alignment)) return true;
1518 if (!isPowerOf2_32(Alignment))
1519 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001520 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001521 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001522 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001523}
1524
Hal Finkelb0407ba2014-07-18 15:51:28 +00001525/// ParseOptionalDereferenceableBytes
1526/// ::= /* empty */
1527/// ::= 'dereferenceable' '(' 4 ')'
1528bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1529 Bytes = 0;
1530 if (!EatIfPresent(lltok::kw_dereferenceable))
1531 return false;
1532 LocTy ParenLoc = Lex.getLoc();
1533 if (!EatIfPresent(lltok::lparen))
1534 return Error(ParenLoc, "expected '('");
1535 LocTy DerefLoc = Lex.getLoc();
1536 if (ParseUInt64(Bytes)) return true;
1537 ParenLoc = Lex.getLoc();
1538 if (!EatIfPresent(lltok::rparen))
1539 return Error(ParenLoc, "expected ')'");
1540 if (!Bytes)
1541 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1542 return false;
1543}
1544
Chris Lattnerb2f39502009-12-30 05:44:30 +00001545/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001546/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001547/// ::= ',' align 4
1548///
1549/// This returns with AteExtraComma set to true if it ate an excess comma at the
1550/// end.
1551bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1552 bool &AteExtraComma) {
1553 AteExtraComma = false;
1554 while (EatIfPresent(lltok::comma)) {
1555 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001556 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001557 AteExtraComma = true;
1558 return false;
1559 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001560
Chris Lattner95b0ff42010-04-23 00:50:50 +00001561 if (Lex.getKind() != lltok::kw_align)
1562 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001563
Chris Lattner95b0ff42010-04-23 00:50:50 +00001564 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001565 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001566
Devang Patelea8a4b92009-09-17 23:04:48 +00001567 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001568}
1569
Eli Friedmanfee02c62011-07-25 23:16:38 +00001570/// ParseScopeAndOrdering
1571/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1572/// else: ::=
1573///
1574/// This sets Scope and Ordering to the parsed values.
1575bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1576 AtomicOrdering &Ordering) {
1577 if (!isAtomic)
1578 return false;
1579
1580 Scope = CrossThread;
1581 if (EatIfPresent(lltok::kw_singlethread))
1582 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001583
1584 return ParseOrdering(Ordering);
1585}
1586
1587/// ParseOrdering
1588/// ::= AtomicOrdering
1589///
1590/// This sets Ordering to the parsed value.
1591bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001592 switch (Lex.getKind()) {
1593 default: return TokError("Expected ordering on atomic instruction");
1594 case lltok::kw_unordered: Ordering = Unordered; break;
1595 case lltok::kw_monotonic: Ordering = Monotonic; break;
1596 case lltok::kw_acquire: Ordering = Acquire; break;
1597 case lltok::kw_release: Ordering = Release; break;
1598 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1599 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1600 }
1601 Lex.Lex();
1602 return false;
1603}
1604
Charles Davisbe5557e2010-02-12 00:31:15 +00001605/// ParseOptionalStackAlignment
1606/// ::= /* empty */
1607/// ::= 'alignstack' '(' 4 ')'
1608bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1609 Alignment = 0;
1610 if (!EatIfPresent(lltok::kw_alignstack))
1611 return false;
1612 LocTy ParenLoc = Lex.getLoc();
1613 if (!EatIfPresent(lltok::lparen))
1614 return Error(ParenLoc, "expected '('");
1615 LocTy AlignLoc = Lex.getLoc();
1616 if (ParseUInt32(Alignment)) return true;
1617 ParenLoc = Lex.getLoc();
1618 if (!EatIfPresent(lltok::rparen))
1619 return Error(ParenLoc, "expected ')'");
1620 if (!isPowerOf2_32(Alignment))
1621 return Error(AlignLoc, "stack alignment is not a power of two");
1622 return false;
1623}
Devang Patelea8a4b92009-09-17 23:04:48 +00001624
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001625/// ParseIndexList - This parses the index list for an insert/extractvalue
1626/// instruction. This sets AteExtraComma in the case where we eat an extra
1627/// comma at the end of the line and find that it is followed by metadata.
1628/// Clients that don't allow metadata can call the version of this function that
1629/// only takes one argument.
1630///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001631/// ParseIndexList
1632/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001633///
1634bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1635 bool &AteExtraComma) {
1636 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001637
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638 if (Lex.getKind() != lltok::comma)
1639 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001640
Chris Lattner3822f632009-01-02 08:05:26 +00001641 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001642 if (Lex.getKind() == lltok::MetadataVar) {
1643 AteExtraComma = true;
1644 return false;
1645 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001646 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001647 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001648 Indices.push_back(Idx);
1649 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001650
Chris Lattnerac161bf2009-01-02 07:01:27 +00001651 return false;
1652}
1653
1654//===----------------------------------------------------------------------===//
1655// Type Parsing.
1656//===----------------------------------------------------------------------===//
1657
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001658/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001659bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001660 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001661 switch (Lex.getKind()) {
1662 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001663 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001664 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001665 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001666 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001667 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001668 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001669 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001670 // Type ::= StructType
1671 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001672 return true;
1673 break;
1674 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001676 Lex.Lex(); // eat the lsquare.
1677 if (ParseArrayVectorType(Result, false))
1678 return true;
1679 break;
1680 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001681 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001682 Lex.Lex();
1683 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001684 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001685 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001687 } else if (ParseArrayVectorType(Result, true))
1688 return true;
1689 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001690 case lltok::LocalVar: {
1691 // Type ::= %foo
1692 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001693
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 // If the type hasn't been defined yet, create a forward definition and
1695 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001696 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001697 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001698 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001699 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001700 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701 Lex.Lex();
1702 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001704
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001705 case lltok::LocalVarID: {
1706 // Type ::= %4
1707 if (Lex.getUIntVal() >= NumberedTypes.size())
1708 NumberedTypes.resize(Lex.getUIntVal()+1);
1709 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001710
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711 // If the type hasn't been defined yet, create a forward definition and
1712 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001713 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001714 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001716 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001717 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001718 Lex.Lex();
1719 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001720 }
1721 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001722
1723 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724 while (1) {
1725 switch (Lex.getKind()) {
1726 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001727 default:
1728 if (!AllowVoid && Result->isVoidTy())
1729 return Error(TypeLoc, "void type only allowed for function results");
1730 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001731
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001733 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001734 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001735 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001736 if (Result->isVoidTy())
1737 return TokError("pointers to void are invalid - use i8* instead");
1738 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001739 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001740 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001741 Lex.Lex();
1742 break;
1743
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001744 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001745 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001746 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001747 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001748 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001749 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001750 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001751 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 unsigned AddrSpace;
1753 if (ParseOptionalAddrSpace(AddrSpace) ||
1754 ParseToken(lltok::star, "expected '*' in address space"))
1755 return true;
1756
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001757 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001758 break;
1759 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001760
Chris Lattnerac161bf2009-01-02 07:01:27 +00001761 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1762 case lltok::lparen:
1763 if (ParseFunctionType(Result))
1764 return true;
1765 break;
1766 }
1767 }
1768}
1769
1770/// ParseParameterList
1771/// ::= '(' ')'
1772/// ::= '(' Arg (',' Arg)* ')'
1773/// Arg
1774/// ::= Type OptionalAttributes Value OptionalAttributes
1775bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001776 PerFunctionState &PFS, bool IsMustTailCall,
1777 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001778 if (ParseToken(lltok::lparen, "expected '(' in call"))
1779 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001780
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001781 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782 while (Lex.getKind() != lltok::rparen) {
1783 // If this isn't the first argument, we need a comma.
1784 if (!ArgList.empty() &&
1785 ParseToken(lltok::comma, "expected ',' in argument list"))
1786 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001787
Reid Kleckner83498642014-08-26 00:33:28 +00001788 // Parse an ellipsis if this is a musttail call in a variadic function.
1789 if (Lex.getKind() == lltok::dotdotdot) {
1790 const char *Msg = "unexpected ellipsis in argument list for ";
1791 if (!IsMustTailCall)
1792 return TokError(Twine(Msg) + "non-musttail call");
1793 if (!InVarArgsFunc)
1794 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1795 Lex.Lex(); // Lex the '...', it is purely for readability.
1796 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1797 }
1798
Chris Lattnerac161bf2009-01-02 07:01:27 +00001799 // Parse the argument.
1800 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001801 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001802 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001804 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001805 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001806
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001807 if (ArgTy->isMetadataTy()) {
1808 if (ParseMetadataAsValue(V, PFS))
1809 return true;
1810 } else {
1811 // Otherwise, handle normal operands.
1812 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1813 return true;
1814 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001815 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1816 AttrIndex++,
1817 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001818 }
1819
Reid Kleckner83498642014-08-26 00:33:28 +00001820 if (IsMustTailCall && InVarArgsFunc)
1821 return TokError("expected '...' at end of argument list for musttail call "
1822 "in varargs function");
1823
Chris Lattnerac161bf2009-01-02 07:01:27 +00001824 Lex.Lex(); // Lex the ')'.
1825 return false;
1826}
1827
1828
1829
Chris Lattner2ed06b42009-01-05 18:34:07 +00001830/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001831/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001832/// ::= '(' ArgTypeListI ')'
1833/// ArgTypeListI
1834/// ::= /*empty*/
1835/// ::= '...'
1836/// ::= ArgTypeList ',' '...'
1837/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001838///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001839bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1840 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001841 isVarArg = false;
1842 assert(Lex.getKind() == lltok::lparen);
1843 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001844
Chris Lattnerac161bf2009-01-02 07:01:27 +00001845 if (Lex.getKind() == lltok::rparen) {
1846 // empty
1847 } else if (Lex.getKind() == lltok::dotdotdot) {
1848 isVarArg = true;
1849 Lex.Lex();
1850 } else {
1851 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001852 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001853 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001855
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001856 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001857 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001858
Chris Lattnerfdd87902009-10-05 05:54:46 +00001859 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001860 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001861
Chris Lattnerdef19492011-06-17 06:36:20 +00001862 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001863 Name = Lex.getStrVal();
1864 Lex.Lex();
1865 }
Chris Lattner3822f632009-01-02 08:05:26 +00001866
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001867 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001868 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001869
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001870 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001871 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001872 AttributeSet::get(ArgTy->getContext(),
1873 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001874
Chris Lattner3822f632009-01-02 08:05:26 +00001875 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001877 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001878 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001879 break;
1880 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001881
Chris Lattnerac161bf2009-01-02 07:01:27 +00001882 // Otherwise must be an argument type.
1883 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001884 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001885
Chris Lattnerfdd87902009-10-05 05:54:46 +00001886 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001887 return Error(TypeLoc, "argument can not have void type");
1888
Chris Lattnerdef19492011-06-17 06:36:20 +00001889 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001890 Name = Lex.getStrVal();
1891 Lex.Lex();
1892 } else {
1893 Name = "";
1894 }
Chris Lattner3822f632009-01-02 08:05:26 +00001895
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001896 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001897 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001898
Bill Wendlingd079a442012-10-15 04:46:55 +00001899 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001900 AttributeSet::get(ArgTy->getContext(),
1901 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001902 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001903 }
1904 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Chris Lattner3822f632009-01-02 08:05:26 +00001906 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Chris Lattnerac161bf2009-01-02 07:01:27 +00001909/// ParseFunctionType
1910/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001911bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001912 assert(Lex.getKind() == lltok::lparen);
1913
Chris Lattnerce473c72009-01-05 08:04:33 +00001914 if (!FunctionType::isValidReturnType(Result))
1915 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001916
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001919 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001921
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922 // Reject names on the arguments lists.
1923 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1924 if (!ArgList[i].Name.empty())
1925 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001926 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001927 return Error(ArgList[i].Loc,
1928 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001930
Jay Foadb804a2b2011-07-12 14:06:48 +00001931 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001934
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001935 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001936 return false;
1937}
1938
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1940/// other structs.
1941bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1942 SmallVector<Type*, 8> Elts;
1943 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001944
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 Result = StructType::get(Context, Elts, Packed);
1946 return false;
1947}
1948
1949/// ParseStructDefinition - Parse a struct in a 'type' definition.
1950bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1951 std::pair<Type*, LocTy> &Entry,
1952 Type *&ResultTy) {
1953 // If the type was already defined, diagnose the redefinition.
1954 if (Entry.first && !Entry.second.isValid())
1955 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001956
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001957 // If we have opaque, just return without filling in the definition for the
1958 // struct. This counts as a definition as far as the .ll file goes.
1959 if (EatIfPresent(lltok::kw_opaque)) {
1960 // This type is being defined, so clear the location to indicate this.
1961 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001962
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001964 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001965 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001966 ResultTy = Entry.first;
1967 return false;
1968 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970 // If the type starts with '<', then it is either a packed struct or a vector.
1971 bool isPacked = EatIfPresent(lltok::less);
1972
1973 // If we don't have a struct, then we have a random type alias, which we
1974 // accept for compatibility with old files. These types are not allowed to be
1975 // forward referenced and not allowed to be recursive.
1976 if (Lex.getKind() != lltok::lbrace) {
1977 if (Entry.first)
1978 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001979
Craig Topper2617dcc2014-04-15 06:32:26 +00001980 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981 if (isPacked)
1982 return ParseArrayVectorType(ResultTy, true);
1983 return ParseType(ResultTy);
1984 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001985
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001986 // This type is being defined, so clear the location to indicate this.
1987 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001988
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001990 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001991 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001994
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001995 SmallVector<Type*, 8> Body;
1996 if (ParseStructBody(Body) ||
1997 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1998 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001999
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002000 STy->setBody(Body, isPacked);
2001 ResultTy = STy;
2002 return false;
2003}
2004
2005
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002011/// ::= '<' '{' Type (',' Type)* '}' '>'
2012bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002013 assert(Lex.getKind() == lltok::lbrace);
2014 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002016 // Handle the empty struct.
2017 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002019
Chris Lattnerf880ca22009-03-09 04:49:14 +00002020 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002021 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 if (ParseType(Ty)) return true;
2023 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002024
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002026 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002027
Chris Lattner3822f632009-01-02 08:05:26 +00002028 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002029 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002031
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002033 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002034
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002037
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002038 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002039}
2040
2041/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2042/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044/// ::= '[' APSINTVAL 'x' Types ']'
2045/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002046bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002047 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2048 Lex.getAPSIntVal().getBitWidth() > 64)
2049 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002050
Chris Lattnerac161bf2009-01-02 07:01:27 +00002051 LocTy SizeLoc = Lex.getLoc();
2052 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002053 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002054
Chris Lattner3822f632009-01-02 08:05:26 +00002055 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2056 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057
2058 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002059 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002061
Chris Lattner3822f632009-01-02 08:05:26 +00002062 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2063 "expected end of sequential type"))
2064 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002065
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002067 if (Size == 0)
2068 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069 if ((unsigned)Size != Size)
2070 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002071 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002072 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002073 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002074 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002075 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078 }
2079 return false;
2080}
2081
2082//===----------------------------------------------------------------------===//
2083// Function Semantic Analysis.
2084//===----------------------------------------------------------------------===//
2085
Chris Lattner3432c622009-10-28 03:39:23 +00002086LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2087 int functionNumber)
2088 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089
2090 // Insert unnamed arguments into the NumberedVals list.
2091 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2092 AI != E; ++AI)
2093 if (!AI->hasName())
2094 NumberedVals.push_back(AI);
2095}
2096
2097LLParser::PerFunctionState::~PerFunctionState() {
2098 // If there were any forward referenced non-basicblock values, delete them.
2099 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2100 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2101 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002102 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002103 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002105 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002107
Chris Lattnerac161bf2009-01-02 07:01:27 +00002108 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2109 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2110 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002111 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002112 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002114 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 }
2116}
2117
Chris Lattner3432c622009-10-28 03:39:23 +00002118bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 if (!ForwardRefVals.empty())
2120 return P.Error(ForwardRefVals.begin()->second.second,
2121 "use of undefined value '%" + ForwardRefVals.begin()->first +
2122 "'");
2123 if (!ForwardRefValIDs.empty())
2124 return P.Error(ForwardRefValIDs.begin()->second.second,
2125 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002126 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 return false;
2128}
2129
2130
2131/// GetVal - Get a value with the specified name or ID, creating a
2132/// forward reference record if needed. This can return null if the value
2133/// exists but does not have the right type.
2134Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002135 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 // Look this name up in the normal function symbol table.
2137 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002138
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 // If this is a forward reference for the value, see if we already created a
2140 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002141 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2143 I = ForwardRefVals.find(Name);
2144 if (I != ForwardRefVals.end())
2145 Val = I->second.first;
2146 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002147
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 // If we have the value in the symbol table or fwd-ref table, return it.
2149 if (Val) {
2150 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002151 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 P.Error(Loc, "'%" + Name + "' is not a basic block");
2153 else
2154 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002155 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002156 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002158
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002160 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002161 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002162 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002164
Chris Lattnerac161bf2009-01-02 07:01:27 +00002165 // Otherwise, create a new forward reference for this value and remember it.
2166 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002167 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002168 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 else
2170 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002171
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2173 return FwdVal;
2174}
2175
Chris Lattner229907c2011-07-18 04:54:35 +00002176Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002177 LocTy Loc) {
2178 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002179 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002180
Chris Lattnerac161bf2009-01-02 07:01:27 +00002181 // If this is a forward reference for the value, see if we already created a
2182 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002183 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2185 I = ForwardRefValIDs.find(ID);
2186 if (I != ForwardRefValIDs.end())
2187 Val = I->second.first;
2188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002189
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 // If we have the value in the symbol table or fwd-ref table, return it.
2191 if (Val) {
2192 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002193 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002194 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002196 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002197 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002198 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002201 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002203 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002204 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002205
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 // Otherwise, create a new forward reference for this value and remember it.
2207 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002208 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002209 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 else
2211 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2214 return FwdVal;
2215}
2216
2217/// SetInstName - After an instruction is parsed and inserted into its
2218/// basic block, this installs its name.
2219bool LLParser::PerFunctionState::SetInstName(int NameID,
2220 const std::string &NameStr,
2221 LocTy NameLoc, Instruction *Inst) {
2222 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002223 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002224 if (NameID != -1 || !NameStr.empty())
2225 return P.Error(NameLoc, "instructions returning void cannot have a name");
2226 return false;
2227 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002228
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 // If this was a numbered instruction, verify that the instruction is the
2230 // expected value and resolve any forward references.
2231 if (NameStr.empty()) {
2232 // If neither a name nor an ID was specified, just use the next ID.
2233 if (NameID == -1)
2234 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002235
Chris Lattnerac161bf2009-01-02 07:01:27 +00002236 if (unsigned(NameID) != NumberedVals.size())
2237 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002238 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002239
Chris Lattnerac161bf2009-01-02 07:01:27 +00002240 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2241 ForwardRefValIDs.find(NameID);
2242 if (FI != ForwardRefValIDs.end()) {
2243 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002245 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002247 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 ForwardRefValIDs.erase(FI);
2249 }
2250
2251 NumberedVals.push_back(Inst);
2252 return false;
2253 }
2254
2255 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2256 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2257 FI = ForwardRefVals.find(NameStr);
2258 if (FI != ForwardRefVals.end()) {
2259 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002260 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002261 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002263 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264 ForwardRefVals.erase(FI);
2265 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 // Set the name on the instruction.
2268 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002269
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002270 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002271 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 NameStr + "'");
2273 return false;
2274}
2275
2276/// GetBB - Get a basic block with the specified name or ID, creating a
2277/// forward reference record if needed.
2278BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2279 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002280 return cast_or_null<BasicBlock>(GetVal(Name,
2281 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282}
2283
2284BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002285 return cast_or_null<BasicBlock>(GetVal(ID,
2286 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287}
2288
2289/// DefineBB - Define the specified basic block, which is either named or
2290/// unnamed. If there is an error, this returns null otherwise it returns
2291/// the block being defined.
2292BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2293 LocTy Loc) {
2294 BasicBlock *BB;
2295 if (Name.empty())
2296 BB = GetBB(NumberedVals.size(), Loc);
2297 else
2298 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002299 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002300
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301 // Move the block to the end of the function. Forward ref'd blocks are
2302 // inserted wherever they happen to be referenced.
2303 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 // Remove the block from forward ref sets.
2306 if (Name.empty()) {
2307 ForwardRefValIDs.erase(NumberedVals.size());
2308 NumberedVals.push_back(BB);
2309 } else {
2310 // BB forward references are already in the function symbol table.
2311 ForwardRefVals.erase(Name);
2312 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002313
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 return BB;
2315}
2316
2317//===----------------------------------------------------------------------===//
2318// Constants.
2319//===----------------------------------------------------------------------===//
2320
2321/// ParseValID - Parse an abstract value that doesn't necessarily have a
2322/// type implied. For example, if we parse "4" we don't know what integer type
2323/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002324/// sanity. PFS is used to convert function-local operands of metadata (since
2325/// metadata operands are not just parsed here but also converted to values).
2326/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002327bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328 ID.Loc = Lex.getLoc();
2329 switch (Lex.getKind()) {
2330 default: return TokError("expected value token");
2331 case lltok::GlobalID: // @42
2332 ID.UIntVal = Lex.getUIntVal();
2333 ID.Kind = ValID::t_GlobalID;
2334 break;
2335 case lltok::GlobalVar: // @foo
2336 ID.StrVal = Lex.getStrVal();
2337 ID.Kind = ValID::t_GlobalName;
2338 break;
2339 case lltok::LocalVarID: // %42
2340 ID.UIntVal = Lex.getUIntVal();
2341 ID.Kind = ValID::t_LocalID;
2342 break;
2343 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344 ID.StrVal = Lex.getStrVal();
2345 ID.Kind = ValID::t_LocalName;
2346 break;
2347 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 ID.Kind = ValID::t_APSInt;
2350 break;
2351 case lltok::APFloat:
2352 ID.APFloatVal = Lex.getAPFloatVal();
2353 ID.Kind = ValID::t_APFloat;
2354 break;
2355 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002356 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002357 ID.Kind = ValID::t_Constant;
2358 break;
2359 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002360 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361 ID.Kind = ValID::t_Constant;
2362 break;
2363 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2364 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2365 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002366
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367 case lltok::lbrace: {
2368 // ValID ::= '{' ConstVector '}'
2369 Lex.Lex();
2370 SmallVector<Constant*, 16> Elts;
2371 if (ParseGlobalValueVector(Elts) ||
2372 ParseToken(lltok::rbrace, "expected end of struct constant"))
2373 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002374
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002375 ID.ConstantStructElts = new Constant*[Elts.size()];
2376 ID.UIntVal = Elts.size();
2377 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2378 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379 return false;
2380 }
2381 case lltok::less: {
2382 // ValID ::= '<' ConstVector '>' --> Vector.
2383 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2384 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002385 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 SmallVector<Constant*, 16> Elts;
2388 LocTy FirstEltLoc = Lex.getLoc();
2389 if (ParseGlobalValueVector(Elts) ||
2390 (isPackedStruct &&
2391 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2392 ParseToken(lltok::greater, "expected end of constant"))
2393 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 ID.ConstantStructElts = new Constant*[Elts.size()];
2397 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2398 ID.UIntVal = Elts.size();
2399 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 return false;
2401 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002402
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 if (Elts.empty())
2404 return Error(ID.Loc, "constant vector must not be empty");
2405
Duncan Sands9dff9be2010-02-15 16:12:20 +00002406 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002407 !Elts[0]->getType()->isFloatingPointTy() &&
2408 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002410 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002411
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412 // Verify that all the vector elements have the same type.
2413 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2414 if (Elts[i]->getType() != Elts[0]->getType())
2415 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002416 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002417 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418
Chris Lattner69229312011-02-15 00:14:00 +00002419 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002420 ID.Kind = ValID::t_Constant;
2421 return false;
2422 }
2423 case lltok::lsquare: { // Array Constant
2424 Lex.Lex();
2425 SmallVector<Constant*, 16> Elts;
2426 LocTy FirstEltLoc = Lex.getLoc();
2427 if (ParseGlobalValueVector(Elts) ||
2428 ParseToken(lltok::rsquare, "expected end of array constant"))
2429 return true;
2430
2431 // Handle empty element.
2432 if (Elts.empty()) {
2433 // Use undef instead of an array because it's inconvenient to determine
2434 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002435 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 return false;
2437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002438
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002440 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002441 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Owen Anderson4056ca92009-07-29 22:17:13 +00002443 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002446 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 if (Elts[i]->getType() != Elts[0]->getType())
2448 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002449 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002450 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002452
Jay Foad83be3612011-06-22 09:24:39 +00002453 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002454 ID.Kind = ValID::t_Constant;
2455 return false;
2456 }
2457 case lltok::kw_c: // c "foo"
2458 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002459 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2460 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2462 ID.Kind = ValID::t_Constant;
2463 return false;
2464
2465 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002466 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2467 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002468 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 Lex.Lex();
2470 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002471 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002472 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002473 ParseStringConstant(ID.StrVal) ||
2474 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 ParseToken(lltok::StringConstant, "expected constraint string"))
2476 return true;
2477 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002478 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002479 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480 ID.Kind = ValID::t_InlineAsm;
2481 return false;
2482 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002483
Chris Lattner3432c622009-10-28 03:39:23 +00002484 case lltok::kw_blockaddress: {
2485 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2486 Lex.Lex();
2487
2488 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002489
Chris Lattner3432c622009-10-28 03:39:23 +00002490 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2491 ParseValID(Fn) ||
2492 ParseToken(lltok::comma, "expected comma in block address expression")||
2493 ParseValID(Label) ||
2494 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2495 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002496
Chris Lattner3432c622009-10-28 03:39:23 +00002497 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2498 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002499 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002500 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002501
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002502 // Try to find the function (but skip it if it's forward-referenced).
2503 GlobalValue *GV = nullptr;
2504 if (Fn.Kind == ValID::t_GlobalID) {
2505 if (Fn.UIntVal < NumberedVals.size())
2506 GV = NumberedVals[Fn.UIntVal];
2507 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2508 GV = M->getNamedValue(Fn.StrVal);
2509 }
2510 Function *F = nullptr;
2511 if (GV) {
2512 // Confirm that it's actually a function with a definition.
2513 if (!isa<Function>(GV))
2514 return Error(Fn.Loc, "expected function name in blockaddress");
2515 F = cast<Function>(GV);
2516 if (F->isDeclaration())
2517 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2518 }
2519
2520 if (!F) {
2521 // Make a global variable as a placeholder for this reference.
2522 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2523 if (!FwdRef)
2524 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2525 GlobalValue::InternalLinkage, nullptr, "");
2526 ID.ConstantVal = FwdRef;
2527 ID.Kind = ValID::t_Constant;
2528 return false;
2529 }
2530
2531 // We found the function; now find the basic block. Don't use PFS, since we
2532 // might be inside a constant expression.
2533 BasicBlock *BB;
2534 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2535 if (Label.Kind == ValID::t_LocalID)
2536 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2537 else
2538 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2539 if (!BB)
2540 return Error(Label.Loc, "referenced value is not a basic block");
2541 } else {
2542 if (Label.Kind == ValID::t_LocalID)
2543 return Error(Label.Loc, "cannot take address of numeric label after "
2544 "the function is defined");
2545 BB = dyn_cast_or_null<BasicBlock>(
2546 F->getValueSymbolTable().lookup(Label.StrVal));
2547 if (!BB)
2548 return Error(Label.Loc, "referenced value is not a basic block");
2549 }
2550
2551 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002552 ID.Kind = ValID::t_Constant;
2553 return false;
2554 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002555
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 case lltok::kw_trunc:
2557 case lltok::kw_zext:
2558 case lltok::kw_sext:
2559 case lltok::kw_fptrunc:
2560 case lltok::kw_fpext:
2561 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002562 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 case lltok::kw_uitofp:
2564 case lltok::kw_sitofp:
2565 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002568 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002570 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002571 Constant *SrcVal;
2572 Lex.Lex();
2573 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2574 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002575 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 ParseType(DestTy) ||
2577 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2578 return true;
2579 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2580 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002581 getTypeString(SrcVal->getType()) + "' to '" +
2582 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002583 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002584 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002585 ID.Kind = ValID::t_Constant;
2586 return false;
2587 }
2588 case lltok::kw_extractvalue: {
2589 Lex.Lex();
2590 Constant *Val;
2591 SmallVector<unsigned, 4> Indices;
2592 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2593 ParseGlobalTypeAndValue(Val) ||
2594 ParseIndexList(Indices) ||
2595 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2596 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002597
Chris Lattner392be582010-02-12 20:49:41 +00002598 if (!Val->getType()->isAggregateType())
2599 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002600 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002601 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002602 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002603 ID.Kind = ValID::t_Constant;
2604 return false;
2605 }
2606 case lltok::kw_insertvalue: {
2607 Lex.Lex();
2608 Constant *Val0, *Val1;
2609 SmallVector<unsigned, 4> Indices;
2610 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2611 ParseGlobalTypeAndValue(Val0) ||
2612 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2613 ParseGlobalTypeAndValue(Val1) ||
2614 ParseIndexList(Indices) ||
2615 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2616 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002617 if (!Val0->getType()->isAggregateType())
2618 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002619 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002621 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 ID.Kind = ValID::t_Constant;
2623 return false;
2624 }
2625 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002626 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 unsigned PredVal, Opc = Lex.getUIntVal();
2628 Constant *Val0, *Val1;
2629 Lex.Lex();
2630 if (ParseCmpPredicate(PredVal, Opc) ||
2631 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2632 ParseGlobalTypeAndValue(Val0) ||
2633 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2634 ParseGlobalTypeAndValue(Val1) ||
2635 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2636 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002637
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 if (Val0->getType() != Val1->getType())
2639 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002640
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002642
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002644 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002646 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002647 } else {
2648 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002649 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002650 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002652 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 }
2654 ID.Kind = ValID::t_Constant;
2655 return false;
2656 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 // Binary Operators.
2659 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002660 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002662 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002664 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 case lltok::kw_udiv:
2666 case lltok::kw_sdiv:
2667 case lltok::kw_fdiv:
2668 case lltok::kw_urem:
2669 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002670 case lltok::kw_frem:
2671 case lltok::kw_shl:
2672 case lltok::kw_lshr:
2673 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002674 bool NUW = false;
2675 bool NSW = false;
2676 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 unsigned Opc = Lex.getUIntVal();
2678 Constant *Val0, *Val1;
2679 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002680 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002681 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2682 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002683 if (EatIfPresent(lltok::kw_nuw))
2684 NUW = true;
2685 if (EatIfPresent(lltok::kw_nsw)) {
2686 NSW = true;
2687 if (EatIfPresent(lltok::kw_nuw))
2688 NUW = true;
2689 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002690 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2691 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002692 if (EatIfPresent(lltok::kw_exact))
2693 Exact = true;
2694 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2696 ParseGlobalTypeAndValue(Val0) ||
2697 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2698 ParseGlobalTypeAndValue(Val1) ||
2699 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2700 return true;
2701 if (Val0->getType() != Val1->getType())
2702 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002703 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002704 if (NUW)
2705 return Error(ModifierLoc, "nuw only applies to integer operations");
2706 if (NSW)
2707 return Error(ModifierLoc, "nsw only applies to integer operations");
2708 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002709 // Check that the type is valid for the operator.
2710 switch (Opc) {
2711 case Instruction::Add:
2712 case Instruction::Sub:
2713 case Instruction::Mul:
2714 case Instruction::UDiv:
2715 case Instruction::SDiv:
2716 case Instruction::URem:
2717 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002718 case Instruction::Shl:
2719 case Instruction::AShr:
2720 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002721 if (!Val0->getType()->isIntOrIntVectorTy())
2722 return Error(ID.Loc, "constexpr requires integer operands");
2723 break;
2724 case Instruction::FAdd:
2725 case Instruction::FSub:
2726 case Instruction::FMul:
2727 case Instruction::FDiv:
2728 case Instruction::FRem:
2729 if (!Val0->getType()->isFPOrFPVectorTy())
2730 return Error(ID.Loc, "constexpr requires fp operands");
2731 break;
2732 default: llvm_unreachable("Unknown binary operator!");
2733 }
Dan Gohman1b849082009-09-07 23:54:19 +00002734 unsigned Flags = 0;
2735 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2736 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002737 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002738 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002739 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002740 ID.Kind = ValID::t_Constant;
2741 return false;
2742 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002743
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002745 case lltok::kw_and:
2746 case lltok::kw_or:
2747 case lltok::kw_xor: {
2748 unsigned Opc = Lex.getUIntVal();
2749 Constant *Val0, *Val1;
2750 Lex.Lex();
2751 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2752 ParseGlobalTypeAndValue(Val0) ||
2753 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2754 ParseGlobalTypeAndValue(Val1) ||
2755 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2756 return true;
2757 if (Val0->getType() != Val1->getType())
2758 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002759 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002760 return Error(ID.Loc,
2761 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002762 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002763 ID.Kind = ValID::t_Constant;
2764 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002765 }
2766
Chris Lattnerac161bf2009-01-02 07:01:27 +00002767 case lltok::kw_getelementptr:
2768 case lltok::kw_shufflevector:
2769 case lltok::kw_insertelement:
2770 case lltok::kw_extractelement:
2771 case lltok::kw_select: {
2772 unsigned Opc = Lex.getUIntVal();
2773 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002774 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002776 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002777 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002778 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2779 ParseGlobalValueVector(Elts) ||
2780 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2781 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002782
Chris Lattnerac161bf2009-01-02 07:01:27 +00002783 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002784 if (Elts.size() == 0 ||
2785 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002786 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787
Jay Foaded8db7d2011-07-21 14:31:17 +00002788 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002789 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002791 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2792 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 } else if (Opc == Instruction::Select) {
2794 if (Elts.size() != 3)
2795 return Error(ID.Loc, "expected three operands to select");
2796 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2797 Elts[2]))
2798 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002799 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 } else if (Opc == Instruction::ShuffleVector) {
2801 if (Elts.size() != 3)
2802 return Error(ID.Loc, "expected three operands to shufflevector");
2803 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2804 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002805 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002806 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002807 } else if (Opc == Instruction::ExtractElement) {
2808 if (Elts.size() != 2)
2809 return Error(ID.Loc, "expected two operands to extractelement");
2810 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2811 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002812 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 } else {
2814 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2815 if (Elts.size() != 3)
2816 return Error(ID.Loc, "expected three operands to insertelement");
2817 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2818 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002819 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002820 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002822
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 ID.Kind = ValID::t_Constant;
2824 return false;
2825 }
2826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002827
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 Lex.Lex();
2829 return false;
2830}
2831
2832/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002833bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002834 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002836 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002837 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002838 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002839 if (V && !(C = dyn_cast<Constant>(V)))
2840 return Error(ID.Loc, "global values must be constants");
2841 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002842}
2843
Victor Hernandez9d75c962010-01-11 22:31:58 +00002844bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002845 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002846 return ParseType(Ty) ||
2847 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002848}
2849
Rafael Espindola83a362c2015-01-06 22:55:16 +00002850bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002851 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002852
2853 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002854 if (!EatIfPresent(lltok::kw_comdat))
2855 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002856
2857 if (EatIfPresent(lltok::lparen)) {
2858 if (Lex.getKind() != lltok::ComdatVar)
2859 return TokError("expected comdat variable");
2860 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2861 Lex.Lex();
2862 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2863 return true;
2864 } else {
2865 if (GlobalName.empty())
2866 return TokError("comdat cannot be unnamed");
2867 C = getComdat(GlobalName, KwLoc);
2868 }
2869
David Majnemerdad0a642014-06-27 18:19:56 +00002870 return false;
2871}
2872
Victor Hernandez9d75c962010-01-11 22:31:58 +00002873/// ParseGlobalValueVector
2874/// ::= /*empty*/
2875/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002876bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002877 // Empty list.
2878 if (Lex.getKind() == lltok::rbrace ||
2879 Lex.getKind() == lltok::rsquare ||
2880 Lex.getKind() == lltok::greater ||
2881 Lex.getKind() == lltok::rparen)
2882 return false;
2883
2884 Constant *C;
2885 if (ParseGlobalTypeAndValue(C)) return true;
2886 Elts.push_back(C);
2887
2888 while (EatIfPresent(lltok::comma)) {
2889 if (ParseGlobalTypeAndValue(C)) return true;
2890 Elts.push_back(C);
2891 }
2892
2893 return false;
2894}
2895
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002896bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002897 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002898 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002899 return true;
2900
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002901 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002902 return false;
2903}
2904
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002905/// MDNode:
2906/// ::= !{ ... }
2907/// ::= !7
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002908/// ::= !MDLocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002909bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002910 if (Lex.getKind() == lltok::MetadataVar)
2911 return ParseSpecializedMDNode(N);
2912
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002913 return ParseToken(lltok::exclaim, "expected '!' here") ||
2914 ParseMDNodeTail(N);
2915}
2916
2917bool LLParser::ParseMDNodeTail(MDNode *&N) {
2918 // !{ ... }
2919 if (Lex.getKind() == lltok::lbrace)
2920 return ParseMDTuple(N);
2921
2922 // !42
2923 return ParseMDNodeID(N);
2924}
2925
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002926namespace {
2927
2928/// Structure to represent an optional metadata field.
2929template <class FieldTy> struct MDFieldImpl {
2930 typedef MDFieldImpl ImplTy;
2931 FieldTy Val;
2932 bool Seen;
2933
2934 void assign(FieldTy Val) {
2935 Seen = true;
2936 this->Val = std::move(Val);
2937 }
2938
2939 explicit MDFieldImpl(FieldTy Default)
2940 : Val(std::move(Default)), Seen(false) {}
2941};
2942struct MDUnsignedField : public MDFieldImpl<uint64_t> {
2943 uint64_t Max;
2944
2945 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
2946 : ImplTy(Default), Max(Max) {}
2947};
2948struct DwarfTagField : public MDUnsignedField {
2949 DwarfTagField() : MDUnsignedField(0, ~0u >> 16) {}
2950};
2951struct MDField : public MDFieldImpl<Metadata *> {
2952 MDField() : ImplTy(nullptr) {}
2953};
2954struct MDStringField : public MDFieldImpl<std::string> {
2955 MDStringField() : ImplTy(std::string()) {}
2956};
2957struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
2958 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
2959};
2960
2961} // end namespace
2962
2963template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002964bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00002965 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002966 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2967 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002968
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00002969 auto &U = Lex.getAPSIntVal();
2970 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002971 return TokError("value for '" + Name + "' too large, limit is " +
2972 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00002973 Result.assign(U.getZExtValue());
2974 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002975 Lex.Lex();
2976 return false;
2977}
2978
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002979template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00002980bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
2981 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00002982 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00002983
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00002984 if (Lex.getKind() != lltok::DwarfTag)
2985 return TokError("expected DWARF tag");
2986
2987 unsigned Tag = dwarf::getTag(Lex.getStrVal());
2988 if (Tag == dwarf::DW_TAG_invalid)
2989 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00002990 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00002991
2992 Result.assign(Tag);
2993 Lex.Lex();
2994 return false;
2995}
2996
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002997template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002998bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002999 Metadata *MD;
3000 if (ParseMetadata(MD, nullptr))
3001 return true;
3002
3003 Result.assign(MD);
3004 return false;
3005}
3006
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003007template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003008bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3009 std::string S;
3010 if (ParseStringConstant(S))
3011 return true;
3012
3013 Result.assign(std::move(S));
3014 return false;
3015}
3016
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003017template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003018bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3019 SmallVector<Metadata *, 4> MDs;
3020 if (ParseMDNodeVector(MDs))
3021 return true;
3022
3023 Result.assign(std::move(MDs));
3024 return false;
3025}
3026
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003027template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003028bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003029 do {
3030 if (Lex.getKind() != lltok::LabelStr)
3031 return TokError("expected field label here");
3032
3033 if (parseField())
3034 return true;
3035 } while (EatIfPresent(lltok::comma));
3036
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003037 return false;
3038}
3039
3040template <class ParserTy>
3041bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3042 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3043 Lex.Lex();
3044
3045 if (ParseToken(lltok::lparen, "expected '(' here"))
3046 return true;
3047 if (Lex.getKind() != lltok::rparen)
3048 if (ParseMDFieldsImplBody(parseField))
3049 return true;
3050
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003051 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003052 return ParseToken(lltok::rparen, "expected ')' here");
3053}
3054
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003055template <class FieldTy>
3056bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3057 if (Result.Seen)
3058 return TokError("field '" + Name + "' cannot be specified more than once");
3059
3060 LocTy Loc = Lex.getLoc();
3061 Lex.Lex();
3062 return ParseMDField(Loc, Name, Result);
3063}
3064
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003065bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3066 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3067#define DISPATCH_TO_PARSER(CLASS) \
3068 if (Lex.getStrVal() == #CLASS) \
3069 return Parse##CLASS(N, IsDistinct);
3070
3071 DISPATCH_TO_PARSER(MDLocation);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003072 DISPATCH_TO_PARSER(GenericDebugNode);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003073#undef DISPATCH_TO_PARSER
3074
3075 return TokError("expected metadata type");
3076}
3077
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003078#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3079#define NOP_FIELD(NAME, TYPE, INIT)
3080#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3081 if (!NAME.Seen) \
3082 return Error(ClosingLoc, "missing required field '" #NAME "'");
3083#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003084 if (Lex.getStrVal() == #NAME) \
3085 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003086#define PARSE_MD_FIELDS() \
3087 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3088 do { \
3089 LocTy ClosingLoc; \
3090 if (ParseMDFieldsImpl([&]() -> bool { \
3091 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3092 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3093 }, ClosingLoc)) \
3094 return true; \
3095 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3096 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003097#define GET_OR_DISTINCT(CLASS, ARGS) \
3098 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003099
3100/// ParseMDLocationFields:
3101/// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3102bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003103#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003104 OPTIONAL(line, MDUnsignedField, (0, ~0u >> 8)); \
3105 OPTIONAL(column, MDUnsignedField, (0, ~0u >> 16)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003106 REQUIRED(scope, MDField, ); \
3107 OPTIONAL(inlinedAt, MDField, );
3108 PARSE_MD_FIELDS();
3109#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003110
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003111 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3112 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3113 return false;
3114}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003115
3116/// ParseGenericDebugNode:
3117/// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3118bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3119#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003120 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003121 OPTIONAL(header, MDStringField, ); \
3122 OPTIONAL(operands, MDFieldList, );
3123 PARSE_MD_FIELDS();
3124#undef VISIT_MD_FIELDS
3125
3126 Result = GET_OR_DISTINCT(GenericDebugNode,
3127 (Context, tag.Val, header.Val, operands.Val));
3128 return false;
3129}
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003130#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003131#undef NOP_FIELD
3132#undef REQUIRE_FIELD
3133#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003134
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003135/// ParseMetadataAsValue
3136/// ::= metadata i32 %local
3137/// ::= metadata i32 @global
3138/// ::= metadata i32 7
3139/// ::= metadata !0
3140/// ::= metadata !{...}
3141/// ::= metadata !"string"
3142bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3143 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003144 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003145 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003146 return true;
3147
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003148 V = MetadataAsValue::get(Context, MD);
3149 return false;
3150}
3151
3152/// ParseValueAsMetadata
3153/// ::= i32 %local
3154/// ::= i32 @global
3155/// ::= i32 7
3156bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
3157 Type *Ty;
3158 LocTy Loc;
3159 if (ParseType(Ty, "expected metadata operand", Loc))
3160 return true;
3161 if (Ty->isMetadataTy())
3162 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3163
3164 Value *V;
3165 if (ParseValue(Ty, V, PFS))
3166 return true;
3167
3168 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003169 return false;
3170}
3171
3172/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003173/// ::= i32 %local
3174/// ::= i32 @global
3175/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003176/// ::= !42
3177/// ::= !{...}
3178/// ::= !"string"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003179/// ::= !MDLocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003180bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003181 if (Lex.getKind() == lltok::MetadataVar) {
3182 MDNode *N;
3183 if (ParseSpecializedMDNode(N))
3184 return true;
3185 MD = N;
3186 return false;
3187 }
3188
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003189 // ValueAsMetadata:
3190 // <type> <value>
3191 if (Lex.getKind() != lltok::exclaim)
3192 return ParseValueAsMetadata(MD, PFS);
3193
3194 // '!'.
3195 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3196 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003197
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003198 // MDString:
3199 // ::= '!' STRINGCONSTANT
3200 if (Lex.getKind() == lltok::StringConstant) {
3201 MDString *S;
3202 if (ParseMDString(S))
3203 return true;
3204 MD = S;
3205 return false;
3206 }
3207
Dan Gohman8939ba332010-07-14 18:26:50 +00003208 // MDNode:
3209 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003210 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003211 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003212 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003213 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003214 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003215 return false;
3216}
3217
Victor Hernandez9d75c962010-01-11 22:31:58 +00003218
3219//===----------------------------------------------------------------------===//
3220// Function Parsing.
3221//===----------------------------------------------------------------------===//
3222
Chris Lattner229907c2011-07-18 04:54:35 +00003223bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003224 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003225 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003226 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003227
Chris Lattnerac161bf2009-01-02 07:01:27 +00003228 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003229 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003230 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3231 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003232 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003233 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003234 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3235 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003236 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003237 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003238 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003239 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003240 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003241 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3242 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003243 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003244 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003245 return false;
3246 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247 case ValID::t_GlobalName:
3248 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003249 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003250 case ValID::t_GlobalID:
3251 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003252 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003253 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003254 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003256 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003257 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003258 return false;
3259 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003260 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003261 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3262 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003263
Dan Gohman518cda42011-12-17 00:04:22 +00003264 // The lexer has no type info, so builds all half, float, and double FP
3265 // constants as double. Fix this here. Long double does not need this.
3266 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003268 if (Ty->isHalfTy())
3269 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3270 &Ignored);
3271 else if (Ty->isFloatTy())
3272 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3273 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003274 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003275 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003276
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003277 if (V->getType() != Ty)
3278 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003279 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003280
Chris Lattnerac161bf2009-01-02 07:01:27 +00003281 return false;
3282 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003283 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003284 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003285 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003286 return false;
3287 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003288 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003289 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003290 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003291 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003292 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003293 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003294 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003295 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003296 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003297 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003299 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003300 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003301 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003302 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003303 return false;
3304 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003305 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003306 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003307
Chris Lattnerac161bf2009-01-02 07:01:27 +00003308 V = ID.ConstantVal;
3309 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003310 case ValID::t_ConstantStruct:
3311 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003312 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003313 if (ST->getNumElements() != ID.UIntVal)
3314 return Error(ID.Loc,
3315 "initializer with struct type has wrong # elements");
3316 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3317 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003318
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003319 // Verify that the elements are compatible with the structtype.
3320 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3321 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3322 return Error(ID.Loc, "element " + Twine(i) +
3323 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003324
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003325 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3326 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003327 } else
3328 return Error(ID.Loc, "constant expression type mismatch");
3329 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003330 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003331 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003332}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003333
Chris Lattner229907c2011-07-18 04:54:35 +00003334bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003335 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003336 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003337 return ParseValID(ID, PFS) ||
3338 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003339}
3340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003341bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003342 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003343 return ParseType(Ty) ||
3344 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345}
3346
Chris Lattner3ed871f2009-10-27 19:13:16 +00003347bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3348 PerFunctionState &PFS) {
3349 Value *V;
3350 Loc = Lex.getLoc();
3351 if (ParseTypeAndValue(V, PFS)) return true;
3352 if (!isa<BasicBlock>(V))
3353 return Error(Loc, "expected a basic block");
3354 BB = cast<BasicBlock>(V);
3355 return false;
3356}
3357
3358
Chris Lattnerac161bf2009-01-02 07:01:27 +00003359/// FunctionHeader
3360/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003361/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003362/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003363bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3364 // Parse the linkage.
3365 LocTy LinkageLoc = Lex.getLoc();
3366 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003367
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003368 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003369 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003370 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003371 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003372 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003373 LocTy RetTypeLoc = Lex.getLoc();
3374 if (ParseOptionalLinkage(Linkage) ||
3375 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003376 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003377 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003378 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003379 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003380 return true;
3381
3382 // Verify that the linkage is ok.
3383 switch ((GlobalValue::LinkageTypes)Linkage) {
3384 case GlobalValue::ExternalLinkage:
3385 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003386 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003387 if (isDefine)
3388 return Error(LinkageLoc, "invalid linkage for function definition");
3389 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003390 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003391 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003392 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003393 case GlobalValue::LinkOnceAnyLinkage:
3394 case GlobalValue::LinkOnceODRLinkage:
3395 case GlobalValue::WeakAnyLinkage:
3396 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003397 if (!isDefine)
3398 return Error(LinkageLoc, "invalid linkage for function declaration");
3399 break;
3400 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003401 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003402 return Error(LinkageLoc, "invalid function linkage type");
3403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003404
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003405 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3406 return Error(LinkageLoc,
3407 "symbol with local linkage must have default visibility");
3408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003409 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003410 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003411
Chris Lattnerac161bf2009-01-02 07:01:27 +00003412 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003413
3414 std::string FunctionName;
3415 if (Lex.getKind() == lltok::GlobalVar) {
3416 FunctionName = Lex.getStrVal();
3417 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3418 unsigned NameID = Lex.getUIntVal();
3419
3420 if (NameID != NumberedVals.size())
3421 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003422 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003423 } else {
3424 return TokError("expected function name");
3425 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003426
Chris Lattner3822f632009-01-02 08:05:26 +00003427 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003428
Chris Lattner3822f632009-01-02 08:05:26 +00003429 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003430 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003431
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003432 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003433 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003434 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003435 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003436 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003437 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003438 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003439 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003440 bool UnnamedAddr;
3441 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003442 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003443 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003444 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003445
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003446 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003447 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3448 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003449 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003450 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003451 (EatIfPresent(lltok::kw_section) &&
3452 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00003453 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003454 ParseOptionalAlignment(Alignment) ||
3455 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003456 ParseStringConstant(GC)) ||
3457 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003458 ParseGlobalTypeAndValue(Prefix)) ||
3459 (EatIfPresent(lltok::kw_prologue) &&
3460 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003461 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003462
Michael Gottesman41748d72013-06-27 00:25:01 +00003463 if (FuncAttrs.contains(Attribute::Builtin))
3464 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003465
Chris Lattnerac161bf2009-01-02 07:01:27 +00003466 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003467 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003468 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003469 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003470 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003471
Chris Lattnerac161bf2009-01-02 07:01:27 +00003472 // Okay, if we got here, the function is syntactically valid. Convert types
3473 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003474 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003475 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003476
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003477 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003478 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3479 AttributeSet::ReturnIndex,
3480 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003481
Chris Lattnerac161bf2009-01-02 07:01:27 +00003482 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003483 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003484 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3485 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003486 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3487 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003488 }
3489
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003490 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003491 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3492 AttributeSet::FunctionIndex,
3493 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003494
Bill Wendlinge94d8432012-12-07 23:16:57 +00003495 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003496
Bill Wendling749a43d2012-12-30 13:50:49 +00003497 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003498 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3499
Chris Lattner229907c2011-07-18 04:54:35 +00003500 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003501 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003502 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003503
Craig Topper2617dcc2014-04-15 06:32:26 +00003504 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003505 if (!FunctionName.empty()) {
3506 // If this was a definition of a forward reference, remove the definition
3507 // from the forward reference table and fill in the forward ref.
3508 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3509 ForwardRefVals.find(FunctionName);
3510 if (FRVI != ForwardRefVals.end()) {
3511 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003512 if (!Fn)
3513 return Error(FRVI->second.second, "invalid forward reference to "
3514 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003515 if (Fn->getType() != PFT)
3516 return Error(FRVI->second.second, "invalid forward reference to "
3517 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003518
Chris Lattnerac161bf2009-01-02 07:01:27 +00003519 ForwardRefVals.erase(FRVI);
3520 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003521 // Reject redefinitions.
3522 return Error(NameLoc, "invalid redefinition of function '" +
3523 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003524 } else if (M->getNamedValue(FunctionName)) {
3525 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003526 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003527
Dan Gohman399d6ae2009-08-29 23:37:49 +00003528 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 // If this is a definition of a forward referenced function, make sure the
3530 // types agree.
3531 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3532 = ForwardRefValIDs.find(NumberedVals.size());
3533 if (I != ForwardRefValIDs.end()) {
3534 Fn = cast<Function>(I->second.first);
3535 if (Fn->getType() != PFT)
3536 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003537 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003538 ForwardRefValIDs.erase(I);
3539 }
3540 }
3541
Craig Topper2617dcc2014-04-15 06:32:26 +00003542 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003543 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3544 else // Move the forward-reference to the correct spot in the module.
3545 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3546
3547 if (FunctionName.empty())
3548 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003549
Chris Lattnerac161bf2009-01-02 07:01:27 +00003550 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3551 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003552 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003553 Fn->setCallingConv(CC);
3554 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003555 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003556 Fn->setAlignment(Alignment);
3557 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003558 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003559 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003560 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003561 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003562 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003563
Chris Lattnerac161bf2009-01-02 07:01:27 +00003564 // Add all of the arguments we parsed to the function.
3565 Function::arg_iterator ArgIt = Fn->arg_begin();
3566 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3567 // If the argument has a name, insert it into the argument symbol table.
3568 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003569
Chris Lattnerac161bf2009-01-02 07:01:27 +00003570 // Set the name, if it conflicted, it will be auto-renamed.
3571 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003572
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003573 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003574 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3575 ArgList[i].Name + "'");
3576 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003577
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003578 if (isDefine)
3579 return false;
3580
Robin Morisset039781e2014-08-29 21:53:01 +00003581 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003582 ValID ID;
3583 if (FunctionName.empty()) {
3584 ID.Kind = ValID::t_GlobalID;
3585 ID.UIntVal = NumberedVals.size() - 1;
3586 } else {
3587 ID.Kind = ValID::t_GlobalName;
3588 ID.StrVal = FunctionName;
3589 }
3590 auto Blocks = ForwardRefBlockAddresses.find(ID);
3591 if (Blocks != ForwardRefBlockAddresses.end())
3592 return Error(Blocks->first.Loc,
3593 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003594 return false;
3595}
3596
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003597bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3598 ValID ID;
3599 if (FunctionNumber == -1) {
3600 ID.Kind = ValID::t_GlobalName;
3601 ID.StrVal = F.getName();
3602 } else {
3603 ID.Kind = ValID::t_GlobalID;
3604 ID.UIntVal = FunctionNumber;
3605 }
3606
3607 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3608 if (Blocks == P.ForwardRefBlockAddresses.end())
3609 return false;
3610
3611 for (const auto &I : Blocks->second) {
3612 const ValID &BBID = I.first;
3613 GlobalValue *GV = I.second;
3614
3615 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3616 "Expected local id or name");
3617 BasicBlock *BB;
3618 if (BBID.Kind == ValID::t_LocalName)
3619 BB = GetBB(BBID.StrVal, BBID.Loc);
3620 else
3621 BB = GetBB(BBID.UIntVal, BBID.Loc);
3622 if (!BB)
3623 return P.Error(BBID.Loc, "referenced value is not a basic block");
3624
3625 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3626 GV->eraseFromParent();
3627 }
3628
3629 P.ForwardRefBlockAddresses.erase(Blocks);
3630 return false;
3631}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003632
3633/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003634/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003635bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003636 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003637 return TokError("expected '{' in function body");
3638 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003639
Chris Lattner3432c622009-10-28 03:39:23 +00003640 int FunctionNumber = -1;
3641 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003642
Chris Lattner3432c622009-10-28 03:39:23 +00003643 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003644
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003645 // Resolve block addresses and allow basic blocks to be forward-declared
3646 // within this function.
3647 if (PFS.resolveForwardRefBlockAddresses())
3648 return true;
3649 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3650
Chris Lattnerbbddd962010-01-09 19:20:07 +00003651 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003652 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003653 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003654
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003655 while (Lex.getKind() != lltok::rbrace &&
3656 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003657 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003658
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003659 while (Lex.getKind() != lltok::rbrace)
3660 if (ParseUseListOrder(&PFS))
3661 return true;
3662
Chris Lattnerac161bf2009-01-02 07:01:27 +00003663 // Eat the }.
3664 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003665
Chris Lattnerac161bf2009-01-02 07:01:27 +00003666 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003667 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003668}
3669
3670/// ParseBasicBlock
3671/// ::= LabelStr? Instruction*
3672bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3673 // If this basic block starts out with a name, remember it.
3674 std::string Name;
3675 LocTy NameLoc = Lex.getLoc();
3676 if (Lex.getKind() == lltok::LabelStr) {
3677 Name = Lex.getStrVal();
3678 Lex.Lex();
3679 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003680
Chris Lattnerac161bf2009-01-02 07:01:27 +00003681 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003682 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003683
Chris Lattnerac161bf2009-01-02 07:01:27 +00003684 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003685
Chris Lattnerac161bf2009-01-02 07:01:27 +00003686 // Parse the instructions in this block until we get a terminator.
3687 Instruction *Inst;
3688 do {
3689 // This instruction may have three possibilities for a name: a) none
3690 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3691 LocTy NameLoc = Lex.getLoc();
3692 int NameID = -1;
3693 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003694
Chris Lattnerac161bf2009-01-02 07:01:27 +00003695 if (Lex.getKind() == lltok::LocalVarID) {
3696 NameID = Lex.getUIntVal();
3697 Lex.Lex();
3698 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3699 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003700 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003701 NameStr = Lex.getStrVal();
3702 Lex.Lex();
3703 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3704 return true;
3705 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003706
Chris Lattner77b89dc2009-12-30 05:23:43 +00003707 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003708 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003709 case InstError: return true;
3710 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003711 BB->getInstList().push_back(Inst);
3712
Chris Lattner77b89dc2009-12-30 05:23:43 +00003713 // With a normal result, we check to see if the instruction is followed by
3714 // a comma and metadata.
3715 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003716 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003717 return true;
3718 break;
3719 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003720 BB->getInstList().push_back(Inst);
3721
Chris Lattner77b89dc2009-12-30 05:23:43 +00003722 // If the instruction parser ate an extra comma at the end of it, it
3723 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003724 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003725 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003726 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003727 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003728
Chris Lattnerac161bf2009-01-02 07:01:27 +00003729 // Set the name on the instruction.
3730 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3731 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Chris Lattnerac161bf2009-01-02 07:01:27 +00003733 return false;
3734}
3735
3736//===----------------------------------------------------------------------===//
3737// Instruction Parsing.
3738//===----------------------------------------------------------------------===//
3739
3740/// ParseInstruction - Parse one of the many different instructions.
3741///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003742int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3743 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003744 lltok::Kind Token = Lex.getKind();
3745 if (Token == lltok::Eof)
3746 return TokError("found end of file when expecting more instructions");
3747 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003748 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003749 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003750
Chris Lattnerac161bf2009-01-02 07:01:27 +00003751 switch (Token) {
3752 default: return Error(Loc, "expected instruction opcode");
3753 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003754 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003755 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3756 case lltok::kw_br: return ParseBr(Inst, PFS);
3757 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003758 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003760 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003761 // Binary Operators.
3762 case lltok::kw_add:
3763 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003764 case lltok::kw_mul:
3765 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003766 bool NUW = EatIfPresent(lltok::kw_nuw);
3767 bool NSW = EatIfPresent(lltok::kw_nsw);
3768 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003769
Chris Lattnera676c0f2011-02-07 16:40:21 +00003770 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003771
Chris Lattnera676c0f2011-02-07 16:40:21 +00003772 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3773 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3774 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003775 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003776 case lltok::kw_fadd:
3777 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003778 case lltok::kw_fmul:
3779 case lltok::kw_fdiv:
3780 case lltok::kw_frem: {
3781 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3782 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3783 if (Res != 0)
3784 return Res;
3785 if (FMF.any())
3786 Inst->setFastMathFlags(FMF);
3787 return 0;
3788 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003789
Chris Lattner35315d02011-02-06 21:44:57 +00003790 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003791 case lltok::kw_udiv:
3792 case lltok::kw_lshr:
3793 case lltok::kw_ashr: {
3794 bool Exact = EatIfPresent(lltok::kw_exact);
3795
3796 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3797 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3798 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003799 }
3800
Chris Lattnerac161bf2009-01-02 07:01:27 +00003801 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003802 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003803 case lltok::kw_and:
3804 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003805 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003806 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003807 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003808 // Casts.
3809 case lltok::kw_trunc:
3810 case lltok::kw_zext:
3811 case lltok::kw_sext:
3812 case lltok::kw_fptrunc:
3813 case lltok::kw_fpext:
3814 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003815 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003816 case lltok::kw_uitofp:
3817 case lltok::kw_sitofp:
3818 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003819 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003820 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003821 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003822 // Other.
3823 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003824 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003825 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3826 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3827 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3828 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003829 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003830 // Call.
3831 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3832 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3833 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003834 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003835 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003836 case lltok::kw_load: return ParseLoad(Inst, PFS);
3837 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003838 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3839 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003840 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003841 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3842 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3843 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3844 }
3845}
3846
3847/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3848bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003849 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003850 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003851 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003852 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3853 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3854 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3855 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3856 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3857 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3858 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3859 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3860 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3861 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3862 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3863 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3864 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3865 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3866 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3867 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3868 }
3869 } else {
3870 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003871 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003872 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3873 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3874 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3875 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3876 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3877 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3878 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3879 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3880 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3881 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3882 }
3883 }
3884 Lex.Lex();
3885 return false;
3886}
3887
3888//===----------------------------------------------------------------------===//
3889// Terminator Instructions.
3890//===----------------------------------------------------------------------===//
3891
3892/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003893/// ::= 'ret' void (',' !dbg, !1)*
3894/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003895bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003896 PerFunctionState &PFS) {
3897 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003898 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003899 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003900
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003901 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003902
Chris Lattnerfdd87902009-10-05 05:54:46 +00003903 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003904 if (!ResType->isVoidTy())
3905 return Error(TypeLoc, "value doesn't match function result type '" +
3906 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003907
Owen Anderson55f1c092009-08-13 21:58:54 +00003908 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003909 return false;
3910 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003911
Chris Lattnerac161bf2009-01-02 07:01:27 +00003912 Value *RV;
3913 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003914
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003915 if (ResType != RV->getType())
3916 return Error(TypeLoc, "value doesn't match function result type '" +
3917 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003918
Owen Anderson55f1c092009-08-13 21:58:54 +00003919 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003920 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921}
3922
3923
3924/// ParseBr
3925/// ::= 'br' TypeAndValue
3926/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3927bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3928 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003929 Value *Op0;
3930 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003932
Chris Lattnerac161bf2009-01-02 07:01:27 +00003933 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3934 Inst = BranchInst::Create(BB);
3935 return false;
3936 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003937
Owen Anderson55f1c092009-08-13 21:58:54 +00003938 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003939 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003940
Chris Lattnerac161bf2009-01-02 07:01:27 +00003941 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003942 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003943 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003944 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003945 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003946
Chris Lattner3ed871f2009-10-27 19:13:16 +00003947 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003948 return false;
3949}
3950
3951/// ParseSwitch
3952/// Instruction
3953/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3954/// JumpTable
3955/// ::= (TypeAndValue ',' TypeAndValue)*
3956bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3957 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003958 Value *Cond;
3959 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003960 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3961 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003962 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003963 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3964 return true;
3965
Duncan Sands19d0b472010-02-16 11:11:14 +00003966 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003967 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003968
Chris Lattnerac161bf2009-01-02 07:01:27 +00003969 // Parse the jump table pairs.
3970 SmallPtrSet<Value*, 32> SeenCases;
3971 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3972 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003973 Value *Constant;
3974 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003975
Chris Lattnerac161bf2009-01-02 07:01:27 +00003976 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3977 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003978 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003979 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003980
David Blaikie70573dc2014-11-19 07:49:26 +00003981 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003982 return Error(CondLoc, "duplicate case value in switch");
3983 if (!isa<ConstantInt>(Constant))
3984 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003985
Chris Lattner3ed871f2009-10-27 19:13:16 +00003986 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003988
Chris Lattnerac161bf2009-01-02 07:01:27 +00003989 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003990
Chris Lattner3ed871f2009-10-27 19:13:16 +00003991 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003992 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3993 SI->addCase(Table[i].first, Table[i].second);
3994 Inst = SI;
3995 return false;
3996}
3997
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003998/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003999/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004000/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4001bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004002 LocTy AddrLoc;
4003 Value *Address;
4004 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004005 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4006 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004007 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004008
Duncan Sands19d0b472010-02-16 11:11:14 +00004009 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004010 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004011
Chris Lattner3ed871f2009-10-27 19:13:16 +00004012 // Parse the destination list.
4013 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004014
Chris Lattner3ed871f2009-10-27 19:13:16 +00004015 if (Lex.getKind() != lltok::rsquare) {
4016 BasicBlock *DestBB;
4017 if (ParseTypeAndBasicBlock(DestBB, PFS))
4018 return true;
4019 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004020
Chris Lattner3ed871f2009-10-27 19:13:16 +00004021 while (EatIfPresent(lltok::comma)) {
4022 if (ParseTypeAndBasicBlock(DestBB, PFS))
4023 return true;
4024 DestList.push_back(DestBB);
4025 }
4026 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004027
Chris Lattner3ed871f2009-10-27 19:13:16 +00004028 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4029 return true;
4030
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004031 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004032 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4033 IBI->addDestination(DestList[i]);
4034 Inst = IBI;
4035 return false;
4036}
4037
4038
Chris Lattnerac161bf2009-01-02 07:01:27 +00004039/// ParseInvoke
4040/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4041/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4042bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4043 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004044 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004045 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004046 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004047 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004048 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004049 LocTy RetTypeLoc;
4050 ValID CalleeID;
4051 SmallVector<ParamInfo, 16> ArgList;
4052
Chris Lattner3ed871f2009-10-27 19:13:16 +00004053 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004054 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004055 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004056 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004057 ParseValID(CalleeID) ||
4058 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004059 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4060 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004061 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004062 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004063 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004064 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004065 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004066
Chris Lattnerac161bf2009-01-02 07:01:27 +00004067 // If RetType is a non-function pointer type, then this is the short syntax
4068 // for the call, which means that RetType is just the return type. Infer the
4069 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004070 PointerType *PFTy = nullptr;
4071 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004072 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4073 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4074 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004075 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004076 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4077 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004078
Chris Lattnerac161bf2009-01-02 07:01:27 +00004079 if (!FunctionType::isValidReturnType(RetType))
4080 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004081
Owen Anderson4056ca92009-07-29 22:17:13 +00004082 Ty = FunctionType::get(RetType, ParamTypes, false);
4083 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004084 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004085
Chris Lattnerac161bf2009-01-02 07:01:27 +00004086 // Look up the callee.
4087 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004088 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004089
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004090 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004091 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004092 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004093 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4094 AttributeSet::ReturnIndex,
4095 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004096
Chris Lattnerac161bf2009-01-02 07:01:27 +00004097 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004098
Chris Lattnerac161bf2009-01-02 07:01:27 +00004099 // Loop through FunctionType's arguments and ensure they are specified
4100 // correctly. Also, gather any parameter attributes.
4101 FunctionType::param_iterator I = Ty->param_begin();
4102 FunctionType::param_iterator E = Ty->param_end();
4103 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004104 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004105 if (I != E) {
4106 ExpectedTy = *I++;
4107 } else if (!Ty->isVarArg()) {
4108 return Error(ArgList[i].Loc, "too many arguments specified");
4109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004110
Chris Lattnerac161bf2009-01-02 07:01:27 +00004111 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4112 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004113 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004114 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004115 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4116 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004117 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4118 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004119 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004120
Chris Lattnerac161bf2009-01-02 07:01:27 +00004121 if (I != E)
4122 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004123
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004124 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004125 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4126 AttributeSet::FunctionIndex,
4127 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004129 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004130 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004131
Jay Foad5bd375a2011-07-15 08:37:34 +00004132 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004133 II->setCallingConv(CC);
4134 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004135 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004136 Inst = II;
4137 return false;
4138}
4139
Bill Wendlingf891bf82011-07-31 06:30:59 +00004140/// ParseResume
4141/// ::= 'resume' TypeAndValue
4142bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4143 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004144 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4145 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004146
Bill Wendlingf891bf82011-07-31 06:30:59 +00004147 ResumeInst *RI = ResumeInst::Create(Exn);
4148 Inst = RI;
4149 return false;
4150}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004151
4152//===----------------------------------------------------------------------===//
4153// Binary Operators.
4154//===----------------------------------------------------------------------===//
4155
4156/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004157/// ::= ArithmeticOps TypeAndValue ',' Value
4158///
4159/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4160/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004161bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004162 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004163 LocTy Loc; Value *LHS, *RHS;
4164 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4165 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4166 ParseValue(LHS->getType(), RHS, PFS))
4167 return true;
4168
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004169 bool Valid;
4170 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004171 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004172 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004173 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4174 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004175 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004176 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4177 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004178 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004179
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004180 if (!Valid)
4181 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004182
Chris Lattnerac161bf2009-01-02 07:01:27 +00004183 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4184 return false;
4185}
4186
4187/// ParseLogical
4188/// ::= ArithmeticOps TypeAndValue ',' Value {
4189bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4190 unsigned Opc) {
4191 LocTy Loc; Value *LHS, *RHS;
4192 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4193 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4194 ParseValue(LHS->getType(), RHS, PFS))
4195 return true;
4196
Duncan Sands9dff9be2010-02-15 16:12:20 +00004197 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004198 return Error(Loc,"instruction requires integer or integer vector operands");
4199
4200 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4201 return false;
4202}
4203
4204
4205/// ParseCompare
4206/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4207/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004208bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4209 unsigned Opc) {
4210 // Parse the integer/fp comparison predicate.
4211 LocTy Loc;
4212 unsigned Pred;
4213 Value *LHS, *RHS;
4214 if (ParseCmpPredicate(Pred, Opc) ||
4215 ParseTypeAndValue(LHS, Loc, PFS) ||
4216 ParseToken(lltok::comma, "expected ',' after compare value") ||
4217 ParseValue(LHS->getType(), RHS, PFS))
4218 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004219
Chris Lattnerac161bf2009-01-02 07:01:27 +00004220 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004221 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004223 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004224 } else {
4225 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004226 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004227 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004228 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004229 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004230 }
4231 return false;
4232}
4233
4234//===----------------------------------------------------------------------===//
4235// Other Instructions.
4236//===----------------------------------------------------------------------===//
4237
4238
4239/// ParseCast
4240/// ::= CastOpc TypeAndValue 'to' Type
4241bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4242 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004243 LocTy Loc;
4244 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004245 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 if (ParseTypeAndValue(Op, Loc, PFS) ||
4247 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4248 ParseType(DestTy))
4249 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004250
Chris Lattner89d856e2009-03-01 00:53:13 +00004251 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4252 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004253 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004254 getTypeString(Op->getType()) + "' to '" +
4255 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004256 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4258 return false;
4259}
4260
4261/// ParseSelect
4262/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4263bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4264 LocTy Loc;
4265 Value *Op0, *Op1, *Op2;
4266 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4267 ParseToken(lltok::comma, "expected ',' after select condition") ||
4268 ParseTypeAndValue(Op1, PFS) ||
4269 ParseToken(lltok::comma, "expected ',' after select value") ||
4270 ParseTypeAndValue(Op2, PFS))
4271 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004272
Chris Lattnerac161bf2009-01-02 07:01:27 +00004273 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4274 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004275
Chris Lattnerac161bf2009-01-02 07:01:27 +00004276 Inst = SelectInst::Create(Op0, Op1, Op2);
4277 return false;
4278}
4279
Chris Lattnerb55ab542009-01-05 08:18:44 +00004280/// ParseVA_Arg
4281/// ::= 'va_arg' TypeAndValue ',' Type
4282bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004283 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004284 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004285 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004286 if (ParseTypeAndValue(Op, PFS) ||
4287 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004288 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004289 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004290
Chris Lattnerb55ab542009-01-05 08:18:44 +00004291 if (!EltTy->isFirstClassType())
4292 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004293
4294 Inst = new VAArgInst(Op, EltTy);
4295 return false;
4296}
4297
4298/// ParseExtractElement
4299/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4300bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4301 LocTy Loc;
4302 Value *Op0, *Op1;
4303 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4304 ParseToken(lltok::comma, "expected ',' after extract value") ||
4305 ParseTypeAndValue(Op1, PFS))
4306 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004307
Chris Lattnerac161bf2009-01-02 07:01:27 +00004308 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4309 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004310
Eric Christopherc9742252009-07-25 02:28:41 +00004311 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 return false;
4313}
4314
4315/// ParseInsertElement
4316/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4317bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4318 LocTy Loc;
4319 Value *Op0, *Op1, *Op2;
4320 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4321 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4322 ParseTypeAndValue(Op1, PFS) ||
4323 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4324 ParseTypeAndValue(Op2, PFS))
4325 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004326
Chris Lattnerac161bf2009-01-02 07:01:27 +00004327 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004328 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004329
Chris Lattnerac161bf2009-01-02 07:01:27 +00004330 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4331 return false;
4332}
4333
4334/// ParseShuffleVector
4335/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4336bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4337 LocTy Loc;
4338 Value *Op0, *Op1, *Op2;
4339 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4340 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4341 ParseTypeAndValue(Op1, PFS) ||
4342 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4343 ParseTypeAndValue(Op2, PFS))
4344 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004345
Chris Lattnerac161bf2009-01-02 07:01:27 +00004346 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004347 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004348
Chris Lattnerac161bf2009-01-02 07:01:27 +00004349 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4350 return false;
4351}
4352
4353/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004354/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004355int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004356 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004358
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004359 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004360 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4361 ParseValue(Ty, Op0, PFS) ||
4362 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004363 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004364 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4365 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004366
Chris Lattnerf4f03422009-12-30 05:27:33 +00004367 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004368 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4369 while (1) {
4370 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004371
Chris Lattner3822f632009-01-02 08:05:26 +00004372 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004373 break;
4374
Chris Lattnerf4f03422009-12-30 05:27:33 +00004375 if (Lex.getKind() == lltok::MetadataVar) {
4376 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004377 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004378 }
Devang Patel8f842d32009-10-16 18:45:49 +00004379
Chris Lattner3822f632009-01-02 08:05:26 +00004380 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004381 ParseValue(Ty, Op0, PFS) ||
4382 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004383 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004384 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4385 return true;
4386 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004387
Chris Lattnerac161bf2009-01-02 07:01:27 +00004388 if (!Ty->isFirstClassType())
4389 return Error(TypeLoc, "phi node must have first class type");
4390
Jay Foad52131342011-03-30 11:28:46 +00004391 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004392 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4393 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4394 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004395 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396}
4397
Bill Wendlingfae14752011-08-12 20:24:12 +00004398/// ParseLandingPad
4399/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4400/// Clause
4401/// ::= 'catch' TypeAndValue
4402/// ::= 'filter'
4403/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4404bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004405 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004406 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004407
4408 if (ParseType(Ty, TyLoc) ||
4409 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4410 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4411 return true;
4412
4413 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4414 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4415
4416 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4417 LandingPadInst::ClauseType CT;
4418 if (EatIfPresent(lltok::kw_catch))
4419 CT = LandingPadInst::Catch;
4420 else if (EatIfPresent(lltok::kw_filter))
4421 CT = LandingPadInst::Filter;
4422 else
4423 return TokError("expected 'catch' or 'filter' clause type");
4424
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004425 Value *V;
4426 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004427 if (ParseTypeAndValue(V, VLoc, PFS)) {
4428 delete LP;
4429 return true;
4430 }
4431
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004432 // A 'catch' type expects a non-array constant. A filter clause expects an
4433 // array constant.
4434 if (CT == LandingPadInst::Catch) {
4435 if (isa<ArrayType>(V->getType()))
4436 Error(VLoc, "'catch' clause has an invalid type");
4437 } else {
4438 if (!isa<ArrayType>(V->getType()))
4439 Error(VLoc, "'filter' clause has an invalid type");
4440 }
4441
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004442 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004443 }
4444
4445 Inst = LP;
4446 return false;
4447}
4448
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004450/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4451/// ParameterList OptionalAttrs
4452/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4453/// ParameterList OptionalAttrs
4454/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004455/// ParameterList OptionalAttrs
4456bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004457 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004458 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004459 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004460 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004461 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004462 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 LocTy RetTypeLoc;
4464 ValID CalleeID;
4465 SmallVector<ParamInfo, 16> ArgList;
4466 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004467
Reid Kleckner5772b772014-04-24 20:14:34 +00004468 if ((TCK != CallInst::TCK_None &&
4469 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004470 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004471 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004472 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004473 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004474 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4475 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004476 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004477 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004478 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004479
Chris Lattnerac161bf2009-01-02 07:01:27 +00004480 // If RetType is a non-function pointer type, then this is the short syntax
4481 // for the call, which means that RetType is just the return type. Infer the
4482 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004483 PointerType *PFTy = nullptr;
4484 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004485 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4486 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4487 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004488 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004489 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4490 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004491
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 if (!FunctionType::isValidReturnType(RetType))
4493 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004494
Owen Anderson4056ca92009-07-29 22:17:13 +00004495 Ty = FunctionType::get(RetType, ParamTypes, false);
4496 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004498
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 // Look up the callee.
4500 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004501 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004502
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004503 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004504 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004505 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004506 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4507 AttributeSet::ReturnIndex,
4508 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004509
Chris Lattnerac161bf2009-01-02 07:01:27 +00004510 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004511
Chris Lattnerac161bf2009-01-02 07:01:27 +00004512 // Loop through FunctionType's arguments and ensure they are specified
4513 // correctly. Also, gather any parameter attributes.
4514 FunctionType::param_iterator I = Ty->param_begin();
4515 FunctionType::param_iterator E = Ty->param_end();
4516 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004517 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 if (I != E) {
4519 ExpectedTy = *I++;
4520 } else if (!Ty->isVarArg()) {
4521 return Error(ArgList[i].Loc, "too many arguments specified");
4522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004523
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4525 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004526 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004527 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004528 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4529 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004530 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4531 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004532 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004533
Chris Lattnerac161bf2009-01-02 07:01:27 +00004534 if (I != E)
4535 return Error(CallLoc, "not enough parameters specified for call");
4536
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004537 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004538 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4539 AttributeSet::FunctionIndex,
4540 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004542 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004543 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004544
Jay Foad5bd375a2011-07-15 08:37:34 +00004545 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004546 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004547 CI->setCallingConv(CC);
4548 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004549 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 Inst = CI;
4551 return false;
4552}
4553
4554//===----------------------------------------------------------------------===//
4555// Memory Instructions.
4556//===----------------------------------------------------------------------===//
4557
4558/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004559/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004560int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004561 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004562 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004564 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004565
4566 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4567
Chris Lattner3822f632009-01-02 08:05:26 +00004568 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569
Chris Lattnerb2f39502009-12-30 05:44:30 +00004570 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004571 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004572 if (Lex.getKind() == lltok::kw_align) {
4573 if (ParseOptionalAlignment(Alignment)) return true;
4574 } else if (Lex.getKind() == lltok::MetadataVar) {
4575 AteExtraComma = true;
4576 } else {
4577 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4578 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4579 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004580 }
4581 }
4582
Dan Gohman2140a742010-05-28 01:14:11 +00004583 if (Size && !Size->getType()->isIntegerTy())
4584 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585
Reid Kleckner436c42e2014-01-17 23:58:17 +00004586 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4587 AI->setUsedWithInAlloca(IsInAlloca);
4588 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004589 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590}
4591
4592/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004593/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004594/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004595/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004596int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004598 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004599 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004600 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004601 AtomicOrdering Ordering = NotAtomic;
4602 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004603
4604 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004605 isAtomic = true;
4606 Lex.Lex();
4607 }
4608
Chris Lattnerbc639292011-11-27 06:56:53 +00004609 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004610 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004611 isVolatile = true;
4612 Lex.Lex();
4613 }
4614
Chris Lattnerb2f39502009-12-30 05:44:30 +00004615 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004616 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004617 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4618 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004619
Duncan Sands19d0b472010-02-16 11:11:14 +00004620 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004621 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4622 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004623 if (isAtomic && !Alignment)
4624 return Error(Loc, "atomic load must have explicit non-zero alignment");
4625 if (Ordering == Release || Ordering == AcquireRelease)
4626 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004627
Eli Friedman59b66882011-08-09 23:02:53 +00004628 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004629 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630}
4631
4632/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004633
4634/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4635/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004636/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004637int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004638 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004639 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004640 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004641 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004642 AtomicOrdering Ordering = NotAtomic;
4643 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004644
4645 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004646 isAtomic = true;
4647 Lex.Lex();
4648 }
4649
Chris Lattnerbc639292011-11-27 06:56:53 +00004650 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004651 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004652 isVolatile = true;
4653 Lex.Lex();
4654 }
4655
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 if (ParseTypeAndValue(Val, Loc, PFS) ||
4657 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004658 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004659 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004660 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004662
Duncan Sands19d0b472010-02-16 11:11:14 +00004663 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 return Error(PtrLoc, "store operand must be a pointer");
4665 if (!Val->getType()->isFirstClassType())
4666 return Error(Loc, "store operand must be a first class value");
4667 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4668 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004669 if (isAtomic && !Alignment)
4670 return Error(Loc, "atomic store must have explicit non-zero alignment");
4671 if (Ordering == Acquire || Ordering == AcquireRelease)
4672 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004673
Eli Friedman59b66882011-08-09 23:02:53 +00004674 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004675 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004676}
4677
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004678/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004679/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4680/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004681int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004682 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4683 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004684 AtomicOrdering SuccessOrdering = NotAtomic;
4685 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004686 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004687 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004688 bool isWeak = false;
4689
4690 if (EatIfPresent(lltok::kw_weak))
4691 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004692
4693 if (EatIfPresent(lltok::kw_volatile))
4694 isVolatile = true;
4695
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004696 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4697 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4698 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4699 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4700 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004701 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4702 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004703 return true;
4704
Tim Northovere94a5182014-03-11 10:48:52 +00004705 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004706 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004707 if (SuccessOrdering < FailureOrdering)
4708 return TokError("cmpxchg must be at least as ordered on success as failure");
4709 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4710 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004711 if (!Ptr->getType()->isPointerTy())
4712 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4713 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4714 return Error(CmpLoc, "compare value and pointer type do not match");
4715 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4716 return Error(NewLoc, "new value and pointer type do not match");
4717 if (!New->getType()->isIntegerTy())
4718 return Error(NewLoc, "cmpxchg operand must be an integer");
4719 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4720 if (Size < 8 || (Size & (Size - 1)))
4721 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4722 " integer");
4723
Tim Northover420a2162014-06-13 14:24:07 +00004724 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4725 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004726 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004727 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004728 Inst = CXI;
4729 return AteExtraComma ? InstExtraComma : InstNormal;
4730}
4731
4732/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004733/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4734/// 'singlethread'? AtomicOrdering
4735int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004736 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4737 bool AteExtraComma = false;
4738 AtomicOrdering Ordering = NotAtomic;
4739 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004740 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004741 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004742
4743 if (EatIfPresent(lltok::kw_volatile))
4744 isVolatile = true;
4745
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004746 switch (Lex.getKind()) {
4747 default: return TokError("expected binary operation in atomicrmw");
4748 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4749 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4750 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4751 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4752 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4753 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4754 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4755 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4756 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4757 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4758 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4759 }
4760 Lex.Lex(); // Eat the operation.
4761
4762 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4763 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4764 ParseTypeAndValue(Val, ValLoc, PFS) ||
4765 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4766 return true;
4767
4768 if (Ordering == Unordered)
4769 return TokError("atomicrmw cannot be unordered");
4770 if (!Ptr->getType()->isPointerTy())
4771 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4772 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4773 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4774 if (!Val->getType()->isIntegerTy())
4775 return Error(ValLoc, "atomicrmw operand must be an integer");
4776 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4777 if (Size < 8 || (Size & (Size - 1)))
4778 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4779 " integer");
4780
4781 AtomicRMWInst *RMWI =
4782 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4783 RMWI->setVolatile(isVolatile);
4784 Inst = RMWI;
4785 return AteExtraComma ? InstExtraComma : InstNormal;
4786}
4787
Eli Friedmanfee02c62011-07-25 23:16:38 +00004788/// ParseFence
4789/// ::= 'fence' 'singlethread'? AtomicOrdering
4790int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4791 AtomicOrdering Ordering = NotAtomic;
4792 SynchronizationScope Scope = CrossThread;
4793 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4794 return true;
4795
4796 if (Ordering == Unordered)
4797 return TokError("fence cannot be unordered");
4798 if (Ordering == Monotonic)
4799 return TokError("fence cannot be monotonic");
4800
4801 Inst = new FenceInst(Context, Ordering, Scope);
4802 return InstNormal;
4803}
4804
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004806/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004807int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004808 Value *Ptr = nullptr;
4809 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004810 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004811
Dan Gohman16cbbe42009-07-29 15:58:36 +00004812 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004813
Chris Lattner3822f632009-01-02 08:05:26 +00004814 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004815
Eli Benderskyd9806682013-04-22 17:03:42 +00004816 Type *BaseType = Ptr->getType();
4817 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4818 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004819 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004820
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004822 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004823 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004824 if (Lex.getKind() == lltok::MetadataVar) {
4825 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004826 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004827 }
Chris Lattner3822f632009-01-02 08:05:26 +00004828 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004829 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004831 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4832 return Error(EltLoc, "getelementptr index type missmatch");
4833 if (Val->getType()->isVectorTy()) {
4834 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4835 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4836 if (ValNumEl != PtrNumEl)
4837 return Error(EltLoc,
4838 "getelementptr vector index has a wrong number of elements");
4839 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 Indices.push_back(Val);
4841 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004842
Eli Benderskyd9806682013-04-22 17:03:42 +00004843 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4844 return Error(Loc, "base element of getelementptr must be sized");
4845
4846 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004847 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004848 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004849 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004850 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004851 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004852}
4853
4854/// ParseExtractValue
4855/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004856int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004857 Value *Val; LocTy Loc;
4858 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004859 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004861 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004862 return true;
4863
Chris Lattner392be582010-02-12 20:49:41 +00004864 if (!Val->getType()->isAggregateType())
4865 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004866
Jay Foad57aa6362011-07-13 10:26:04 +00004867 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004868 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004869 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004870 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004871}
4872
4873/// ParseInsertValue
4874/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004875int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004876 Value *Val0, *Val1; LocTy Loc0, Loc1;
4877 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004878 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4880 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4881 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004882 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004883 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004884
Chris Lattner392be582010-02-12 20:49:41 +00004885 if (!Val0->getType()->isAggregateType())
4886 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004887
Jay Foad57aa6362011-07-13 10:26:04 +00004888 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004889 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004890 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004891 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004892}
Nick Lewycky49f89192009-04-04 07:22:01 +00004893
4894//===----------------------------------------------------------------------===//
4895// Embedded metadata.
4896//===----------------------------------------------------------------------===//
4897
4898/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004899/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004900/// Element
4901/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004902bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00004903 if (ParseToken(lltok::lbrace, "expected '{' here"))
4904 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004905
Dan Gohman1e0213a2010-07-13 19:33:27 +00004906 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004907 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004908 return false;
4909
Nick Lewycky49f89192009-04-04 07:22:01 +00004910 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004911 // Null is a special case since it is typeless.
4912 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004913 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004914 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004915 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004916
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004917 Metadata *MD;
4918 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004919 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004920 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00004921 } while (EatIfPresent(lltok::comma));
4922
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004923 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004924}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004925
4926//===----------------------------------------------------------------------===//
4927// Use-list order directives.
4928//===----------------------------------------------------------------------===//
4929bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4930 SMLoc Loc) {
4931 if (V->use_empty())
4932 return Error(Loc, "value has no uses");
4933
4934 unsigned NumUses = 0;
4935 SmallDenseMap<const Use *, unsigned, 16> Order;
4936 for (const Use &U : V->uses()) {
4937 if (++NumUses > Indexes.size())
4938 break;
4939 Order[&U] = Indexes[NumUses - 1];
4940 }
4941 if (NumUses < 2)
4942 return Error(Loc, "value only has one use");
4943 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4944 return Error(Loc, "wrong number of indexes, expected " +
4945 Twine(std::distance(V->use_begin(), V->use_end())));
4946
4947 V->sortUseList([&](const Use &L, const Use &R) {
4948 return Order.lookup(&L) < Order.lookup(&R);
4949 });
4950 return false;
4951}
4952
4953/// ParseUseListOrderIndexes
4954/// ::= '{' uint32 (',' uint32)+ '}'
4955bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4956 SMLoc Loc = Lex.getLoc();
4957 if (ParseToken(lltok::lbrace, "expected '{' here"))
4958 return true;
4959 if (Lex.getKind() == lltok::rbrace)
4960 return Lex.Error("expected non-empty list of uselistorder indexes");
4961
4962 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4963 // indexes should be distinct numbers in the range [0, size-1], and should
4964 // not be in order.
4965 unsigned Offset = 0;
4966 unsigned Max = 0;
4967 bool IsOrdered = true;
4968 assert(Indexes.empty() && "Expected empty order vector");
4969 do {
4970 unsigned Index;
4971 if (ParseUInt32(Index))
4972 return true;
4973
4974 // Update consistency checks.
4975 Offset += Index - Indexes.size();
4976 Max = std::max(Max, Index);
4977 IsOrdered &= Index == Indexes.size();
4978
4979 Indexes.push_back(Index);
4980 } while (EatIfPresent(lltok::comma));
4981
4982 if (ParseToken(lltok::rbrace, "expected '}' here"))
4983 return true;
4984
4985 if (Indexes.size() < 2)
4986 return Error(Loc, "expected >= 2 uselistorder indexes");
4987 if (Offset != 0 || Max >= Indexes.size())
4988 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4989 if (IsOrdered)
4990 return Error(Loc, "expected uselistorder indexes to change the order");
4991
4992 return false;
4993}
4994
4995/// ParseUseListOrder
4996/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4997bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4998 SMLoc Loc = Lex.getLoc();
4999 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5000 return true;
5001
5002 Value *V;
5003 SmallVector<unsigned, 16> Indexes;
5004 if (ParseTypeAndValue(V, PFS) ||
5005 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5006 ParseUseListOrderIndexes(Indexes))
5007 return true;
5008
5009 return sortUseListOrder(V, Indexes, Loc);
5010}
5011
5012/// ParseUseListOrderBB
5013/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5014bool LLParser::ParseUseListOrderBB() {
5015 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5016 SMLoc Loc = Lex.getLoc();
5017 Lex.Lex();
5018
5019 ValID Fn, Label;
5020 SmallVector<unsigned, 16> Indexes;
5021 if (ParseValID(Fn) ||
5022 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5023 ParseValID(Label) ||
5024 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5025 ParseUseListOrderIndexes(Indexes))
5026 return true;
5027
5028 // Check the function.
5029 GlobalValue *GV;
5030 if (Fn.Kind == ValID::t_GlobalName)
5031 GV = M->getNamedValue(Fn.StrVal);
5032 else if (Fn.Kind == ValID::t_GlobalID)
5033 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5034 else
5035 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5036 if (!GV)
5037 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5038 auto *F = dyn_cast<Function>(GV);
5039 if (!F)
5040 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5041 if (F->isDeclaration())
5042 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5043
5044 // Check the basic block.
5045 if (Label.Kind == ValID::t_LocalID)
5046 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5047 if (Label.Kind != ValID::t_LocalName)
5048 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5049 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5050 if (!V)
5051 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5052 if (!isa<BasicBlock>(V))
5053 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5054
5055 return sortUseListOrder(V, Indexes, Loc);
5056}