blob: 441d36cb21d877e307b84699b28a5471465c1172 [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 Smith70ab3d22015-02-21 01:02:18 +000019#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000020#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/InlineAsm.h"
23#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000024#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
27#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000028#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000030#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000031#include "llvm/Support/raw_ostream.h"
32using namespace llvm;
33
Chris Lattner229907c2011-07-18 04:54:35 +000034static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000035 std::string Result;
36 raw_string_ostream Tmp(Result);
37 Tmp << *T;
38 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000039}
40
Chris Lattner3822f632009-01-02 08:05:26 +000041/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000042bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000043 // Prime the lexer.
44 Lex.Lex();
45
Chris Lattnerad6f3352009-01-04 20:44:11 +000046 return ParseTopLevelEntities() ||
47 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000048}
49
50/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51/// module.
52bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000053 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55
Bill Wendlingb32b0412013-02-08 06:32:06 +000056 // Handle any function attribute group forward references.
57 for (std::map<Value*, std::vector<unsigned> >::iterator
58 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
59 I != E; ++I) {
60 Value *V = I->first;
61 std::vector<unsigned> &Vec = I->second;
62 AttrBuilder B;
63
64 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65 VI != VE; ++VI)
66 B.merge(NumberedAttrBuilders[*VI]);
67
68 if (Function *Fn = dyn_cast<Function>(V)) {
69 AttributeSet AS = Fn->getAttributes();
70 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72 AS.getFnAttributes());
73
74 FnAttrs.merge(B);
75
76 // If the alignment was parsed as an attribute, move to the alignment
77 // field.
78 if (FnAttrs.hasAlignmentAttr()) {
79 Fn->setAlignment(FnAttrs.getAlignment());
80 FnAttrs.removeAttribute(Attribute::Alignment);
81 }
82
83 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84 AttributeSet::get(Context,
85 AttributeSet::FunctionIndex,
86 FnAttrs));
87 Fn->setAttributes(AS);
88 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89 AttributeSet AS = CI->getAttributes();
90 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000093 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000094 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95 AttributeSet::get(Context,
96 AttributeSet::FunctionIndex,
97 FnAttrs));
98 CI->setAttributes(AS);
99 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100 AttributeSet AS = II->getAttributes();
101 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000104 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000105 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106 AttributeSet::get(Context,
107 AttributeSet::FunctionIndex,
108 FnAttrs));
109 II->setAttributes(AS);
110 } else {
111 llvm_unreachable("invalid object with forward attribute group reference");
112 }
113 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000114
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000115 // If there are entries in ForwardRefBlockAddresses at this point, the
116 // function was never defined.
117 if (!ForwardRefBlockAddresses.empty())
118 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000120
David Majnemer19b51052015-02-11 07:43:56 +0000121 for (const auto &NT : NumberedTypes)
122 if (NT.second.second.isValid())
123 return Error(NT.second.second,
124 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000125
126 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128 if (I->second.second.isValid())
129 return Error(I->second.second,
130 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000131
David Majnemerdad0a642014-06-27 18:19:56 +0000132 if (!ForwardRefComdats.empty())
133 return Error(ForwardRefComdats.begin()->second,
134 "use of undefined comdat '$" +
135 ForwardRefComdats.begin()->first + "'");
136
Chris Lattnerac161bf2009-01-02 07:01:27 +0000137 if (!ForwardRefVals.empty())
138 return Error(ForwardRefVals.begin()->second.second,
139 "use of undefined value '@" + ForwardRefVals.begin()->first +
140 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000141
Chris Lattnerac161bf2009-01-02 07:01:27 +0000142 if (!ForwardRefValIDs.empty())
143 return Error(ForwardRefValIDs.begin()->second.second,
144 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000145 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000146
Devang Pateld2541152009-07-08 19:23:54 +0000147 if (!ForwardRefMDNodes.empty())
148 return Error(ForwardRefMDNodes.begin()->second.second,
149 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000150 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000151
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000152 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000153 for (auto &N : NumberedMetadata) {
154 if (N.second && !N.second->isResolved())
155 N.second->resolveCycles();
156 }
Devang Pateld2541152009-07-08 19:23:54 +0000157
Chris Lattnerac161bf2009-01-02 07:01:27 +0000158 // Look for intrinsic functions and CallInst that need to be upgraded
159 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000161
Manman Ren8b4306c2013-12-02 21:29:56 +0000162 UpgradeDebugInfo(*M);
163
Chris Lattnerac161bf2009-01-02 07:01:27 +0000164 return false;
165}
166
167//===----------------------------------------------------------------------===//
168// Top-Level Entities
169//===----------------------------------------------------------------------===//
170
171bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000172 while (1) {
173 switch (Lex.getKind()) {
174 default: return TokError("expected top-level entity");
175 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000176 case lltok::kw_declare: if (ParseDeclare()) return true; break;
177 case lltok::kw_define: if (ParseDefine()) return true; break;
178 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
179 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000180 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000181 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000182 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000183 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000185 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000186 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000187 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000188
189 // The Global variable production with no name can have many different
190 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000191 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000193 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000194 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000195 case lltok::kw_internal: // OptionalLinkage
196 case lltok::kw_weak: // OptionalLinkage
197 case lltok::kw_weak_odr: // OptionalLinkage
198 case lltok::kw_linkonce: // OptionalLinkage
199 case lltok::kw_linkonce_odr: // OptionalLinkage
200 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000201 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000202 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000203 case lltok::kw_external: // OptionalLinkage
204 case lltok::kw_default: // OptionalVisibility
205 case lltok::kw_hidden: // OptionalVisibility
206 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000207 case lltok::kw_dllimport: // OptionalDLLStorageClass
208 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000209 case lltok::kw_thread_local: // OptionalThreadLocal
210 case lltok::kw_addrspace: // OptionalAddrSpace
211 case lltok::kw_constant: // GlobalType
212 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000213 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000214 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000215 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000216 bool HasLinkage;
217 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000218 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000219 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000220 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000221 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000222 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000223 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000224 return true;
225 break;
226 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000227
228 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000229 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230 case lltok::kw_uselistorder_bb:
231 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000232 }
233 }
234}
235
236
237/// toplevelentity
238/// ::= 'module' 'asm' STRINGCONSTANT
239bool LLParser::ParseModuleAsm() {
240 assert(Lex.getKind() == lltok::kw_module);
241 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000242
243 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000244 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000246
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000247 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000248 return false;
249}
250
251/// toplevelentity
252/// ::= 'target' 'triple' '=' STRINGCONSTANT
253/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
254bool LLParser::ParseTargetDefinition() {
255 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000256 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000257 switch (Lex.Lex()) {
258 default: return TokError("unknown target property");
259 case lltok::kw_triple:
260 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000261 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000263 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000264 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 return false;
266 case lltok::kw_datalayout:
267 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000268 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000270 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000271 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000272 return false;
273 }
274}
275
Bill Wendling706d3d62012-11-28 08:41:48 +0000276/// toplevelentity
277/// ::= 'deplibs' '=' '[' ']'
278/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279/// FIXME: Remove in 4.0. Currently parse, but ignore.
280bool LLParser::ParseDepLibs() {
281 assert(Lex.getKind() == lltok::kw_deplibs);
282 Lex.Lex();
283 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285 return true;
286
287 if (EatIfPresent(lltok::rsquare))
288 return false;
289
290 do {
291 std::string Str;
292 if (ParseStringConstant(Str)) return true;
293 } while (EatIfPresent(lltok::comma));
294
295 return ParseToken(lltok::rsquare, "expected ']' at end of list");
296}
297
Dan Gohman466876b2009-08-12 23:32:33 +0000298/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000299/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000300bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000301 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000302 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000303 Lex.Lex(); // eat LocalVarID;
304
305 if (ParseToken(lltok::equal, "expected '=' after name") ||
306 ParseToken(lltok::kw_type, "expected 'type' after '='"))
307 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000308
Craig Topper2617dcc2014-04-15 06:32:26 +0000309 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000310 if (ParseStructDefinition(TypeLoc, "",
311 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000313 if (!isa<StructType>(Result)) {
314 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315 if (Entry.first)
316 return Error(TypeLoc, "non-struct types may not be recursive");
317 Entry.first = Result;
318 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000320
Chris Lattnerac161bf2009-01-02 07:01:27 +0000321 return false;
322}
323
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000324
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325/// toplevelentity
326/// ::= LocalVar '=' 'type' type
327bool LLParser::ParseNamedType() {
328 std::string Name = Lex.getStrVal();
329 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000330 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000331
Chris Lattner3822f632009-01-02 08:05:26 +0000332 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000334 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000335
Craig Topper2617dcc2014-04-15 06:32:26 +0000336 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000337 if (ParseStructDefinition(NameLoc, Name,
338 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000339
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000340 if (!isa<StructType>(Result)) {
341 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342 if (Entry.first)
343 return Error(NameLoc, "non-struct types may not be recursive");
344 Entry.first = Result;
345 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000346 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000348 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000349}
350
351
352/// toplevelentity
353/// ::= 'declare' FunctionHeader
354bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
356 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000357
Chris Lattnerac161bf2009-01-02 07:01:27 +0000358 Function *F;
359 return ParseFunctionHeader(F, false);
360}
361
362/// toplevelentity
363/// ::= 'define' FunctionHeader '{' ...
364bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
366 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000367
Chris Lattnerac161bf2009-01-02 07:01:27 +0000368 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371}
372
Chris Lattner3822f632009-01-02 08:05:26 +0000373/// ParseGlobalType
374/// ::= 'constant'
375/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
378 IsConstant = true;
379 else if (Lex.getKind() == lltok::kw_global)
380 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000381 else {
382 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000384 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385 Lex.Lex();
386 return false;
387}
388
Dan Gohman466876b2009-08-12 23:32:33 +0000389/// ParseUnnamedGlobal:
390/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000391/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000393/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000394/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000396bool LLParser::ParseUnnamedGlobal() {
397 unsigned VarID = NumberedVals.size();
398 std::string Name;
399 LocTy NameLoc = Lex.getLoc();
400
401 // Handle the GlobalID form.
402 if (Lex.getKind() == lltok::GlobalID) {
403 if (Lex.getUIntVal() != VarID)
404 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000405 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000406 Lex.Lex(); // eat GlobalID;
407
408 if (ParseToken(lltok::equal, "expected '=' after name"))
409 return true;
410 }
411
412 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000413 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000414 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000415 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000416 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000417 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000418 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000419 ParseOptionalThreadLocal(TLM) ||
420 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000421 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000422
Rafael Espindola464fe022014-07-30 22:51:54 +0000423 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000425 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000426 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000427 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000428}
429
Chris Lattnerac161bf2009-01-02 07:01:27 +0000430/// ParseNamedGlobal:
431/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000432/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434bool LLParser::ParseNamedGlobal() {
435 assert(Lex.getKind() == lltok::GlobalVar);
436 LocTy NameLoc = Lex.getLoc();
437 std::string Name = Lex.getStrVal();
438 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000439
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000441 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000442 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000443 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000446 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000447 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000448 ParseOptionalThreadLocal(TLM) ||
449 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Rafael Espindola464fe022014-07-30 22:51:54 +0000452 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000454 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000455
456 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000457 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458}
459
David Majnemerdad0a642014-06-27 18:19:56 +0000460bool LLParser::parseComdat() {
461 assert(Lex.getKind() == lltok::ComdatVar);
462 std::string Name = Lex.getStrVal();
463 LocTy NameLoc = Lex.getLoc();
464 Lex.Lex();
465
466 if (ParseToken(lltok::equal, "expected '=' here"))
467 return true;
468
469 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470 return TokError("expected comdat type");
471
472 Comdat::SelectionKind SK;
473 switch (Lex.getKind()) {
474 default:
475 return TokError("unknown selection kind");
476 case lltok::kw_any:
477 SK = Comdat::Any;
478 break;
479 case lltok::kw_exactmatch:
480 SK = Comdat::ExactMatch;
481 break;
482 case lltok::kw_largest:
483 SK = Comdat::Largest;
484 break;
485 case lltok::kw_noduplicates:
486 SK = Comdat::NoDuplicates;
487 break;
488 case lltok::kw_samesize:
489 SK = Comdat::SameSize;
490 break;
491 }
492 Lex.Lex();
493
494 // See if the comdat was forward referenced, if so, use the comdat.
495 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
499
500 Comdat *C;
501 if (I != ComdatSymTab.end())
502 C = &I->second;
503 else
504 C = M->getOrInsertComdat(Name);
505 C->setSelectionKind(SK);
506
507 return false;
508}
509
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000510// MDString:
511// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000512bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000513 std::string Str;
514 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000515 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000516 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000517 return false;
518}
519
520// MDNode:
521// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000522bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000523 // !{ ..., !42, ... }
524 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000525 if (ParseUInt32(MID))
526 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000527
Chris Lattner8eff0152010-04-01 05:14:45 +0000528 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000529 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000530 Result = NumberedMetadata[MID];
531 return false;
532 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000533
Chris Lattner8eff0152010-04-01 05:14:45 +0000534 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000535 auto &FwdRef = ForwardRefMDNodes[MID];
536 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000537
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000538 Result = FwdRef.first.get();
539 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000540 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000541}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000542
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000543/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000544/// !foo = !{ !1, !2 }
545bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000546 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000547 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000548 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000549
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000550 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000551 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000552 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000553 return true;
554
Dan Gohman2637cc12010-07-21 23:38:33 +0000555 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000556 if (Lex.getKind() != lltok::rbrace)
557 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000558 if (ParseToken(lltok::exclaim, "Expected '!' here"))
559 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000560
Craig Topper2617dcc2014-04-15 06:32:26 +0000561 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000562 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000563 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000564 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000565
566 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
567 return true;
568
Devang Patelbe626972009-07-29 00:34:02 +0000569 return false;
570}
571
Devang Patel39e64d42009-07-01 19:21:12 +0000572/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000574bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000575 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000576 Lex.Lex();
577 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000578
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000579 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000580 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000581 ParseToken(lltok::equal, "expected '=' here"))
582 return true;
583
584 // Detect common error, from old metadata syntax.
585 if (Lex.getKind() == lltok::Type)
586 return TokError("unexpected type in metadata definition");
587
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000588 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000589 if (Lex.getKind() == lltok::MetadataVar) {
590 if (ParseSpecializedMDNode(Init, IsDistinct))
591 return true;
592 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
593 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000594 return true;
595
Chris Lattnerfc58af22009-12-30 04:51:58 +0000596 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000597 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000598 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000599 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000600 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000601
Chris Lattnerfc58af22009-12-30 04:51:58 +0000602 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
603 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000604 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000605 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000606 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000607 }
608
Devang Patel39e64d42009-07-01 19:21:12 +0000609 return false;
610}
611
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000612static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
613 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
614 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
615}
616
Chris Lattnerac161bf2009-01-02 07:01:27 +0000617/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000618/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
619/// OptionalDLLStorageClass OptionalThreadLocal
620/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000621///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000622/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000623/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000624///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000625/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000626///
Rafael Espindola464fe022014-07-30 22:51:54 +0000627bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000628 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000629 GlobalVariable::ThreadLocalMode TLM,
630 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631 assert(Lex.getKind() == lltok::kw_alias);
632 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000633
Rafael Espindola78527052013-10-06 15:10:43 +0000634 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
635
Rafael Espindolacaa43562013-10-09 16:07:32 +0000636 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000637 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000638
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000639 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000640 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000641 "symbol with local linkage must have default visibility");
642
Rafael Espindola64c1e182014-06-03 02:41:57 +0000643 Constant *Aliasee;
644 LocTy AliaseeLoc = Lex.getLoc();
645 if (Lex.getKind() != lltok::kw_bitcast &&
646 Lex.getKind() != lltok::kw_getelementptr &&
647 Lex.getKind() != lltok::kw_addrspacecast &&
648 Lex.getKind() != lltok::kw_inttoptr) {
649 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000650 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000651 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000652 // The bitcast dest type is not present, it is implied by the dest type.
653 ValID ID;
654 if (ParseValID(ID))
655 return true;
656 if (ID.Kind != ValID::t_Constant)
657 return Error(AliaseeLoc, "invalid aliasee");
658 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000660
Rafael Espindola64c1e182014-06-03 02:41:57 +0000661 Type *AliaseeType = Aliasee->getType();
662 auto *PTy = dyn_cast<PointerType>(AliaseeType);
663 if (!PTy)
664 return Error(AliaseeLoc, "An alias must have pointer type");
665 Type *Ty = PTy->getElementType();
666 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000667
668 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000669 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000670 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
671 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000672 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000673 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000674 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000675 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000676
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677 // See if this value already exists in the symbol table. If so, it is either
678 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000679 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000680 // See if this was a redefinition. If so, there is no entry in
681 // ForwardRefVals.
682 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
683 I = ForwardRefVals.find(Name);
684 if (I == ForwardRefVals.end())
685 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
686
687 // Otherwise, this was a definition of forward ref. Verify that types
688 // agree.
689 if (Val->getType() != GA->getType())
690 return Error(NameLoc,
691 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000692
Chris Lattnerac161bf2009-01-02 07:01:27 +0000693 // If they agree, just RAUW the old value with the alias and remove the
694 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000695 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696 Val->eraseFromParent();
697 ForwardRefVals.erase(I);
698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000699
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000701 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000702 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000703
Rafael Espindolaaa273822014-05-09 21:49:17 +0000704 // The module owns this now
705 GA.release();
706
Chris Lattnerac161bf2009-01-02 07:01:27 +0000707 return false;
708}
709
710/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000711/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000712/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000713/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000714/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000715/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000716/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000717///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000718/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000719/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720///
721bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
722 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000723 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000724 GlobalVariable::ThreadLocalMode TLM,
725 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000726 if (!isValidVisibilityForLinkage(Visibility, Linkage))
727 return Error(NameLoc,
728 "symbol with local linkage must have default visibility");
729
Chris Lattnerac161bf2009-01-02 07:01:27 +0000730 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000731 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000732 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000733 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Craig Topper2617dcc2014-04-15 06:32:26 +0000735 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000736 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000737 ParseOptionalToken(lltok::kw_externally_initialized,
738 IsExternallyInitialized,
739 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000740 ParseGlobalType(IsConstant) ||
741 ParseType(Ty, TyLoc))
742 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000743
Chris Lattnerac161bf2009-01-02 07:01:27 +0000744 // If the linkage is specified and is external, then no initializer is
745 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000746 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000747 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 Linkage != GlobalValue::ExternalLinkage)) {
749 if (ParseGlobalValue(Ty, Init))
750 return true;
751 }
752
David Majnemer49b3d9b2015-02-16 08:41:08 +0000753 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000754 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
David Majnemer598bd052014-12-09 05:56:09 +0000756 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000757
758 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000759 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000760 GVal = M->getNamedValue(Name);
761 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000762 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
763 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000764 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765 } else {
766 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
767 I = ForwardRefValIDs.find(NumberedVals.size());
768 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000769 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000770 ForwardRefValIDs.erase(I);
771 }
772 }
773
David Majnemer598bd052014-12-09 05:56:09 +0000774 GlobalVariable *GV;
775 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000776 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
777 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000778 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000780 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000781 return Error(TyLoc,
782 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
David Majnemer598bd052014-12-09 05:56:09 +0000784 GV = cast<GlobalVariable>(GVal);
785
Chris Lattnerac161bf2009-01-02 07:01:27 +0000786 // Move the forward-reference to the correct spot in the module.
787 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
788 }
789
790 if (Name.empty())
791 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000792
Chris Lattnerac161bf2009-01-02 07:01:27 +0000793 // Set the parsed properties on the global.
794 if (Init)
795 GV->setInitializer(Init);
796 GV->setConstant(IsConstant);
797 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
798 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000799 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000800 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000801 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000802 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 // Parse attributes on the global.
805 while (Lex.getKind() == lltok::comma) {
806 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000807
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 if (Lex.getKind() == lltok::kw_section) {
809 Lex.Lex();
810 GV->setSection(Lex.getStrVal());
811 if (ParseToken(lltok::StringConstant, "expected global section string"))
812 return true;
813 } else if (Lex.getKind() == lltok::kw_align) {
814 unsigned Alignment;
815 if (ParseOptionalAlignment(Alignment)) return true;
816 GV->setAlignment(Alignment);
817 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000818 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000819 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000820 return true;
821 if (C)
822 GV->setComdat(C);
823 else
824 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 }
826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 return false;
829}
830
Bill Wendling63b88192013-02-06 06:52:58 +0000831/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000832/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000833bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000834 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000835 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000836 Lex.Lex();
837
David Majnemerb39e22b2014-12-09 18:33:57 +0000838 if (Lex.getKind() != lltok::AttrGrpID)
839 return TokError("expected attribute group id");
840
Bill Wendling63b88192013-02-06 06:52:58 +0000841 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000842 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000843 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000844 Lex.Lex();
845
846 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000847 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000848 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000849 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000850 ParseToken(lltok::rbrace, "expected end of attribute group"))
851 return true;
852
Bill Wendlingb32b0412013-02-08 06:32:06 +0000853 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000854 return Error(AttrGrpLoc, "attribute group has no attributes");
855
856 return false;
857}
858
Bill Wendling8b0321d2013-02-08 00:52:31 +0000859/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000860/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000861bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
862 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000863 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000864 bool HaveError = false;
865
866 B.clear();
867
Bill Wendling63b88192013-02-06 06:52:58 +0000868 while (true) {
869 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000870 if (Token == lltok::kw_builtin)
871 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000872 switch (Token) {
873 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000874 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000875 return Error(Lex.getLoc(), "unterminated attribute group");
876 case lltok::rbrace:
877 // Finished.
878 return false;
879
Bill Wendlingb32b0412013-02-08 06:32:06 +0000880 case lltok::AttrGrpID: {
881 // Allow a function to reference an attribute group:
882 //
883 // define void @foo() #1 { ... }
884 if (inAttrGrp)
885 HaveError |=
886 Error(Lex.getLoc(),
887 "cannot have an attribute group reference in an attribute group");
888
889 unsigned AttrGrpNum = Lex.getUIntVal();
890 if (inAttrGrp) break;
891
892 // Save the reference to the attribute group. We'll fill it in later.
893 FwdRefAttrGrps.push_back(AttrGrpNum);
894 break;
895 }
Bill Wendling63b88192013-02-06 06:52:58 +0000896 // Target-dependent attributes:
897 case lltok::StringConstant: {
898 std::string Attr = Lex.getStrVal();
899 Lex.Lex();
900 std::string Val;
901 if (EatIfPresent(lltok::equal) &&
902 ParseStringConstant(Val))
903 return true;
904
905 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000906 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000907 }
908
909 // Target-independent attributes:
910 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000911 // As a hack, we allow function alignment to be initially parsed as an
912 // attribute on a function declaration/definition or added to an attribute
913 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000914 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000915 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000916 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000917 if (ParseToken(lltok::equal, "expected '=' here") ||
918 ParseUInt32(Alignment))
919 return true;
920 } else {
921 if (ParseOptionalAlignment(Alignment))
922 return true;
923 }
Bill Wendling63b88192013-02-06 06:52:58 +0000924 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000925 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000926 }
927 case lltok::kw_alignstack: {
928 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000929 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000930 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
933 return true;
934 } else {
935 if (ParseOptionalStackAlignment(Alignment))
936 return true;
937 }
Bill Wendling63b88192013-02-06 06:52:58 +0000938 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000940 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000941 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000942 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000943 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000944 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000945 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000946 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
947 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
948 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
949 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
950 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
951 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
952 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
953 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
954 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
955 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000956 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000957 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
958 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
959 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
960 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
961 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
962 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
963 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
964 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
965 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
966 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
967 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000968
969 // Error handling.
970 case lltok::kw_inreg:
971 case lltok::kw_signext:
972 case lltok::kw_zeroext:
973 HaveError |=
974 Error(Lex.getLoc(),
975 "invalid use of attribute on a function");
976 break;
977 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000978 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000979 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +0000980 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000981 case lltok::kw_nest:
982 case lltok::kw_noalias:
983 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000984 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000985 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000986 case lltok::kw_sret:
987 HaveError |=
988 Error(Lex.getLoc(),
989 "invalid use of parameter-only attribute on a function");
990 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000991 }
992
993 Lex.Lex();
994 }
995}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000996
997//===----------------------------------------------------------------------===//
998// GlobalValue Reference/Resolution Routines.
999//===----------------------------------------------------------------------===//
1000
1001/// GetGlobalVal - Get a value with the specified name or ID, creating a
1002/// forward reference record if needed. This can return null if the value
1003/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001004GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001005 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001006 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001007 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001008 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001009 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001010 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001011
Chris Lattnerac161bf2009-01-02 07:01:27 +00001012 // Look this name up in the normal function symbol table.
1013 GlobalValue *Val =
1014 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001015
Chris Lattnerac161bf2009-01-02 07:01:27 +00001016 // If this is a forward reference for the value, see if we already created a
1017 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001018 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001019 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1020 I = ForwardRefVals.find(Name);
1021 if (I != ForwardRefVals.end())
1022 Val = I->second.first;
1023 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001024
Chris Lattnerac161bf2009-01-02 07:01:27 +00001025 // If we have the value in the symbol table or fwd-ref table, return it.
1026 if (Val) {
1027 if (Val->getType() == Ty) return Val;
1028 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001029 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001030 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001032
Chris Lattnerac161bf2009-01-02 07:01:27 +00001033 // Otherwise, create a new forward reference for this value and remember it.
1034 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001035 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001036 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001037 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001038 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001039 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1040 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001041 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001042
Chris Lattnerac161bf2009-01-02 07:01:27 +00001043 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1044 return FwdVal;
1045}
1046
Chris Lattner229907c2011-07-18 04:54:35 +00001047GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1048 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001050 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001051 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001052 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001053
Craig Topper2617dcc2014-04-15 06:32:26 +00001054 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001055
Chris Lattnerac161bf2009-01-02 07:01:27 +00001056 // If this is a forward reference for the value, see if we already created a
1057 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001058 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1060 I = ForwardRefValIDs.find(ID);
1061 if (I != ForwardRefValIDs.end())
1062 Val = I->second.first;
1063 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001064
Chris Lattnerac161bf2009-01-02 07:01:27 +00001065 // If we have the value in the symbol table or fwd-ref table, return it.
1066 if (Val) {
1067 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001068 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001069 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001070 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001071 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001072
Chris Lattnerac161bf2009-01-02 07:01:27 +00001073 // Otherwise, create a new forward reference for this value and remember it.
1074 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001075 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001076 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001077 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001078 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001079 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001080
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1082 return FwdVal;
1083}
1084
1085
1086//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001087// Comdat Reference/Resolution Routines.
1088//===----------------------------------------------------------------------===//
1089
1090Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1091 // Look this name up in the comdat symbol table.
1092 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1093 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1094 if (I != ComdatSymTab.end())
1095 return &I->second;
1096
1097 // Otherwise, create a new forward reference for this value and remember it.
1098 Comdat *C = M->getOrInsertComdat(Name);
1099 ForwardRefComdats[Name] = Loc;
1100 return C;
1101}
1102
1103
1104//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001105// Helper Routines.
1106//===----------------------------------------------------------------------===//
1107
1108/// ParseToken - If the current token has the specified kind, eat it and return
1109/// success. Otherwise, emit the specified error and return failure.
1110bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1111 if (Lex.getKind() != T)
1112 return TokError(ErrMsg);
1113 Lex.Lex();
1114 return false;
1115}
1116
Chris Lattner3822f632009-01-02 08:05:26 +00001117/// ParseStringConstant
1118/// ::= StringConstant
1119bool LLParser::ParseStringConstant(std::string &Result) {
1120 if (Lex.getKind() != lltok::StringConstant)
1121 return TokError("expected string constant");
1122 Result = Lex.getStrVal();
1123 Lex.Lex();
1124 return false;
1125}
1126
1127/// ParseUInt32
1128/// ::= uint32
1129bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001130 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1131 return TokError("expected integer");
1132 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1133 if (Val64 != unsigned(Val64))
1134 return TokError("expected 32-bit integer (too large)");
1135 Val = Val64;
1136 Lex.Lex();
1137 return false;
1138}
1139
Hal Finkelb0407ba2014-07-18 15:51:28 +00001140/// ParseUInt64
1141/// ::= uint64
1142bool LLParser::ParseUInt64(uint64_t &Val) {
1143 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1144 return TokError("expected integer");
1145 Val = Lex.getAPSIntVal().getLimitedValue();
1146 Lex.Lex();
1147 return false;
1148}
1149
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001150/// ParseTLSModel
1151/// := 'localdynamic'
1152/// := 'initialexec'
1153/// := 'localexec'
1154bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1155 switch (Lex.getKind()) {
1156 default:
1157 return TokError("expected localdynamic, initialexec or localexec");
1158 case lltok::kw_localdynamic:
1159 TLM = GlobalVariable::LocalDynamicTLSModel;
1160 break;
1161 case lltok::kw_initialexec:
1162 TLM = GlobalVariable::InitialExecTLSModel;
1163 break;
1164 case lltok::kw_localexec:
1165 TLM = GlobalVariable::LocalExecTLSModel;
1166 break;
1167 }
1168
1169 Lex.Lex();
1170 return false;
1171}
1172
1173/// ParseOptionalThreadLocal
1174/// := /*empty*/
1175/// := 'thread_local'
1176/// := 'thread_local' '(' tlsmodel ')'
1177bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1178 TLM = GlobalVariable::NotThreadLocal;
1179 if (!EatIfPresent(lltok::kw_thread_local))
1180 return false;
1181
1182 TLM = GlobalVariable::GeneralDynamicTLSModel;
1183 if (Lex.getKind() == lltok::lparen) {
1184 Lex.Lex();
1185 return ParseTLSModel(TLM) ||
1186 ParseToken(lltok::rparen, "expected ')' after thread local model");
1187 }
1188 return false;
1189}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001190
1191/// ParseOptionalAddrSpace
1192/// := /*empty*/
1193/// := 'addrspace' '(' uint32 ')'
1194bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1195 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001196 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001198 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001199 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001201}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202
Bill Wendling34c2eb22012-12-04 23:40:58 +00001203/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1204bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1205 bool HaveError = false;
1206
1207 B.clear();
1208
1209 while (1) {
1210 lltok::Kind Token = Lex.getKind();
1211 switch (Token) {
1212 default: // End of attributes.
1213 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 case lltok::kw_align: {
1215 unsigned Alignment;
1216 if (ParseOptionalAlignment(Alignment))
1217 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001218 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219 continue;
1220 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001221 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001222 case lltok::kw_dereferenceable: {
1223 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001224 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001225 return true;
1226 B.addDereferenceableAttr(Bytes);
1227 continue;
1228 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001229 case lltok::kw_dereferenceable_or_null: {
1230 uint64_t Bytes;
1231 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1232 return true;
1233 B.addDereferenceableOrNullAttr(Bytes);
1234 continue;
1235 }
Reid Klecknera534a382013-12-19 02:14:12 +00001236 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001237 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1238 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1239 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1240 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001241 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001242 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1243 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001244 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001245 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1246 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1247 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001248
Stephen Lin7577ed52013-04-20 13:16:13 +00001249 case lltok::kw_alignstack:
1250 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001251 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001252 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001253 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001254 case lltok::kw_minsize:
1255 case lltok::kw_naked:
1256 case lltok::kw_nobuiltin:
1257 case lltok::kw_noduplicate:
1258 case lltok::kw_noimplicitfloat:
1259 case lltok::kw_noinline:
1260 case lltok::kw_nonlazybind:
1261 case lltok::kw_noredzone:
1262 case lltok::kw_noreturn:
1263 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001264 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001265 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001266 case lltok::kw_returns_twice:
1267 case lltok::kw_sanitize_address:
1268 case lltok::kw_sanitize_memory:
1269 case lltok::kw_sanitize_thread:
1270 case lltok::kw_ssp:
1271 case lltok::kw_sspreq:
1272 case lltok::kw_sspstrong:
1273 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001274 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1275 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001276 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001277
Bill Wendling34c2eb22012-12-04 23:40:58 +00001278 Lex.Lex();
1279 }
1280}
1281
1282/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1283bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1284 bool HaveError = false;
1285
1286 B.clear();
1287
1288 while (1) {
1289 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001290 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001291 default: // End of attributes.
1292 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001293 case lltok::kw_dereferenceable: {
1294 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001295 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001296 return true;
1297 B.addDereferenceableAttr(Bytes);
1298 continue;
1299 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001300 case lltok::kw_dereferenceable_or_null: {
1301 uint64_t Bytes;
1302 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1303 return true;
1304 B.addDereferenceableOrNullAttr(Bytes);
1305 continue;
1306 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001307 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1308 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001309 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001310 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1311 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001312
Bill Wendling34c2eb22012-12-04 23:40:58 +00001313 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001314 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001315 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001316 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001317 case lltok::kw_nest:
1318 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001319 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001320 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001321 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001322 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001323
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001324 case lltok::kw_alignstack:
1325 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001326 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001327 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001328 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001329 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001330 case lltok::kw_minsize:
1331 case lltok::kw_naked:
1332 case lltok::kw_nobuiltin:
1333 case lltok::kw_noduplicate:
1334 case lltok::kw_noimplicitfloat:
1335 case lltok::kw_noinline:
1336 case lltok::kw_nonlazybind:
1337 case lltok::kw_noredzone:
1338 case lltok::kw_noreturn:
1339 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001340 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001341 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001342 case lltok::kw_returns_twice:
1343 case lltok::kw_sanitize_address:
1344 case lltok::kw_sanitize_memory:
1345 case lltok::kw_sanitize_thread:
1346 case lltok::kw_ssp:
1347 case lltok::kw_sspreq:
1348 case lltok::kw_sspstrong:
1349 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001350 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001351 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001352
1353 case lltok::kw_readnone:
1354 case lltok::kw_readonly:
1355 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001356 }
1357
Chris Lattnerac161bf2009-01-02 07:01:27 +00001358 Lex.Lex();
1359 }
1360}
1361
1362/// ParseOptionalLinkage
1363/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001364/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001365/// ::= 'internal'
1366/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001367/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001368/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001369/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001370/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001371/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001373/// ::= 'extern_weak'
1374/// ::= 'external'
1375bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1376 HasLinkage = false;
1377 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001378 default: Res=GlobalValue::ExternalLinkage; return false;
1379 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001380 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1381 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1382 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1383 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1384 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001385 case lltok::kw_available_externally:
1386 Res = GlobalValue::AvailableExternallyLinkage;
1387 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001388 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001389 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001390 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1391 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001392 }
1393 Lex.Lex();
1394 HasLinkage = true;
1395 return false;
1396}
1397
1398/// ParseOptionalVisibility
1399/// ::= /*empty*/
1400/// ::= 'default'
1401/// ::= 'hidden'
1402/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001403///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001404bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1405 switch (Lex.getKind()) {
1406 default: Res = GlobalValue::DefaultVisibility; return false;
1407 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1408 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1409 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1410 }
1411 Lex.Lex();
1412 return false;
1413}
1414
Nico Rieck7157bb72014-01-14 15:22:47 +00001415/// ParseOptionalDLLStorageClass
1416/// ::= /*empty*/
1417/// ::= 'dllimport'
1418/// ::= 'dllexport'
1419///
1420bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1421 switch (Lex.getKind()) {
1422 default: Res = GlobalValue::DefaultStorageClass; return false;
1423 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1424 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1425 }
1426 Lex.Lex();
1427 return false;
1428}
1429
Chris Lattnerac161bf2009-01-02 07:01:27 +00001430/// ParseOptionalCallingConv
1431/// ::= /*empty*/
1432/// ::= 'ccc'
1433/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001434/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001435/// ::= 'coldcc'
1436/// ::= 'x86_stdcallcc'
1437/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001438/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001439/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001440/// ::= 'arm_apcscc'
1441/// ::= 'arm_aapcscc'
1442/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001443/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001444/// ::= 'ptx_kernel'
1445/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001446/// ::= 'spir_func'
1447/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001448/// ::= 'x86_64_sysvcc'
1449/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001450/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001451/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001452/// ::= 'preserve_mostcc'
1453/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001454/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001455/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001456///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001457bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001458 switch (Lex.getKind()) {
1459 default: CC = CallingConv::C; return false;
1460 case lltok::kw_ccc: CC = CallingConv::C; break;
1461 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1462 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1463 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1464 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001465 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001466 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001467 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1468 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1469 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001470 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001471 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1472 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001473 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1474 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001475 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001476 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1477 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001478 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001479 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001480 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1481 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001482 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001483 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001484 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001485 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001486 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001488
Chris Lattnerac161bf2009-01-02 07:01:27 +00001489 Lex.Lex();
1490 return false;
1491}
1492
Chris Lattner5c427632009-12-30 05:31:19 +00001493/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001494/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001495bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1496 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001497 do {
1498 if (Lex.getKind() != lltok::MetadataVar)
1499 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001500
Chris Lattner596760d2009-12-29 21:25:40 +00001501 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001502 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001503 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001504
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001505 MDNode *N;
1506 if (ParseMDNode(N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001507 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001508
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001509 Inst->setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001510 if (MDK == LLVMContext::MD_tbaa)
1511 InstsWithTBAATag.push_back(Inst);
1512
Chris Lattner596760d2009-12-29 21:25:40 +00001513 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001514 } while (EatIfPresent(lltok::comma));
1515 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001516}
1517
Chris Lattnerac161bf2009-01-02 07:01:27 +00001518/// ParseOptionalAlignment
1519/// ::= /* empty */
1520/// ::= 'align' 4
1521bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1522 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001523 if (!EatIfPresent(lltok::kw_align))
1524 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001525 LocTy AlignLoc = Lex.getLoc();
1526 if (ParseUInt32(Alignment)) return true;
1527 if (!isPowerOf2_32(Alignment))
1528 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001529 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001530 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001531 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001532}
1533
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001534/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001535/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001536/// ::= AttrKind '(' 4 ')'
1537///
1538/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1539bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1540 uint64_t &Bytes) {
1541 assert((AttrKind == lltok::kw_dereferenceable ||
1542 AttrKind == lltok::kw_dereferenceable_or_null) &&
1543 "contract!");
1544
Hal Finkelb0407ba2014-07-18 15:51:28 +00001545 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001546 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001547 return false;
1548 LocTy ParenLoc = Lex.getLoc();
1549 if (!EatIfPresent(lltok::lparen))
1550 return Error(ParenLoc, "expected '('");
1551 LocTy DerefLoc = Lex.getLoc();
1552 if (ParseUInt64(Bytes)) return true;
1553 ParenLoc = Lex.getLoc();
1554 if (!EatIfPresent(lltok::rparen))
1555 return Error(ParenLoc, "expected ')'");
1556 if (!Bytes)
1557 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1558 return false;
1559}
1560
Chris Lattnerb2f39502009-12-30 05:44:30 +00001561/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001562/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001563/// ::= ',' align 4
1564///
1565/// This returns with AteExtraComma set to true if it ate an excess comma at the
1566/// end.
1567bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1568 bool &AteExtraComma) {
1569 AteExtraComma = false;
1570 while (EatIfPresent(lltok::comma)) {
1571 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001572 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001573 AteExtraComma = true;
1574 return false;
1575 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001576
Chris Lattner95b0ff42010-04-23 00:50:50 +00001577 if (Lex.getKind() != lltok::kw_align)
1578 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001579
Chris Lattner95b0ff42010-04-23 00:50:50 +00001580 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001581 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001582
Devang Patelea8a4b92009-09-17 23:04:48 +00001583 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584}
1585
Eli Friedmanfee02c62011-07-25 23:16:38 +00001586/// ParseScopeAndOrdering
1587/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1588/// else: ::=
1589///
1590/// This sets Scope and Ordering to the parsed values.
1591bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1592 AtomicOrdering &Ordering) {
1593 if (!isAtomic)
1594 return false;
1595
1596 Scope = CrossThread;
1597 if (EatIfPresent(lltok::kw_singlethread))
1598 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001599
1600 return ParseOrdering(Ordering);
1601}
1602
1603/// ParseOrdering
1604/// ::= AtomicOrdering
1605///
1606/// This sets Ordering to the parsed value.
1607bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001608 switch (Lex.getKind()) {
1609 default: return TokError("Expected ordering on atomic instruction");
1610 case lltok::kw_unordered: Ordering = Unordered; break;
1611 case lltok::kw_monotonic: Ordering = Monotonic; break;
1612 case lltok::kw_acquire: Ordering = Acquire; break;
1613 case lltok::kw_release: Ordering = Release; break;
1614 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1615 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1616 }
1617 Lex.Lex();
1618 return false;
1619}
1620
Charles Davisbe5557e2010-02-12 00:31:15 +00001621/// ParseOptionalStackAlignment
1622/// ::= /* empty */
1623/// ::= 'alignstack' '(' 4 ')'
1624bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1625 Alignment = 0;
1626 if (!EatIfPresent(lltok::kw_alignstack))
1627 return false;
1628 LocTy ParenLoc = Lex.getLoc();
1629 if (!EatIfPresent(lltok::lparen))
1630 return Error(ParenLoc, "expected '('");
1631 LocTy AlignLoc = Lex.getLoc();
1632 if (ParseUInt32(Alignment)) return true;
1633 ParenLoc = Lex.getLoc();
1634 if (!EatIfPresent(lltok::rparen))
1635 return Error(ParenLoc, "expected ')'");
1636 if (!isPowerOf2_32(Alignment))
1637 return Error(AlignLoc, "stack alignment is not a power of two");
1638 return false;
1639}
Devang Patelea8a4b92009-09-17 23:04:48 +00001640
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001641/// ParseIndexList - This parses the index list for an insert/extractvalue
1642/// instruction. This sets AteExtraComma in the case where we eat an extra
1643/// comma at the end of the line and find that it is followed by metadata.
1644/// Clients that don't allow metadata can call the version of this function that
1645/// only takes one argument.
1646///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001647/// ParseIndexList
1648/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001649///
1650bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1651 bool &AteExtraComma) {
1652 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001653
Chris Lattnerac161bf2009-01-02 07:01:27 +00001654 if (Lex.getKind() != lltok::comma)
1655 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001656
Chris Lattner3822f632009-01-02 08:05:26 +00001657 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001658 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001659 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001660 AteExtraComma = true;
1661 return false;
1662 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001663 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001664 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001665 Indices.push_back(Idx);
1666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001667
Chris Lattnerac161bf2009-01-02 07:01:27 +00001668 return false;
1669}
1670
1671//===----------------------------------------------------------------------===//
1672// Type Parsing.
1673//===----------------------------------------------------------------------===//
1674
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001676bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001677 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001678 switch (Lex.getKind()) {
1679 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001680 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001681 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001682 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001683 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001684 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001687 // Type ::= StructType
1688 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001689 return true;
1690 break;
1691 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001692 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001693 Lex.Lex(); // eat the lsquare.
1694 if (ParseArrayVectorType(Result, false))
1695 return true;
1696 break;
1697 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001698 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001699 Lex.Lex();
1700 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001701 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001702 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001703 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704 } else if (ParseArrayVectorType(Result, true))
1705 return true;
1706 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001707 case lltok::LocalVar: {
1708 // Type ::= %foo
1709 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
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, Lex.getStrVal());
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 Lattnerb1ed91f2011-07-09 17:41:24 +00001720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001721
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001722 case lltok::LocalVarID: {
1723 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001725
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001726 // If the type hasn't been defined yet, create a forward definition and
1727 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001728 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001729 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001730 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001731 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001733 Lex.Lex();
1734 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001735 }
1736 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001737
1738 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 while (1) {
1740 switch (Lex.getKind()) {
1741 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 default:
1743 if (!AllowVoid && Result->isVoidTy())
1744 return Error(TypeLoc, "void type only allowed for function results");
1745 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001746
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001748 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001749 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001750 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751 if (Result->isVoidTy())
1752 return TokError("pointers to void are invalid - use i8* instead");
1753 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001754 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001755 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756 Lex.Lex();
1757 break;
1758
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001759 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001762 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001764 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001765 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001766 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001767 unsigned AddrSpace;
1768 if (ParseOptionalAddrSpace(AddrSpace) ||
1769 ParseToken(lltok::star, "expected '*' in address space"))
1770 return true;
1771
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 break;
1774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001775
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1777 case lltok::lparen:
1778 if (ParseFunctionType(Result))
1779 return true;
1780 break;
1781 }
1782 }
1783}
1784
1785/// ParseParameterList
1786/// ::= '(' ')'
1787/// ::= '(' Arg (',' Arg)* ')'
1788/// Arg
1789/// ::= Type OptionalAttributes Value OptionalAttributes
1790bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001791 PerFunctionState &PFS, bool IsMustTailCall,
1792 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001793 if (ParseToken(lltok::lparen, "expected '(' in call"))
1794 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001795
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001796 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797 while (Lex.getKind() != lltok::rparen) {
1798 // If this isn't the first argument, we need a comma.
1799 if (!ArgList.empty() &&
1800 ParseToken(lltok::comma, "expected ',' in argument list"))
1801 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001802
Reid Kleckner83498642014-08-26 00:33:28 +00001803 // Parse an ellipsis if this is a musttail call in a variadic function.
1804 if (Lex.getKind() == lltok::dotdotdot) {
1805 const char *Msg = "unexpected ellipsis in argument list for ";
1806 if (!IsMustTailCall)
1807 return TokError(Twine(Msg) + "non-musttail call");
1808 if (!InVarArgsFunc)
1809 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1810 Lex.Lex(); // Lex the '...', it is purely for readability.
1811 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1812 }
1813
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 // Parse the argument.
1815 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001816 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001817 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001818 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001819 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001820 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001821
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001822 if (ArgTy->isMetadataTy()) {
1823 if (ParseMetadataAsValue(V, PFS))
1824 return true;
1825 } else {
1826 // Otherwise, handle normal operands.
1827 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1828 return true;
1829 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001830 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1831 AttrIndex++,
1832 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833 }
1834
Reid Kleckner83498642014-08-26 00:33:28 +00001835 if (IsMustTailCall && InVarArgsFunc)
1836 return TokError("expected '...' at end of argument list for musttail call "
1837 "in varargs function");
1838
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839 Lex.Lex(); // Lex the ')'.
1840 return false;
1841}
1842
1843
1844
Chris Lattner2ed06b42009-01-05 18:34:07 +00001845/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001846/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001847/// ::= '(' ArgTypeListI ')'
1848/// ArgTypeListI
1849/// ::= /*empty*/
1850/// ::= '...'
1851/// ::= ArgTypeList ',' '...'
1852/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001853///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001854bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1855 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 isVarArg = false;
1857 assert(Lex.getKind() == lltok::lparen);
1858 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001859
Chris Lattnerac161bf2009-01-02 07:01:27 +00001860 if (Lex.getKind() == lltok::rparen) {
1861 // empty
1862 } else if (Lex.getKind() == lltok::dotdotdot) {
1863 isVarArg = true;
1864 Lex.Lex();
1865 } else {
1866 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001867 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001868 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001869 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001870
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001871 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001872 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001873
Chris Lattnerfdd87902009-10-05 05:54:46 +00001874 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001875 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001876
Chris Lattnerdef19492011-06-17 06:36:20 +00001877 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001878 Name = Lex.getStrVal();
1879 Lex.Lex();
1880 }
Chris Lattner3822f632009-01-02 08:05:26 +00001881
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001882 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001883 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001884
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001885 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001886 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001887 AttributeSet::get(ArgTy->getContext(),
1888 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001889
Chris Lattner3822f632009-01-02 08:05:26 +00001890 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001891 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001892 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 break;
1895 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001896
Chris Lattnerac161bf2009-01-02 07:01:27 +00001897 // Otherwise must be an argument type.
1898 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001899 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001900
Chris Lattnerfdd87902009-10-05 05:54:46 +00001901 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001902 return Error(TypeLoc, "argument can not have void type");
1903
Chris Lattnerdef19492011-06-17 06:36:20 +00001904 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001905 Name = Lex.getStrVal();
1906 Lex.Lex();
1907 } else {
1908 Name = "";
1909 }
Chris Lattner3822f632009-01-02 08:05:26 +00001910
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001911 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001912 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001913
Bill Wendlingd079a442012-10-15 04:46:55 +00001914 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001915 AttributeSet::get(ArgTy->getContext(),
1916 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001917 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918 }
1919 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001920
Chris Lattner3822f632009-01-02 08:05:26 +00001921 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001923
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924/// ParseFunctionType
1925/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 assert(Lex.getKind() == lltok::lparen);
1928
Chris Lattnerce473c72009-01-05 08:04:33 +00001929 if (!FunctionType::isValidReturnType(Result))
1930 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001934 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001936
Chris Lattnerac161bf2009-01-02 07:01:27 +00001937 // Reject names on the arguments lists.
1938 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1939 if (!ArgList[i].Name.empty())
1940 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001941 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001942 return Error(ArgList[i].Loc,
1943 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001945
Jay Foadb804a2b2011-07-12 14:06:48 +00001946 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001947 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001948 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001950 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001951 return false;
1952}
1953
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001954/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1955/// other structs.
1956bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1957 SmallVector<Type*, 8> Elts;
1958 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960 Result = StructType::get(Context, Elts, Packed);
1961 return false;
1962}
1963
1964/// ParseStructDefinition - Parse a struct in a 'type' definition.
1965bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1966 std::pair<Type*, LocTy> &Entry,
1967 Type *&ResultTy) {
1968 // If the type was already defined, diagnose the redefinition.
1969 if (Entry.first && !Entry.second.isValid())
1970 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001971
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001972 // If we have opaque, just return without filling in the definition for the
1973 // struct. This counts as a definition as far as the .ll file goes.
1974 if (EatIfPresent(lltok::kw_opaque)) {
1975 // This type is being defined, so clear the location to indicate this.
1976 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001977
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001979 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001980 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981 ResultTy = Entry.first;
1982 return false;
1983 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001984
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001985 // If the type starts with '<', then it is either a packed struct or a vector.
1986 bool isPacked = EatIfPresent(lltok::less);
1987
1988 // If we don't have a struct, then we have a random type alias, which we
1989 // accept for compatibility with old files. These types are not allowed to be
1990 // forward referenced and not allowed to be recursive.
1991 if (Lex.getKind() != lltok::lbrace) {
1992 if (Entry.first)
1993 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001994
Craig Topper2617dcc2014-04-15 06:32:26 +00001995 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001996 if (isPacked)
1997 return ParseArrayVectorType(ResultTy, true);
1998 return ParseType(ResultTy);
1999 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002000
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 // This type is being defined, so clear the location to indicate this.
2002 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002003
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002004 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002005 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002006 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002007
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 SmallVector<Type*, 8> Body;
2011 if (ParseStructBody(Body) ||
2012 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2013 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002014
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 STy->setBody(Body, isPacked);
2016 ResultTy = STy;
2017 return false;
2018}
2019
2020
Chris Lattnerac161bf2009-01-02 07:01:27 +00002021/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002025/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026/// ::= '<' '{' Type (',' Type)* '}' '>'
2027bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 assert(Lex.getKind() == lltok::lbrace);
2029 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 // Handle the empty struct.
2032 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002034
Chris Lattnerf880ca22009-03-09 04:49:14 +00002035 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002036 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 if (ParseType(Ty)) return true;
2038 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002039
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002040 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002041 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002042
Chris Lattner3822f632009-01-02 08:05:26 +00002043 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002044 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002046
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002048 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002049
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002050 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002052
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054}
2055
2056/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2057/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059/// ::= '[' APSINTVAL 'x' Types ']'
2060/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2063 Lex.getAPSIntVal().getBitWidth() > 64)
2064 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002065
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 LocTy SizeLoc = Lex.getLoc();
2067 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002068 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002069
Chris Lattner3822f632009-01-02 08:05:26 +00002070 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2071 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072
2073 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002074 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002075 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002076
Chris Lattner3822f632009-01-02 08:05:26 +00002077 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2078 "expected end of sequential type"))
2079 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002080
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002082 if (Size == 0)
2083 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084 if ((unsigned)Size != Size)
2085 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002086 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002087 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002088 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002090 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002091 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002092 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 }
2094 return false;
2095}
2096
2097//===----------------------------------------------------------------------===//
2098// Function Semantic Analysis.
2099//===----------------------------------------------------------------------===//
2100
Chris Lattner3432c622009-10-28 03:39:23 +00002101LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2102 int functionNumber)
2103 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104
2105 // Insert unnamed arguments into the NumberedVals list.
2106 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2107 AI != E; ++AI)
2108 if (!AI->hasName())
2109 NumberedVals.push_back(AI);
2110}
2111
2112LLParser::PerFunctionState::~PerFunctionState() {
2113 // If there were any forward referenced non-basicblock values, delete them.
2114 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2115 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2116 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002117 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002118 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002120 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2124 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2125 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002126 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002127 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002128 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002129 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002130 }
2131}
2132
Chris Lattner3432c622009-10-28 03:39:23 +00002133bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 if (!ForwardRefVals.empty())
2135 return P.Error(ForwardRefVals.begin()->second.second,
2136 "use of undefined value '%" + ForwardRefVals.begin()->first +
2137 "'");
2138 if (!ForwardRefValIDs.empty())
2139 return P.Error(ForwardRefValIDs.begin()->second.second,
2140 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002141 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142 return false;
2143}
2144
2145
2146/// GetVal - Get a value with the specified name or ID, creating a
2147/// forward reference record if needed. This can return null if the value
2148/// exists but does not have the right type.
2149Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002150 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 // Look this name up in the normal function symbol table.
2152 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002153
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 // If this is a forward reference for the value, see if we already created a
2155 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002156 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2158 I = ForwardRefVals.find(Name);
2159 if (I != ForwardRefVals.end())
2160 Val = I->second.first;
2161 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002162
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 // If we have the value in the symbol table or fwd-ref table, return it.
2164 if (Val) {
2165 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002166 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 P.Error(Loc, "'%" + Name + "' is not a basic block");
2168 else
2169 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002170 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002171 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173
Chris Lattnerac161bf2009-01-02 07:01:27 +00002174 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002175 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002177 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002179
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 // Otherwise, create a new forward reference for this value and remember it.
2181 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002182 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002183 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 else
2185 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002186
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2188 return FwdVal;
2189}
2190
Chris Lattner229907c2011-07-18 04:54:35 +00002191Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 LocTy Loc) {
2193 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002194 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002195
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 // If this is a forward reference for the value, see if we already created a
2197 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002198 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002199 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2200 I = ForwardRefValIDs.find(ID);
2201 if (I != ForwardRefValIDs.end())
2202 Val = I->second.first;
2203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002204
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 // If we have the value in the symbol table or fwd-ref table, return it.
2206 if (Val) {
2207 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002208 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002209 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002211 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002212 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002213 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002215
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002216 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002218 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002219 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002220
Chris Lattnerac161bf2009-01-02 07:01:27 +00002221 // Otherwise, create a new forward reference for this value and remember it.
2222 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002223 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002224 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 else
2226 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2229 return FwdVal;
2230}
2231
2232/// SetInstName - After an instruction is parsed and inserted into its
2233/// basic block, this installs its name.
2234bool LLParser::PerFunctionState::SetInstName(int NameID,
2235 const std::string &NameStr,
2236 LocTy NameLoc, Instruction *Inst) {
2237 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002238 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 if (NameID != -1 || !NameStr.empty())
2240 return P.Error(NameLoc, "instructions returning void cannot have a name");
2241 return false;
2242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 // If this was a numbered instruction, verify that the instruction is the
2245 // expected value and resolve any forward references.
2246 if (NameStr.empty()) {
2247 // If neither a name nor an ID was specified, just use the next ID.
2248 if (NameID == -1)
2249 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 if (unsigned(NameID) != NumberedVals.size())
2252 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002253 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2256 ForwardRefValIDs.find(NameID);
2257 if (FI != ForwardRefValIDs.end()) {
2258 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002260 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002262 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 ForwardRefValIDs.erase(FI);
2264 }
2265
2266 NumberedVals.push_back(Inst);
2267 return false;
2268 }
2269
2270 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2271 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2272 FI = ForwardRefVals.find(NameStr);
2273 if (FI != ForwardRefVals.end()) {
2274 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002275 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002276 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002278 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279 ForwardRefVals.erase(FI);
2280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 // Set the name on the instruction.
2283 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002285 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002286 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287 NameStr + "'");
2288 return false;
2289}
2290
2291/// GetBB - Get a basic block with the specified name or ID, creating a
2292/// forward reference record if needed.
2293BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2294 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002295 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2296 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297}
2298
2299BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002300 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2301 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002302}
2303
2304/// DefineBB - Define the specified basic block, which is either named or
2305/// unnamed. If there is an error, this returns null otherwise it returns
2306/// the block being defined.
2307BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2308 LocTy Loc) {
2309 BasicBlock *BB;
2310 if (Name.empty())
2311 BB = GetBB(NumberedVals.size(), Loc);
2312 else
2313 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002314 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 // Move the block to the end of the function. Forward ref'd blocks are
2317 // inserted wherever they happen to be referenced.
2318 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002319
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 // Remove the block from forward ref sets.
2321 if (Name.empty()) {
2322 ForwardRefValIDs.erase(NumberedVals.size());
2323 NumberedVals.push_back(BB);
2324 } else {
2325 // BB forward references are already in the function symbol table.
2326 ForwardRefVals.erase(Name);
2327 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002328
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329 return BB;
2330}
2331
2332//===----------------------------------------------------------------------===//
2333// Constants.
2334//===----------------------------------------------------------------------===//
2335
2336/// ParseValID - Parse an abstract value that doesn't necessarily have a
2337/// type implied. For example, if we parse "4" we don't know what integer type
2338/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002339/// sanity. PFS is used to convert function-local operands of metadata (since
2340/// metadata operands are not just parsed here but also converted to values).
2341/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002342bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002343 ID.Loc = Lex.getLoc();
2344 switch (Lex.getKind()) {
2345 default: return TokError("expected value token");
2346 case lltok::GlobalID: // @42
2347 ID.UIntVal = Lex.getUIntVal();
2348 ID.Kind = ValID::t_GlobalID;
2349 break;
2350 case lltok::GlobalVar: // @foo
2351 ID.StrVal = Lex.getStrVal();
2352 ID.Kind = ValID::t_GlobalName;
2353 break;
2354 case lltok::LocalVarID: // %42
2355 ID.UIntVal = Lex.getUIntVal();
2356 ID.Kind = ValID::t_LocalID;
2357 break;
2358 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 ID.StrVal = Lex.getStrVal();
2360 ID.Kind = ValID::t_LocalName;
2361 break;
2362 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002363 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 ID.Kind = ValID::t_APSInt;
2365 break;
2366 case lltok::APFloat:
2367 ID.APFloatVal = Lex.getAPFloatVal();
2368 ID.Kind = ValID::t_APFloat;
2369 break;
2370 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002371 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 ID.Kind = ValID::t_Constant;
2373 break;
2374 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002375 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 ID.Kind = ValID::t_Constant;
2377 break;
2378 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2379 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2380 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 case lltok::lbrace: {
2383 // ValID ::= '{' ConstVector '}'
2384 Lex.Lex();
2385 SmallVector<Constant*, 16> Elts;
2386 if (ParseGlobalValueVector(Elts) ||
2387 ParseToken(lltok::rbrace, "expected end of struct constant"))
2388 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002389
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002390 ID.ConstantStructElts = new Constant*[Elts.size()];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002391 ID.UIntVal = Elts.size();
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002392 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002393 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 return false;
2395 }
2396 case lltok::less: {
2397 // ValID ::= '<' ConstVector '>' --> Vector.
2398 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2399 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002400 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 SmallVector<Constant*, 16> Elts;
2403 LocTy FirstEltLoc = Lex.getLoc();
2404 if (ParseGlobalValueVector(Elts) ||
2405 (isPackedStruct &&
2406 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2407 ParseToken(lltok::greater, "expected end of constant"))
2408 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002409
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 if (isPackedStruct) {
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002411 ID.ConstantStructElts = new Constant*[Elts.size()];
2412 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002413 ID.UIntVal = Elts.size();
2414 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 return false;
2416 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002417
Chris Lattnerac161bf2009-01-02 07:01:27 +00002418 if (Elts.empty())
2419 return Error(ID.Loc, "constant vector must not be empty");
2420
Duncan Sands9dff9be2010-02-15 16:12:20 +00002421 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002422 !Elts[0]->getType()->isFloatingPointTy() &&
2423 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002425 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002426
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 // Verify that all the vector elements have the same type.
2428 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2429 if (Elts[i]->getType() != Elts[0]->getType())
2430 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002431 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002432 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433
Chris Lattner69229312011-02-15 00:14:00 +00002434 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002435 ID.Kind = ValID::t_Constant;
2436 return false;
2437 }
2438 case lltok::lsquare: { // Array Constant
2439 Lex.Lex();
2440 SmallVector<Constant*, 16> Elts;
2441 LocTy FirstEltLoc = Lex.getLoc();
2442 if (ParseGlobalValueVector(Elts) ||
2443 ParseToken(lltok::rsquare, "expected end of array constant"))
2444 return true;
2445
2446 // Handle empty element.
2447 if (Elts.empty()) {
2448 // Use undef instead of an array because it's inconvenient to determine
2449 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002450 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451 return false;
2452 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453
Chris Lattnerac161bf2009-01-02 07:01:27 +00002454 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002455 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002456 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457
Owen Anderson4056ca92009-07-29 22:17:13 +00002458 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002459
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002461 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462 if (Elts[i]->getType() != Elts[0]->getType())
2463 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002464 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002465 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002466 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002467
Jay Foad83be3612011-06-22 09:24:39 +00002468 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 ID.Kind = ValID::t_Constant;
2470 return false;
2471 }
2472 case lltok::kw_c: // c "foo"
2473 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002474 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2475 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2477 ID.Kind = ValID::t_Constant;
2478 return false;
2479
2480 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002481 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2482 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002483 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484 Lex.Lex();
2485 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002486 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002487 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002488 ParseStringConstant(ID.StrVal) ||
2489 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 ParseToken(lltok::StringConstant, "expected constraint string"))
2491 return true;
2492 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002493 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002494 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495 ID.Kind = ValID::t_InlineAsm;
2496 return false;
2497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498
Chris Lattner3432c622009-10-28 03:39:23 +00002499 case lltok::kw_blockaddress: {
2500 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2501 Lex.Lex();
2502
2503 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002504
Chris Lattner3432c622009-10-28 03:39:23 +00002505 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2506 ParseValID(Fn) ||
2507 ParseToken(lltok::comma, "expected comma in block address expression")||
2508 ParseValID(Label) ||
2509 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2510 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002511
Chris Lattner3432c622009-10-28 03:39:23 +00002512 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2513 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002514 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002515 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002516
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002517 // Try to find the function (but skip it if it's forward-referenced).
2518 GlobalValue *GV = nullptr;
2519 if (Fn.Kind == ValID::t_GlobalID) {
2520 if (Fn.UIntVal < NumberedVals.size())
2521 GV = NumberedVals[Fn.UIntVal];
2522 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2523 GV = M->getNamedValue(Fn.StrVal);
2524 }
2525 Function *F = nullptr;
2526 if (GV) {
2527 // Confirm that it's actually a function with a definition.
2528 if (!isa<Function>(GV))
2529 return Error(Fn.Loc, "expected function name in blockaddress");
2530 F = cast<Function>(GV);
2531 if (F->isDeclaration())
2532 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2533 }
2534
2535 if (!F) {
2536 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002537 GlobalValue *&FwdRef =
2538 ForwardRefBlockAddresses.insert(std::make_pair(
2539 std::move(Fn),
2540 std::map<ValID, GlobalValue *>()))
2541 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2542 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002543 if (!FwdRef)
2544 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2545 GlobalValue::InternalLinkage, nullptr, "");
2546 ID.ConstantVal = FwdRef;
2547 ID.Kind = ValID::t_Constant;
2548 return false;
2549 }
2550
2551 // We found the function; now find the basic block. Don't use PFS, since we
2552 // might be inside a constant expression.
2553 BasicBlock *BB;
2554 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2555 if (Label.Kind == ValID::t_LocalID)
2556 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2557 else
2558 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2559 if (!BB)
2560 return Error(Label.Loc, "referenced value is not a basic block");
2561 } else {
2562 if (Label.Kind == ValID::t_LocalID)
2563 return Error(Label.Loc, "cannot take address of numeric label after "
2564 "the function is defined");
2565 BB = dyn_cast_or_null<BasicBlock>(
2566 F->getValueSymbolTable().lookup(Label.StrVal));
2567 if (!BB)
2568 return Error(Label.Loc, "referenced value is not a basic block");
2569 }
2570
2571 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002572 ID.Kind = ValID::t_Constant;
2573 return false;
2574 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002575
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 case lltok::kw_trunc:
2577 case lltok::kw_zext:
2578 case lltok::kw_sext:
2579 case lltok::kw_fptrunc:
2580 case lltok::kw_fpext:
2581 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002582 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002583 case lltok::kw_uitofp:
2584 case lltok::kw_sitofp:
2585 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002586 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002588 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002589 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002590 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591 Constant *SrcVal;
2592 Lex.Lex();
2593 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2594 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002595 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002596 ParseType(DestTy) ||
2597 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2598 return true;
2599 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2600 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002601 getTypeString(SrcVal->getType()) + "' to '" +
2602 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002603 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002604 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 ID.Kind = ValID::t_Constant;
2606 return false;
2607 }
2608 case lltok::kw_extractvalue: {
2609 Lex.Lex();
2610 Constant *Val;
2611 SmallVector<unsigned, 4> Indices;
2612 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2613 ParseGlobalTypeAndValue(Val) ||
2614 ParseIndexList(Indices) ||
2615 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2616 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002617
Chris Lattner392be582010-02-12 20:49:41 +00002618 if (!Val->getType()->isAggregateType())
2619 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002620 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002622 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 ID.Kind = ValID::t_Constant;
2624 return false;
2625 }
2626 case lltok::kw_insertvalue: {
2627 Lex.Lex();
2628 Constant *Val0, *Val1;
2629 SmallVector<unsigned, 4> Indices;
2630 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2631 ParseGlobalTypeAndValue(Val0) ||
2632 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2633 ParseGlobalTypeAndValue(Val1) ||
2634 ParseIndexList(Indices) ||
2635 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2636 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002637 if (!Val0->getType()->isAggregateType())
2638 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002639 Type *IndexedType =
2640 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2641 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002642 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002643 if (IndexedType != Val1->getType())
2644 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2645 getTypeString(Val1->getType()) +
2646 "' instead of '" + getTypeString(IndexedType) +
2647 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002648 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 ID.Kind = ValID::t_Constant;
2650 return false;
2651 }
2652 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002653 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 unsigned PredVal, Opc = Lex.getUIntVal();
2655 Constant *Val0, *Val1;
2656 Lex.Lex();
2657 if (ParseCmpPredicate(PredVal, Opc) ||
2658 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2659 ParseGlobalTypeAndValue(Val0) ||
2660 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2661 ParseGlobalTypeAndValue(Val1) ||
2662 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2663 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002664
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 if (Val0->getType() != Val1->getType())
2666 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002667
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002671 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002672 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002673 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002674 } else {
2675 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002676 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002677 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002678 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002679 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 }
2681 ID.Kind = ValID::t_Constant;
2682 return false;
2683 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002684
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 // Binary Operators.
2686 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002687 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002689 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002691 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 case lltok::kw_udiv:
2693 case lltok::kw_sdiv:
2694 case lltok::kw_fdiv:
2695 case lltok::kw_urem:
2696 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002697 case lltok::kw_frem:
2698 case lltok::kw_shl:
2699 case lltok::kw_lshr:
2700 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002701 bool NUW = false;
2702 bool NSW = false;
2703 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 unsigned Opc = Lex.getUIntVal();
2705 Constant *Val0, *Val1;
2706 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002707 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002708 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2709 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002710 if (EatIfPresent(lltok::kw_nuw))
2711 NUW = true;
2712 if (EatIfPresent(lltok::kw_nsw)) {
2713 NSW = true;
2714 if (EatIfPresent(lltok::kw_nuw))
2715 NUW = true;
2716 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002717 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2718 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002719 if (EatIfPresent(lltok::kw_exact))
2720 Exact = true;
2721 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2723 ParseGlobalTypeAndValue(Val0) ||
2724 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2725 ParseGlobalTypeAndValue(Val1) ||
2726 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2727 return true;
2728 if (Val0->getType() != Val1->getType())
2729 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002730 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002731 if (NUW)
2732 return Error(ModifierLoc, "nuw only applies to integer operations");
2733 if (NSW)
2734 return Error(ModifierLoc, "nsw only applies to integer operations");
2735 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002736 // Check that the type is valid for the operator.
2737 switch (Opc) {
2738 case Instruction::Add:
2739 case Instruction::Sub:
2740 case Instruction::Mul:
2741 case Instruction::UDiv:
2742 case Instruction::SDiv:
2743 case Instruction::URem:
2744 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002745 case Instruction::Shl:
2746 case Instruction::AShr:
2747 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002748 if (!Val0->getType()->isIntOrIntVectorTy())
2749 return Error(ID.Loc, "constexpr requires integer operands");
2750 break;
2751 case Instruction::FAdd:
2752 case Instruction::FSub:
2753 case Instruction::FMul:
2754 case Instruction::FDiv:
2755 case Instruction::FRem:
2756 if (!Val0->getType()->isFPOrFPVectorTy())
2757 return Error(ID.Loc, "constexpr requires fp operands");
2758 break;
2759 default: llvm_unreachable("Unknown binary operator!");
2760 }
Dan Gohman1b849082009-09-07 23:54:19 +00002761 unsigned Flags = 0;
2762 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2763 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002764 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002765 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002766 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002767 ID.Kind = ValID::t_Constant;
2768 return false;
2769 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002770
Chris Lattnerac161bf2009-01-02 07:01:27 +00002771 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 case lltok::kw_and:
2773 case lltok::kw_or:
2774 case lltok::kw_xor: {
2775 unsigned Opc = Lex.getUIntVal();
2776 Constant *Val0, *Val1;
2777 Lex.Lex();
2778 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2779 ParseGlobalTypeAndValue(Val0) ||
2780 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2781 ParseGlobalTypeAndValue(Val1) ||
2782 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2783 return true;
2784 if (Val0->getType() != Val1->getType())
2785 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002786 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 return Error(ID.Loc,
2788 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002789 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 ID.Kind = ValID::t_Constant;
2791 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792 }
2793
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794 case lltok::kw_getelementptr:
2795 case lltok::kw_shufflevector:
2796 case lltok::kw_insertelement:
2797 case lltok::kw_extractelement:
2798 case lltok::kw_select: {
2799 unsigned Opc = Lex.getUIntVal();
2800 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002801 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002802 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002803 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002804
Dan Gohman1639c392009-07-27 21:53:46 +00002805 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002806 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002807
2808 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2809 return true;
2810
2811 LocTy ExplicitTypeLoc = Lex.getLoc();
2812 if (Opc == Instruction::GetElementPtr) {
2813 if (ParseType(Ty) ||
2814 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2815 return true;
2816 }
2817
2818 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002819 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2820 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002821
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002823 if (Elts.size() == 0 ||
2824 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002825 return Error(ID.Loc, "base of getelementptr must be a pointer");
2826
2827 Type *BaseType = Elts[0]->getType();
2828 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002829 if (Ty != BasePointerType->getElementType())
2830 return Error(
2831 ExplicitTypeLoc,
2832 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002833
Jay Foaded8db7d2011-07-21 14:31:17 +00002834 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002835 for (Constant *Val : Indices) {
2836 Type *ValTy = Val->getType();
2837 if (!ValTy->getScalarType()->isIntegerTy())
2838 return Error(ID.Loc, "getelementptr index must be an integer");
2839 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2840 return Error(ID.Loc, "getelementptr index type missmatch");
2841 if (ValTy->isVectorTy()) {
2842 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2843 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2844 if (ValNumEl != PtrNumEl)
2845 return Error(
2846 ID.Loc,
2847 "getelementptr vector index has a wrong number of elements");
2848 }
2849 }
2850
Owen Andersone90f9922015-03-10 06:34:57 +00002851 SmallPtrSet<const Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00002852 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002853 return Error(ID.Loc, "base element of getelementptr must be sized");
2854
David Blaikie4a2e73b2015-04-02 18:55:32 +00002855 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002856 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002857 ID.ConstantVal =
2858 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002859 } else if (Opc == Instruction::Select) {
2860 if (Elts.size() != 3)
2861 return Error(ID.Loc, "expected three operands to select");
2862 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2863 Elts[2]))
2864 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002865 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002866 } else if (Opc == Instruction::ShuffleVector) {
2867 if (Elts.size() != 3)
2868 return Error(ID.Loc, "expected three operands to shufflevector");
2869 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2870 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002871 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002872 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 } else if (Opc == Instruction::ExtractElement) {
2874 if (Elts.size() != 2)
2875 return Error(ID.Loc, "expected two operands to extractelement");
2876 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2877 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002878 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 } else {
2880 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2881 if (Elts.size() != 3)
2882 return Error(ID.Loc, "expected three operands to insertelement");
2883 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2884 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002885 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002886 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002888
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 ID.Kind = ValID::t_Constant;
2890 return false;
2891 }
2892 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002893
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 Lex.Lex();
2895 return false;
2896}
2897
2898/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002899bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002900 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002902 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002903 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002904 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002905 if (V && !(C = dyn_cast<Constant>(V)))
2906 return Error(ID.Loc, "global values must be constants");
2907 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002908}
2909
Victor Hernandez9d75c962010-01-11 22:31:58 +00002910bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002911 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002912 return ParseType(Ty) ||
2913 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002914}
2915
Rafael Espindola83a362c2015-01-06 22:55:16 +00002916bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002917 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002918
2919 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002920 if (!EatIfPresent(lltok::kw_comdat))
2921 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002922
2923 if (EatIfPresent(lltok::lparen)) {
2924 if (Lex.getKind() != lltok::ComdatVar)
2925 return TokError("expected comdat variable");
2926 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2927 Lex.Lex();
2928 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2929 return true;
2930 } else {
2931 if (GlobalName.empty())
2932 return TokError("comdat cannot be unnamed");
2933 C = getComdat(GlobalName, KwLoc);
2934 }
2935
David Majnemerdad0a642014-06-27 18:19:56 +00002936 return false;
2937}
2938
Victor Hernandez9d75c962010-01-11 22:31:58 +00002939/// ParseGlobalValueVector
2940/// ::= /*empty*/
2941/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002942bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002943 // Empty list.
2944 if (Lex.getKind() == lltok::rbrace ||
2945 Lex.getKind() == lltok::rsquare ||
2946 Lex.getKind() == lltok::greater ||
2947 Lex.getKind() == lltok::rparen)
2948 return false;
2949
2950 Constant *C;
2951 if (ParseGlobalTypeAndValue(C)) return true;
2952 Elts.push_back(C);
2953
2954 while (EatIfPresent(lltok::comma)) {
2955 if (ParseGlobalTypeAndValue(C)) return true;
2956 Elts.push_back(C);
2957 }
2958
2959 return false;
2960}
2961
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002962bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002963 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002964 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002965 return true;
2966
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002967 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002968 return false;
2969}
2970
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002971/// MDNode:
2972/// ::= !{ ... }
2973/// ::= !7
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002974/// ::= !MDLocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002975bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002976 if (Lex.getKind() == lltok::MetadataVar)
2977 return ParseSpecializedMDNode(N);
2978
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002979 return ParseToken(lltok::exclaim, "expected '!' here") ||
2980 ParseMDNodeTail(N);
2981}
2982
2983bool LLParser::ParseMDNodeTail(MDNode *&N) {
2984 // !{ ... }
2985 if (Lex.getKind() == lltok::lbrace)
2986 return ParseMDTuple(N);
2987
2988 // !42
2989 return ParseMDNodeID(N);
2990}
2991
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002992namespace {
2993
2994/// Structure to represent an optional metadata field.
2995template <class FieldTy> struct MDFieldImpl {
2996 typedef MDFieldImpl ImplTy;
2997 FieldTy Val;
2998 bool Seen;
2999
3000 void assign(FieldTy Val) {
3001 Seen = true;
3002 this->Val = std::move(Val);
3003 }
3004
3005 explicit MDFieldImpl(FieldTy Default)
3006 : Val(std::move(Default)), Seen(false) {}
3007};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003008
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003009struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3010 uint64_t Max;
3011
3012 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3013 : ImplTy(Default), Max(Max) {}
3014};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003015struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003016 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003017};
3018struct ColumnField : public MDUnsignedField {
3019 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3020};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003021struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003022 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003023 DwarfTagField(dwarf::Tag DefaultTag)
3024 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003025};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003026struct DwarfAttEncodingField : public MDUnsignedField {
3027 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3028};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003029struct DwarfVirtualityField : public MDUnsignedField {
3030 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3031};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003032struct DwarfLangField : public MDUnsignedField {
3033 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3034};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003035
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003036struct DIFlagField : public MDUnsignedField {
3037 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3038};
3039
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003040struct MDSignedField : public MDFieldImpl<int64_t> {
3041 int64_t Min;
3042 int64_t Max;
3043
3044 MDSignedField(int64_t Default = 0)
3045 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3046 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3047 : ImplTy(Default), Min(Min), Max(Max) {}
3048};
3049
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003050struct MDBoolField : public MDFieldImpl<bool> {
3051 MDBoolField(bool Default = false) : ImplTy(Default) {}
3052};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003053struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003054 bool AllowNull;
3055
3056 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003057};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003058struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3059 MDConstant() : ImplTy(nullptr) {}
3060};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003061struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003062 bool AllowEmpty;
3063 MDStringField(bool AllowEmpty = true)
3064 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003065};
3066struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3067 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3068};
3069
3070} // end namespace
3071
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003072namespace llvm {
3073
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003074template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003075bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003076 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003077 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3078 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003079
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003080 auto &U = Lex.getAPSIntVal();
3081 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003082 return TokError("value for '" + Name + "' too large, limit is " +
3083 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003084 Result.assign(U.getZExtValue());
3085 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003086 Lex.Lex();
3087 return false;
3088}
3089
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003090template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003091bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3092 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3093}
3094template <>
3095bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3096 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3097}
3098
3099template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003100bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3101 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003102 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003103
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003104 if (Lex.getKind() != lltok::DwarfTag)
3105 return TokError("expected DWARF tag");
3106
3107 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3108 if (Tag == dwarf::DW_TAG_invalid)
3109 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003110 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003111
3112 Result.assign(Tag);
3113 Lex.Lex();
3114 return false;
3115}
3116
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003117template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003118bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3119 DwarfVirtualityField &Result) {
3120 if (Lex.getKind() == lltok::APSInt)
3121 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3122
3123 if (Lex.getKind() != lltok::DwarfVirtuality)
3124 return TokError("expected DWARF virtuality code");
3125
3126 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3127 if (!Virtuality)
3128 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3129 Lex.getStrVal() + "'");
3130 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3131 Result.assign(Virtuality);
3132 Lex.Lex();
3133 return false;
3134}
3135
3136template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003137bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3138 if (Lex.getKind() == lltok::APSInt)
3139 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3140
3141 if (Lex.getKind() != lltok::DwarfLang)
3142 return TokError("expected DWARF language");
3143
3144 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3145 if (!Lang)
3146 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3147 "'");
3148 assert(Lang <= Result.Max && "Expected valid DWARF language");
3149 Result.assign(Lang);
3150 Lex.Lex();
3151 return false;
3152}
3153
3154template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003155bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003156 DwarfAttEncodingField &Result) {
3157 if (Lex.getKind() == lltok::APSInt)
3158 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3159
3160 if (Lex.getKind() != lltok::DwarfAttEncoding)
3161 return TokError("expected DWARF type attribute encoding");
3162
3163 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3164 if (!Encoding)
3165 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3166 Lex.getStrVal() + "'");
3167 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3168 Result.assign(Encoding);
3169 Lex.Lex();
3170 return false;
3171}
3172
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003173/// DIFlagField
3174/// ::= uint32
3175/// ::= DIFlagVector
3176/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3177template <>
3178bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3179 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3180
3181 // Parser for a single flag.
3182 auto parseFlag = [&](unsigned &Val) {
3183 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3184 return ParseUInt32(Val);
3185
3186 if (Lex.getKind() != lltok::DIFlag)
3187 return TokError("expected debug info flag");
3188
Duncan P. N. Exon Smith5261e4b2015-04-07 01:21:40 +00003189 Val = DebugNode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003190 if (!Val)
3191 return TokError(Twine("invalid debug info flag flag '") +
3192 Lex.getStrVal() + "'");
3193 Lex.Lex();
3194 return false;
3195 };
3196
3197 // Parse the flags and combine them together.
3198 unsigned Combined = 0;
3199 do {
3200 unsigned Val;
3201 if (parseFlag(Val))
3202 return true;
3203 Combined |= Val;
3204 } while (EatIfPresent(lltok::bar));
3205
3206 Result.assign(Combined);
3207 return false;
3208}
3209
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003210template <>
3211bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003212 MDSignedField &Result) {
3213 if (Lex.getKind() != lltok::APSInt)
3214 return TokError("expected signed integer");
3215
3216 auto &S = Lex.getAPSIntVal();
3217 if (S < Result.Min)
3218 return TokError("value for '" + Name + "' too small, limit is " +
3219 Twine(Result.Min));
3220 if (S > Result.Max)
3221 return TokError("value for '" + Name + "' too large, limit is " +
3222 Twine(Result.Max));
3223 Result.assign(S.getExtValue());
3224 assert(Result.Val >= Result.Min && "Expected value in range");
3225 assert(Result.Val <= Result.Max && "Expected value in range");
3226 Lex.Lex();
3227 return false;
3228}
3229
3230template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003231bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3232 switch (Lex.getKind()) {
3233 default:
3234 return TokError("expected 'true' or 'false'");
3235 case lltok::kw_true:
3236 Result.assign(true);
3237 break;
3238 case lltok::kw_false:
3239 Result.assign(false);
3240 break;
3241 }
3242 Lex.Lex();
3243 return false;
3244}
3245
3246template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003247bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003248 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003249 if (!Result.AllowNull)
3250 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003251 Lex.Lex();
3252 Result.assign(nullptr);
3253 return false;
3254 }
3255
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003256 Metadata *MD;
3257 if (ParseMetadata(MD, nullptr))
3258 return true;
3259
3260 Result.assign(MD);
3261 return false;
3262}
3263
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003264template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003265bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3266 Metadata *MD;
3267 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3268 return true;
3269
3270 Result.assign(cast<ConstantAsMetadata>(MD));
3271 return false;
3272}
3273
3274template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003275bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003276 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003277 std::string S;
3278 if (ParseStringConstant(S))
3279 return true;
3280
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003281 if (!Result.AllowEmpty && S.empty())
3282 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3283
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003284 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003285 return false;
3286}
3287
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003288template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003289bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3290 SmallVector<Metadata *, 4> MDs;
3291 if (ParseMDNodeVector(MDs))
3292 return true;
3293
3294 Result.assign(std::move(MDs));
3295 return false;
3296}
3297
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003298} // end namespace llvm
3299
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003300template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003301bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003302 do {
3303 if (Lex.getKind() != lltok::LabelStr)
3304 return TokError("expected field label here");
3305
3306 if (parseField())
3307 return true;
3308 } while (EatIfPresent(lltok::comma));
3309
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003310 return false;
3311}
3312
3313template <class ParserTy>
3314bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3315 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3316 Lex.Lex();
3317
3318 if (ParseToken(lltok::lparen, "expected '(' here"))
3319 return true;
3320 if (Lex.getKind() != lltok::rparen)
3321 if (ParseMDFieldsImplBody(parseField))
3322 return true;
3323
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003324 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003325 return ParseToken(lltok::rparen, "expected ')' here");
3326}
3327
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003328template <class FieldTy>
3329bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3330 if (Result.Seen)
3331 return TokError("field '" + Name + "' cannot be specified more than once");
3332
3333 LocTy Loc = Lex.getLoc();
3334 Lex.Lex();
3335 return ParseMDField(Loc, Name, Result);
3336}
3337
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003338bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3339 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003340
3341#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003342 if (Lex.getStrVal() == #CLASS) \
3343 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003344#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003345
3346 return TokError("expected metadata type");
3347}
3348
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003349#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3350#define NOP_FIELD(NAME, TYPE, INIT)
3351#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3352 if (!NAME.Seen) \
3353 return Error(ClosingLoc, "missing required field '" #NAME "'");
3354#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003355 if (Lex.getStrVal() == #NAME) \
3356 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003357#define PARSE_MD_FIELDS() \
3358 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3359 do { \
3360 LocTy ClosingLoc; \
3361 if (ParseMDFieldsImpl([&]() -> bool { \
3362 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3363 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3364 }, ClosingLoc)) \
3365 return true; \
3366 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3367 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003368#define GET_OR_DISTINCT(CLASS, ARGS) \
3369 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003370
3371/// ParseMDLocationFields:
3372/// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3373bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003374#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003375 OPTIONAL(line, LineField, ); \
3376 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003377 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003378 OPTIONAL(inlinedAt, MDField, );
3379 PARSE_MD_FIELDS();
3380#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003381
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003382 Result = GET_OR_DISTINCT(
3383 MDLocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003384 return false;
3385}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003386
3387/// ParseGenericDebugNode:
3388/// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3389bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3390#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003391 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003392 OPTIONAL(header, MDStringField, ); \
3393 OPTIONAL(operands, MDFieldList, );
3394 PARSE_MD_FIELDS();
3395#undef VISIT_MD_FIELDS
3396
3397 Result = GET_OR_DISTINCT(GenericDebugNode,
3398 (Context, tag.Val, header.Val, operands.Val));
3399 return false;
3400}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003401
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003402/// ParseMDSubrange:
3403/// ::= !MDSubrange(count: 30, lowerBound: 2)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003404bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003406 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003407 OPTIONAL(lowerBound, MDSignedField, );
3408 PARSE_MD_FIELDS();
3409#undef VISIT_MD_FIELDS
3410
3411 Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3412 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003413}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003414
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003415/// ParseMDEnumerator:
3416/// ::= !MDEnumerator(value: 30, name: "SomeKind")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003417bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003418#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003419 REQUIRED(name, MDStringField, ); \
3420 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003421 PARSE_MD_FIELDS();
3422#undef VISIT_MD_FIELDS
3423
3424 Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3425 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003426}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003427
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003428/// ParseMDBasicType:
3429/// ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003430bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003431#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003432 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003433 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003434 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3435 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003436 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003437 PARSE_MD_FIELDS();
3438#undef VISIT_MD_FIELDS
3439
3440 Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3441 align.Val, encoding.Val));
3442 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003443}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003444
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003445/// ParseMDDerivedType:
3446/// ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3447/// line: 7, scope: !1, baseType: !2, size: 32,
3448/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003449bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003450#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3451 REQUIRED(tag, DwarfTagField, ); \
3452 OPTIONAL(name, MDStringField, ); \
3453 OPTIONAL(file, MDField, ); \
3454 OPTIONAL(line, LineField, ); \
3455 OPTIONAL(scope, MDField, ); \
3456 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003457 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3458 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3459 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003460 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003461 OPTIONAL(extraData, MDField, );
3462 PARSE_MD_FIELDS();
3463#undef VISIT_MD_FIELDS
3464
3465 Result = GET_OR_DISTINCT(MDDerivedType,
3466 (Context, tag.Val, name.Val, file.Val, line.Val,
3467 scope.Val, baseType.Val, size.Val, align.Val,
3468 offset.Val, flags.Val, extraData.Val));
3469 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003470}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003471
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003472bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003473#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3474 REQUIRED(tag, DwarfTagField, ); \
3475 OPTIONAL(name, MDStringField, ); \
3476 OPTIONAL(file, MDField, ); \
3477 OPTIONAL(line, LineField, ); \
3478 OPTIONAL(scope, MDField, ); \
3479 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003480 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3481 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3482 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003483 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003484 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003485 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003486 OPTIONAL(vtableHolder, MDField, ); \
3487 OPTIONAL(templateParams, MDField, ); \
3488 OPTIONAL(identifier, MDStringField, );
3489 PARSE_MD_FIELDS();
3490#undef VISIT_MD_FIELDS
3491
3492 Result = GET_OR_DISTINCT(
3493 MDCompositeType,
3494 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3495 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3496 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3497 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003498}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003499
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003500bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003501#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003502 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003503 REQUIRED(types, MDField, );
3504 PARSE_MD_FIELDS();
3505#undef VISIT_MD_FIELDS
3506
3507 Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3508 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003509}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003510
3511/// ParseMDFileType:
3512/// ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003513bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003514#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3515 REQUIRED(filename, MDStringField, ); \
3516 REQUIRED(directory, MDStringField, );
3517 PARSE_MD_FIELDS();
3518#undef VISIT_MD_FIELDS
3519
3520 Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3521 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003522}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003523
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003524/// ParseMDCompileUnit:
3525/// ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3526/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3527/// splitDebugFilename: "abc.debug", emissionKind: 1,
3528/// enums: !1, retainedTypes: !2, subprograms: !3,
3529/// globals: !4, imports: !5)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003530bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003531#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3532 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003533 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003534 OPTIONAL(producer, MDStringField, ); \
3535 OPTIONAL(isOptimized, MDBoolField, ); \
3536 OPTIONAL(flags, MDStringField, ); \
3537 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3538 OPTIONAL(splitDebugFilename, MDStringField, ); \
3539 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3540 OPTIONAL(enums, MDField, ); \
3541 OPTIONAL(retainedTypes, MDField, ); \
3542 OPTIONAL(subprograms, MDField, ); \
3543 OPTIONAL(globals, MDField, ); \
3544 OPTIONAL(imports, MDField, );
3545 PARSE_MD_FIELDS();
3546#undef VISIT_MD_FIELDS
3547
3548 Result = GET_OR_DISTINCT(MDCompileUnit,
3549 (Context, language.Val, file.Val, producer.Val,
3550 isOptimized.Val, flags.Val, runtimeVersion.Val,
3551 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3552 retainedTypes.Val, subprograms.Val, globals.Val,
3553 imports.Val));
3554 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003555}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003556
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003557/// ParseMDSubprogram:
3558/// ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3559/// file: !1, line: 7, type: !2, isLocal: false,
3560/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003561/// virtuality: DW_VIRTUALTIY_pure_virtual,
3562/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003563/// isOptimized: false, function: void ()* @_Z3foov,
3564/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003565bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003566#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3567 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003568 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003569 OPTIONAL(linkageName, MDStringField, ); \
3570 OPTIONAL(file, MDField, ); \
3571 OPTIONAL(line, LineField, ); \
3572 OPTIONAL(type, MDField, ); \
3573 OPTIONAL(isLocal, MDBoolField, ); \
3574 OPTIONAL(isDefinition, MDBoolField, (true)); \
3575 OPTIONAL(scopeLine, LineField, ); \
3576 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003577 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003578 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003579 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003580 OPTIONAL(isOptimized, MDBoolField, ); \
3581 OPTIONAL(function, MDConstant, ); \
3582 OPTIONAL(templateParams, MDField, ); \
3583 OPTIONAL(declaration, MDField, ); \
3584 OPTIONAL(variables, MDField, );
3585 PARSE_MD_FIELDS();
3586#undef VISIT_MD_FIELDS
3587
3588 Result = GET_OR_DISTINCT(
3589 MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3590 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3591 scopeLine.Val, containingType.Val, virtuality.Val,
3592 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3593 templateParams.Val, declaration.Val, variables.Val));
3594 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003595}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003596
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003597/// ParseMDLexicalBlock:
3598/// ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003599bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003600#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003601 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003602 OPTIONAL(file, MDField, ); \
3603 OPTIONAL(line, LineField, ); \
3604 OPTIONAL(column, ColumnField, );
3605 PARSE_MD_FIELDS();
3606#undef VISIT_MD_FIELDS
3607
3608 Result = GET_OR_DISTINCT(
3609 MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3610 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003611}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003612
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003613/// ParseMDLexicalBlockFile:
3614/// ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003615bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003616#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003617 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003618 OPTIONAL(file, MDField, ); \
3619 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3620 PARSE_MD_FIELDS();
3621#undef VISIT_MD_FIELDS
3622
3623 Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3624 (Context, scope.Val, file.Val, discriminator.Val));
3625 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003626}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003627
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003628/// ParseMDNamespace:
3629/// ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003630bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003631#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3632 REQUIRED(scope, MDField, ); \
3633 OPTIONAL(file, MDField, ); \
3634 OPTIONAL(name, MDStringField, ); \
3635 OPTIONAL(line, LineField, );
3636 PARSE_MD_FIELDS();
3637#undef VISIT_MD_FIELDS
3638
3639 Result = GET_OR_DISTINCT(MDNamespace,
3640 (Context, scope.Val, file.Val, name.Val, line.Val));
3641 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003642}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003643
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003644/// ParseMDTemplateTypeParameter:
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003645/// ::= !MDTemplateTypeParameter(name: "Ty", type: !1)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003646bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003647#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003648 OPTIONAL(name, MDStringField, ); \
3649 REQUIRED(type, MDField, );
3650 PARSE_MD_FIELDS();
3651#undef VISIT_MD_FIELDS
3652
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003653 Result =
3654 GET_OR_DISTINCT(MDTemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003655 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003656}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003657
3658/// ParseMDTemplateValueParameter:
3659/// ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003660/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003661bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003662#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003663 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003664 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003665 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003666 REQUIRED(value, MDField, );
3667 PARSE_MD_FIELDS();
3668#undef VISIT_MD_FIELDS
3669
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003670 Result = GET_OR_DISTINCT(MDTemplateValueParameter,
3671 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003672 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003673}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003674
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003675/// ParseMDGlobalVariable:
3676/// ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3677/// file: !1, line: 7, type: !2, isLocal: false,
3678/// isDefinition: true, variable: i32* @foo,
3679/// declaration: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003680bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003681#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003682 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003683 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003684 OPTIONAL(linkageName, MDStringField, ); \
3685 OPTIONAL(file, MDField, ); \
3686 OPTIONAL(line, LineField, ); \
3687 OPTIONAL(type, MDField, ); \
3688 OPTIONAL(isLocal, MDBoolField, ); \
3689 OPTIONAL(isDefinition, MDBoolField, (true)); \
3690 OPTIONAL(variable, MDConstant, ); \
3691 OPTIONAL(declaration, MDField, );
3692 PARSE_MD_FIELDS();
3693#undef VISIT_MD_FIELDS
3694
3695 Result = GET_OR_DISTINCT(MDGlobalVariable,
3696 (Context, scope.Val, name.Val, linkageName.Val,
3697 file.Val, line.Val, type.Val, isLocal.Val,
3698 isDefinition.Val, variable.Val, declaration.Val));
3699 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003700}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003701
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003702/// ParseMDLocalVariable:
3703/// ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003704/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003705bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003706#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3707 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003708 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003709 OPTIONAL(name, MDStringField, ); \
3710 OPTIONAL(file, MDField, ); \
3711 OPTIONAL(line, LineField, ); \
3712 OPTIONAL(type, MDField, ); \
3713 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003714 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003715 PARSE_MD_FIELDS();
3716#undef VISIT_MD_FIELDS
3717
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003718 Result = GET_OR_DISTINCT(MDLocalVariable,
3719 (Context, tag.Val, scope.Val, name.Val, file.Val,
3720 line.Val, type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003721 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003722}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003723
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003724/// ParseMDExpression:
3725/// ::= !MDExpression(0, 7, -1)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003726bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003727 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3728 Lex.Lex();
3729
3730 if (ParseToken(lltok::lparen, "expected '(' here"))
3731 return true;
3732
3733 SmallVector<uint64_t, 8> Elements;
3734 if (Lex.getKind() != lltok::rparen)
3735 do {
3736 if (Lex.getKind() == lltok::DwarfOp) {
3737 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3738 Lex.Lex();
3739 Elements.push_back(Op);
3740 continue;
3741 }
3742 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3743 }
3744
3745 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3746 return TokError("expected unsigned integer");
3747
3748 auto &U = Lex.getAPSIntVal();
3749 if (U.ugt(UINT64_MAX))
3750 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3751 Elements.push_back(U.getZExtValue());
3752 Lex.Lex();
3753 } while (EatIfPresent(lltok::comma));
3754
3755 if (ParseToken(lltok::rparen, "expected ')' here"))
3756 return true;
3757
3758 Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3759 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003760}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003761
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003762/// ParseMDObjCProperty:
3763/// ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3764/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003765bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003766#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003767 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003768 OPTIONAL(file, MDField, ); \
3769 OPTIONAL(line, LineField, ); \
3770 OPTIONAL(setter, MDStringField, ); \
3771 OPTIONAL(getter, MDStringField, ); \
3772 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3773 OPTIONAL(type, MDField, );
3774 PARSE_MD_FIELDS();
3775#undef VISIT_MD_FIELDS
3776
3777 Result = GET_OR_DISTINCT(MDObjCProperty,
3778 (Context, name.Val, file.Val, line.Val, setter.Val,
3779 getter.Val, attributes.Val, type.Val));
3780 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003781}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003782
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003783/// ParseMDImportedEntity:
3784/// ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3785/// line: 7, name: "foo")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003786bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003787#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3788 REQUIRED(tag, DwarfTagField, ); \
3789 REQUIRED(scope, MDField, ); \
3790 OPTIONAL(entity, MDField, ); \
3791 OPTIONAL(line, LineField, ); \
3792 OPTIONAL(name, MDStringField, );
3793 PARSE_MD_FIELDS();
3794#undef VISIT_MD_FIELDS
3795
3796 Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3797 entity.Val, line.Val, name.Val));
3798 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003799}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003800
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003801#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003802#undef NOP_FIELD
3803#undef REQUIRE_FIELD
3804#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003805
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003806/// ParseMetadataAsValue
3807/// ::= metadata i32 %local
3808/// ::= metadata i32 @global
3809/// ::= metadata i32 7
3810/// ::= metadata !0
3811/// ::= metadata !{...}
3812/// ::= metadata !"string"
3813bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3814 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003815 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003816 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003817 return true;
3818
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003819 V = MetadataAsValue::get(Context, MD);
3820 return false;
3821}
3822
3823/// ParseValueAsMetadata
3824/// ::= i32 %local
3825/// ::= i32 @global
3826/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003827bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3828 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003829 Type *Ty;
3830 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003831 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003832 return true;
3833 if (Ty->isMetadataTy())
3834 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3835
3836 Value *V;
3837 if (ParseValue(Ty, V, PFS))
3838 return true;
3839
3840 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003841 return false;
3842}
3843
3844/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003845/// ::= i32 %local
3846/// ::= i32 @global
3847/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003848/// ::= !42
3849/// ::= !{...}
3850/// ::= !"string"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003851/// ::= !MDLocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003852bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003853 if (Lex.getKind() == lltok::MetadataVar) {
3854 MDNode *N;
3855 if (ParseSpecializedMDNode(N))
3856 return true;
3857 MD = N;
3858 return false;
3859 }
3860
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003861 // ValueAsMetadata:
3862 // <type> <value>
3863 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003864 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003865
3866 // '!'.
3867 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3868 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003869
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003870 // MDString:
3871 // ::= '!' STRINGCONSTANT
3872 if (Lex.getKind() == lltok::StringConstant) {
3873 MDString *S;
3874 if (ParseMDString(S))
3875 return true;
3876 MD = S;
3877 return false;
3878 }
3879
Dan Gohman8939ba332010-07-14 18:26:50 +00003880 // MDNode:
3881 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003882 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003883 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003884 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003885 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003886 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003887 return false;
3888}
3889
Victor Hernandez9d75c962010-01-11 22:31:58 +00003890
3891//===----------------------------------------------------------------------===//
3892// Function Parsing.
3893//===----------------------------------------------------------------------===//
3894
Chris Lattner229907c2011-07-18 04:54:35 +00003895bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003896 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003897 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003898 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003899
Chris Lattnerac161bf2009-01-02 07:01:27 +00003900 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003901 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003902 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3903 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003904 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003905 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003906 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3907 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003908 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003909 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003910 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003911 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003912 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003913 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3914 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003915 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003916 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003917 return false;
3918 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003919 case ValID::t_GlobalName:
3920 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003921 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003922 case ValID::t_GlobalID:
3923 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003924 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003925 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003926 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003927 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003928 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003929 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003930 return false;
3931 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003932 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003933 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3934 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003935
Dan Gohman518cda42011-12-17 00:04:22 +00003936 // The lexer has no type info, so builds all half, float, and double FP
3937 // constants as double. Fix this here. Long double does not need this.
3938 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003939 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003940 if (Ty->isHalfTy())
3941 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3942 &Ignored);
3943 else if (Ty->isFloatTy())
3944 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3945 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003946 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003947 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003948
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003949 if (V->getType() != Ty)
3950 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003951 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003952
Chris Lattnerac161bf2009-01-02 07:01:27 +00003953 return false;
3954 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003955 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003956 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003957 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003958 return false;
3959 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003960 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003961 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003962 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003963 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003964 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003965 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003966 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003967 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003968 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003969 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003970 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003971 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003972 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003973 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003974 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003975 return false;
3976 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003977 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003979
Chris Lattnerac161bf2009-01-02 07:01:27 +00003980 V = ID.ConstantVal;
3981 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003982 case ValID::t_ConstantStruct:
3983 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003984 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003985 if (ST->getNumElements() != ID.UIntVal)
3986 return Error(ID.Loc,
3987 "initializer with struct type has wrong # elements");
3988 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3989 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003990
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003991 // Verify that the elements are compatible with the structtype.
3992 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3993 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3994 return Error(ID.Loc, "element " + Twine(i) +
3995 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003996
Reid Kleckner2ae03e12015-03-04 18:31:10 +00003997 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3998 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003999 } else
4000 return Error(ID.Loc, "constant expression type mismatch");
4001 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004002 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004003 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004004}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004005
Chris Lattner229907c2011-07-18 04:54:35 +00004006bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004007 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004008 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004009 return ParseValID(ID, PFS) ||
4010 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004011}
4012
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004013bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004014 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004015 return ParseType(Ty) ||
4016 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004017}
4018
Chris Lattner3ed871f2009-10-27 19:13:16 +00004019bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4020 PerFunctionState &PFS) {
4021 Value *V;
4022 Loc = Lex.getLoc();
4023 if (ParseTypeAndValue(V, PFS)) return true;
4024 if (!isa<BasicBlock>(V))
4025 return Error(Loc, "expected a basic block");
4026 BB = cast<BasicBlock>(V);
4027 return false;
4028}
4029
4030
Chris Lattnerac161bf2009-01-02 07:01:27 +00004031/// FunctionHeader
4032/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004033/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004034/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00004035bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4036 // Parse the linkage.
4037 LocTy LinkageLoc = Lex.getLoc();
4038 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004039
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004040 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004041 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004042 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004043 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004044 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004045 LocTy RetTypeLoc = Lex.getLoc();
4046 if (ParseOptionalLinkage(Linkage) ||
4047 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004048 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004049 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004050 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004051 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004052 return true;
4053
4054 // Verify that the linkage is ok.
4055 switch ((GlobalValue::LinkageTypes)Linkage) {
4056 case GlobalValue::ExternalLinkage:
4057 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004058 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004059 if (isDefine)
4060 return Error(LinkageLoc, "invalid linkage for function definition");
4061 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004062 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004063 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004064 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004065 case GlobalValue::LinkOnceAnyLinkage:
4066 case GlobalValue::LinkOnceODRLinkage:
4067 case GlobalValue::WeakAnyLinkage:
4068 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004069 if (!isDefine)
4070 return Error(LinkageLoc, "invalid linkage for function declaration");
4071 break;
4072 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004073 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004074 return Error(LinkageLoc, "invalid function linkage type");
4075 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004076
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004077 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4078 return Error(LinkageLoc,
4079 "symbol with local linkage must have default visibility");
4080
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004081 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004082 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004083
Chris Lattnerac161bf2009-01-02 07:01:27 +00004084 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004085
4086 std::string FunctionName;
4087 if (Lex.getKind() == lltok::GlobalVar) {
4088 FunctionName = Lex.getStrVal();
4089 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4090 unsigned NameID = Lex.getUIntVal();
4091
4092 if (NameID != NumberedVals.size())
4093 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004094 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004095 } else {
4096 return TokError("expected function name");
4097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004098
Chris Lattner3822f632009-01-02 08:05:26 +00004099 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004100
Chris Lattner3822f632009-01-02 08:05:26 +00004101 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004102 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004104 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004105 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004106 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004107 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004108 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004109 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004110 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004111 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004112 bool UnnamedAddr;
4113 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004114 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004115 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004116 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004118 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004119 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4120 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004121 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004122 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004123 (EatIfPresent(lltok::kw_section) &&
4124 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004125 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004126 ParseOptionalAlignment(Alignment) ||
4127 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004128 ParseStringConstant(GC)) ||
4129 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004130 ParseGlobalTypeAndValue(Prefix)) ||
4131 (EatIfPresent(lltok::kw_prologue) &&
4132 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00004133 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004134
Michael Gottesman41748d72013-06-27 00:25:01 +00004135 if (FuncAttrs.contains(Attribute::Builtin))
4136 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004137
Chris Lattnerac161bf2009-01-02 07:01:27 +00004138 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004139 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004140 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004141 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004142 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004143
Chris Lattnerac161bf2009-01-02 07:01:27 +00004144 // Okay, if we got here, the function is syntactically valid. Convert types
4145 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004146 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004147 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004148
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004149 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004150 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4151 AttributeSet::ReturnIndex,
4152 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004153
Chris Lattnerac161bf2009-01-02 07:01:27 +00004154 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004155 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004156 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4157 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004158 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4159 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004160 }
4161
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004162 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004163 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4164 AttributeSet::FunctionIndex,
4165 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004166
Bill Wendlinge94d8432012-12-07 23:16:57 +00004167 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004168
Bill Wendling749a43d2012-12-30 13:50:49 +00004169 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004170 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4171
Chris Lattner229907c2011-07-18 04:54:35 +00004172 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004173 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004174 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004175
Craig Topper2617dcc2014-04-15 06:32:26 +00004176 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004177 if (!FunctionName.empty()) {
4178 // If this was a definition of a forward reference, remove the definition
4179 // from the forward reference table and fill in the forward ref.
4180 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4181 ForwardRefVals.find(FunctionName);
4182 if (FRVI != ForwardRefVals.end()) {
4183 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004184 if (!Fn)
4185 return Error(FRVI->second.second, "invalid forward reference to "
4186 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004187 if (Fn->getType() != PFT)
4188 return Error(FRVI->second.second, "invalid forward reference to "
4189 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004190
Chris Lattnerac161bf2009-01-02 07:01:27 +00004191 ForwardRefVals.erase(FRVI);
4192 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004193 // Reject redefinitions.
4194 return Error(NameLoc, "invalid redefinition of function '" +
4195 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004196 } else if (M->getNamedValue(FunctionName)) {
4197 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004198 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004199
Dan Gohman399d6ae2009-08-29 23:37:49 +00004200 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004201 // If this is a definition of a forward referenced function, make sure the
4202 // types agree.
4203 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4204 = ForwardRefValIDs.find(NumberedVals.size());
4205 if (I != ForwardRefValIDs.end()) {
4206 Fn = cast<Function>(I->second.first);
4207 if (Fn->getType() != PFT)
4208 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004209 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 ForwardRefValIDs.erase(I);
4211 }
4212 }
4213
Craig Topper2617dcc2014-04-15 06:32:26 +00004214 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004215 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4216 else // Move the forward-reference to the correct spot in the module.
4217 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4218
4219 if (FunctionName.empty())
4220 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004221
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4223 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004224 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004225 Fn->setCallingConv(CC);
4226 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004227 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004228 Fn->setAlignment(Alignment);
4229 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004230 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004231 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004232 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004233 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004234 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004235
Chris Lattnerac161bf2009-01-02 07:01:27 +00004236 // Add all of the arguments we parsed to the function.
4237 Function::arg_iterator ArgIt = Fn->arg_begin();
4238 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4239 // If the argument has a name, insert it into the argument symbol table.
4240 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004241
Chris Lattnerac161bf2009-01-02 07:01:27 +00004242 // Set the name, if it conflicted, it will be auto-renamed.
4243 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004244
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004245 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4247 ArgList[i].Name + "'");
4248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004249
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004250 if (isDefine)
4251 return false;
4252
Robin Morisset039781e2014-08-29 21:53:01 +00004253 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004254 ValID ID;
4255 if (FunctionName.empty()) {
4256 ID.Kind = ValID::t_GlobalID;
4257 ID.UIntVal = NumberedVals.size() - 1;
4258 } else {
4259 ID.Kind = ValID::t_GlobalName;
4260 ID.StrVal = FunctionName;
4261 }
4262 auto Blocks = ForwardRefBlockAddresses.find(ID);
4263 if (Blocks != ForwardRefBlockAddresses.end())
4264 return Error(Blocks->first.Loc,
4265 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 return false;
4267}
4268
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004269bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4270 ValID ID;
4271 if (FunctionNumber == -1) {
4272 ID.Kind = ValID::t_GlobalName;
4273 ID.StrVal = F.getName();
4274 } else {
4275 ID.Kind = ValID::t_GlobalID;
4276 ID.UIntVal = FunctionNumber;
4277 }
4278
4279 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4280 if (Blocks == P.ForwardRefBlockAddresses.end())
4281 return false;
4282
4283 for (const auto &I : Blocks->second) {
4284 const ValID &BBID = I.first;
4285 GlobalValue *GV = I.second;
4286
4287 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4288 "Expected local id or name");
4289 BasicBlock *BB;
4290 if (BBID.Kind == ValID::t_LocalName)
4291 BB = GetBB(BBID.StrVal, BBID.Loc);
4292 else
4293 BB = GetBB(BBID.UIntVal, BBID.Loc);
4294 if (!BB)
4295 return P.Error(BBID.Loc, "referenced value is not a basic block");
4296
4297 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4298 GV->eraseFromParent();
4299 }
4300
4301 P.ForwardRefBlockAddresses.erase(Blocks);
4302 return false;
4303}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304
4305/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004306/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004307bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004308 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004309 return TokError("expected '{' in function body");
4310 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004311
Chris Lattner3432c622009-10-28 03:39:23 +00004312 int FunctionNumber = -1;
4313 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004314
Chris Lattner3432c622009-10-28 03:39:23 +00004315 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004316
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004317 // Resolve block addresses and allow basic blocks to be forward-declared
4318 // within this function.
4319 if (PFS.resolveForwardRefBlockAddresses())
4320 return true;
4321 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4322
Chris Lattnerbbddd962010-01-09 19:20:07 +00004323 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004324 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004325 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004326
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004327 while (Lex.getKind() != lltok::rbrace &&
4328 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004329 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004330
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004331 while (Lex.getKind() != lltok::rbrace)
4332 if (ParseUseListOrder(&PFS))
4333 return true;
4334
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335 // Eat the }.
4336 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004337
Chris Lattnerac161bf2009-01-02 07:01:27 +00004338 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004339 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004340}
4341
4342/// ParseBasicBlock
4343/// ::= LabelStr? Instruction*
4344bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4345 // If this basic block starts out with a name, remember it.
4346 std::string Name;
4347 LocTy NameLoc = Lex.getLoc();
4348 if (Lex.getKind() == lltok::LabelStr) {
4349 Name = Lex.getStrVal();
4350 Lex.Lex();
4351 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004352
Chris Lattnerac161bf2009-01-02 07:01:27 +00004353 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004354 if (!BB)
4355 return Error(NameLoc,
4356 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004357
Chris Lattnerac161bf2009-01-02 07:01:27 +00004358 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004359
Chris Lattnerac161bf2009-01-02 07:01:27 +00004360 // Parse the instructions in this block until we get a terminator.
4361 Instruction *Inst;
4362 do {
4363 // This instruction may have three possibilities for a name: a) none
4364 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4365 LocTy NameLoc = Lex.getLoc();
4366 int NameID = -1;
4367 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004368
Chris Lattnerac161bf2009-01-02 07:01:27 +00004369 if (Lex.getKind() == lltok::LocalVarID) {
4370 NameID = Lex.getUIntVal();
4371 Lex.Lex();
4372 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4373 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004374 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004375 NameStr = Lex.getStrVal();
4376 Lex.Lex();
4377 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4378 return true;
4379 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004380
Chris Lattner77b89dc2009-12-30 05:23:43 +00004381 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004382 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004383 case InstError: return true;
4384 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004385 BB->getInstList().push_back(Inst);
4386
Chris Lattner77b89dc2009-12-30 05:23:43 +00004387 // With a normal result, we check to see if the instruction is followed by
4388 // a comma and metadata.
4389 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00004390 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004391 return true;
4392 break;
4393 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004394 BB->getInstList().push_back(Inst);
4395
Chris Lattner77b89dc2009-12-30 05:23:43 +00004396 // If the instruction parser ate an extra comma at the end of it, it
4397 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00004398 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004399 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004400 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004401 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004402
Chris Lattnerac161bf2009-01-02 07:01:27 +00004403 // Set the name on the instruction.
4404 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4405 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004406
Chris Lattnerac161bf2009-01-02 07:01:27 +00004407 return false;
4408}
4409
4410//===----------------------------------------------------------------------===//
4411// Instruction Parsing.
4412//===----------------------------------------------------------------------===//
4413
4414/// ParseInstruction - Parse one of the many different instructions.
4415///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004416int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4417 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004418 lltok::Kind Token = Lex.getKind();
4419 if (Token == lltok::Eof)
4420 return TokError("found end of file when expecting more instructions");
4421 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004422 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004423 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004424
Chris Lattnerac161bf2009-01-02 07:01:27 +00004425 switch (Token) {
4426 default: return Error(Loc, "expected instruction opcode");
4427 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004428 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004429 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4430 case lltok::kw_br: return ParseBr(Inst, PFS);
4431 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004432 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004433 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004434 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004435 // Binary Operators.
4436 case lltok::kw_add:
4437 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004438 case lltok::kw_mul:
4439 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004440 bool NUW = EatIfPresent(lltok::kw_nuw);
4441 bool NSW = EatIfPresent(lltok::kw_nsw);
4442 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004443
Chris Lattnera676c0f2011-02-07 16:40:21 +00004444 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004445
Chris Lattnera676c0f2011-02-07 16:40:21 +00004446 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4447 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4448 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004449 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004450 case lltok::kw_fadd:
4451 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004452 case lltok::kw_fmul:
4453 case lltok::kw_fdiv:
4454 case lltok::kw_frem: {
4455 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4456 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4457 if (Res != 0)
4458 return Res;
4459 if (FMF.any())
4460 Inst->setFastMathFlags(FMF);
4461 return 0;
4462 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004463
Chris Lattner35315d02011-02-06 21:44:57 +00004464 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004465 case lltok::kw_udiv:
4466 case lltok::kw_lshr:
4467 case lltok::kw_ashr: {
4468 bool Exact = EatIfPresent(lltok::kw_exact);
4469
4470 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4471 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4472 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004473 }
4474
Chris Lattnerac161bf2009-01-02 07:01:27 +00004475 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004476 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004477 case lltok::kw_and:
4478 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004479 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004480 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004481 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 // Casts.
4483 case lltok::kw_trunc:
4484 case lltok::kw_zext:
4485 case lltok::kw_sext:
4486 case lltok::kw_fptrunc:
4487 case lltok::kw_fpext:
4488 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004489 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 case lltok::kw_uitofp:
4491 case lltok::kw_sitofp:
4492 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004493 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004495 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004496 // Other.
4497 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004498 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4500 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4501 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4502 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004503 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004504 // Call.
4505 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4506 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4507 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004508 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004509 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004510 case lltok::kw_load: return ParseLoad(Inst, PFS);
4511 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004512 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4513 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004514 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4516 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4517 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4518 }
4519}
4520
4521/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4522bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004523 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004525 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4527 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4528 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4529 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4530 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4531 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4532 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4533 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4534 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4535 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4536 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4537 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4538 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4539 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4540 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4541 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4542 }
4543 } else {
4544 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004545 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4547 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4548 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4549 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4550 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4551 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4552 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4553 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4554 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4555 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4556 }
4557 }
4558 Lex.Lex();
4559 return false;
4560}
4561
4562//===----------------------------------------------------------------------===//
4563// Terminator Instructions.
4564//===----------------------------------------------------------------------===//
4565
4566/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004567/// ::= 'ret' void (',' !dbg, !1)*
4568/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004569bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004570 PerFunctionState &PFS) {
4571 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004572 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004573 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004574
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004575 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004576
Chris Lattnerfdd87902009-10-05 05:54:46 +00004577 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004578 if (!ResType->isVoidTy())
4579 return Error(TypeLoc, "value doesn't match function result type '" +
4580 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004581
Owen Anderson55f1c092009-08-13 21:58:54 +00004582 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004583 return false;
4584 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004585
Chris Lattnerac161bf2009-01-02 07:01:27 +00004586 Value *RV;
4587 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004588
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004589 if (ResType != RV->getType())
4590 return Error(TypeLoc, "value doesn't match function result type '" +
4591 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004592
Owen Anderson55f1c092009-08-13 21:58:54 +00004593 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004594 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004595}
4596
4597
4598/// ParseBr
4599/// ::= 'br' TypeAndValue
4600/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4601bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4602 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004603 Value *Op0;
4604 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004606
Chris Lattnerac161bf2009-01-02 07:01:27 +00004607 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4608 Inst = BranchInst::Create(BB);
4609 return false;
4610 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004611
Owen Anderson55f1c092009-08-13 21:58:54 +00004612 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004613 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004614
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004616 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004617 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004618 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004619 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004620
Chris Lattner3ed871f2009-10-27 19:13:16 +00004621 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622 return false;
4623}
4624
4625/// ParseSwitch
4626/// Instruction
4627/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4628/// JumpTable
4629/// ::= (TypeAndValue ',' TypeAndValue)*
4630bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4631 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004632 Value *Cond;
4633 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4635 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004636 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4638 return true;
4639
Duncan Sands19d0b472010-02-16 11:11:14 +00004640 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004641 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004642
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 // Parse the jump table pairs.
4644 SmallPtrSet<Value*, 32> SeenCases;
4645 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4646 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004647 Value *Constant;
4648 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004649
Chris Lattnerac161bf2009-01-02 07:01:27 +00004650 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4651 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004652 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004653 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004654
David Blaikie70573dc2014-11-19 07:49:26 +00004655 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 return Error(CondLoc, "duplicate case value in switch");
4657 if (!isa<ConstantInt>(Constant))
4658 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004659
Chris Lattner3ed871f2009-10-27 19:13:16 +00004660 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004662
Chris Lattnerac161bf2009-01-02 07:01:27 +00004663 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004664
Chris Lattner3ed871f2009-10-27 19:13:16 +00004665 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004666 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4667 SI->addCase(Table[i].first, Table[i].second);
4668 Inst = SI;
4669 return false;
4670}
4671
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004672/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004673/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004674/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4675bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004676 LocTy AddrLoc;
4677 Value *Address;
4678 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004679 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4680 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004681 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004682
Duncan Sands19d0b472010-02-16 11:11:14 +00004683 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004684 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004685
Chris Lattner3ed871f2009-10-27 19:13:16 +00004686 // Parse the destination list.
4687 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004688
Chris Lattner3ed871f2009-10-27 19:13:16 +00004689 if (Lex.getKind() != lltok::rsquare) {
4690 BasicBlock *DestBB;
4691 if (ParseTypeAndBasicBlock(DestBB, PFS))
4692 return true;
4693 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004694
Chris Lattner3ed871f2009-10-27 19:13:16 +00004695 while (EatIfPresent(lltok::comma)) {
4696 if (ParseTypeAndBasicBlock(DestBB, PFS))
4697 return true;
4698 DestList.push_back(DestBB);
4699 }
4700 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004701
Chris Lattner3ed871f2009-10-27 19:13:16 +00004702 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4703 return true;
4704
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004705 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004706 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4707 IBI->addDestination(DestList[i]);
4708 Inst = IBI;
4709 return false;
4710}
4711
4712
Chris Lattnerac161bf2009-01-02 07:01:27 +00004713/// ParseInvoke
4714/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4715/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4716bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4717 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004718 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004719 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004720 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004721 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004722 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 LocTy RetTypeLoc;
4724 ValID CalleeID;
4725 SmallVector<ParamInfo, 16> ArgList;
4726
Chris Lattner3ed871f2009-10-27 19:13:16 +00004727 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004728 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004729 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004730 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 ParseValID(CalleeID) ||
4732 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004733 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4734 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004735 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004736 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004738 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004740
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 // If RetType is a non-function pointer type, then this is the short syntax
4742 // for the call, which means that RetType is just the return type. Infer the
4743 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004744 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4745 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004746 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004747 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004748 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4749 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004750
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751 if (!FunctionType::isValidReturnType(RetType))
4752 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004753
Owen Anderson4056ca92009-07-29 22:17:13 +00004754 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004755 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004756
Chris Lattnerac161bf2009-01-02 07:01:27 +00004757 // Look up the callee.
4758 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004759 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4760 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004762 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004763 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004764 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004765 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4766 AttributeSet::ReturnIndex,
4767 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004768
Chris Lattnerac161bf2009-01-02 07:01:27 +00004769 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004770
Chris Lattnerac161bf2009-01-02 07:01:27 +00004771 // Loop through FunctionType's arguments and ensure they are specified
4772 // correctly. Also, gather any parameter attributes.
4773 FunctionType::param_iterator I = Ty->param_begin();
4774 FunctionType::param_iterator E = Ty->param_end();
4775 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004776 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004777 if (I != E) {
4778 ExpectedTy = *I++;
4779 } else if (!Ty->isVarArg()) {
4780 return Error(ArgList[i].Loc, "too many arguments specified");
4781 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004782
Chris Lattnerac161bf2009-01-02 07:01:27 +00004783 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4784 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004785 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004786 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004787 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4788 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004789 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4790 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004792
Chris Lattnerac161bf2009-01-02 07:01:27 +00004793 if (I != E)
4794 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004795
David Majnemer8d22abd2015-02-23 00:01:32 +00004796 if (FnAttrs.hasAttributes()) {
4797 if (FnAttrs.hasAlignmentAttr())
4798 return Error(CallLoc, "invoke instructions may not have an alignment");
4799
Bill Wendlingf5075a42013-01-27 02:24:02 +00004800 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4801 AttributeSet::FunctionIndex,
4802 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004803 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004804
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004805 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004806 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004807
Jay Foad5bd375a2011-07-15 08:37:34 +00004808 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004809 II->setCallingConv(CC);
4810 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004811 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 Inst = II;
4813 return false;
4814}
4815
Bill Wendlingf891bf82011-07-31 06:30:59 +00004816/// ParseResume
4817/// ::= 'resume' TypeAndValue
4818bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4819 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004820 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4821 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822
Bill Wendlingf891bf82011-07-31 06:30:59 +00004823 ResumeInst *RI = ResumeInst::Create(Exn);
4824 Inst = RI;
4825 return false;
4826}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827
4828//===----------------------------------------------------------------------===//
4829// Binary Operators.
4830//===----------------------------------------------------------------------===//
4831
4832/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004833/// ::= ArithmeticOps TypeAndValue ',' Value
4834///
4835/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4836/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004837bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004838 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004839 LocTy Loc; Value *LHS, *RHS;
4840 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4841 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4842 ParseValue(LHS->getType(), RHS, PFS))
4843 return true;
4844
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004845 bool Valid;
4846 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004847 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004848 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004849 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4850 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004851 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004852 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4853 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004854 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004855
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004856 if (!Valid)
4857 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004858
Chris Lattnerac161bf2009-01-02 07:01:27 +00004859 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4860 return false;
4861}
4862
4863/// ParseLogical
4864/// ::= ArithmeticOps TypeAndValue ',' Value {
4865bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4866 unsigned Opc) {
4867 LocTy Loc; Value *LHS, *RHS;
4868 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4869 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4870 ParseValue(LHS->getType(), RHS, PFS))
4871 return true;
4872
Duncan Sands9dff9be2010-02-15 16:12:20 +00004873 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004874 return Error(Loc,"instruction requires integer or integer vector operands");
4875
4876 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4877 return false;
4878}
4879
4880
4881/// ParseCompare
4882/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4883/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004884bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4885 unsigned Opc) {
4886 // Parse the integer/fp comparison predicate.
4887 LocTy Loc;
4888 unsigned Pred;
4889 Value *LHS, *RHS;
4890 if (ParseCmpPredicate(Pred, Opc) ||
4891 ParseTypeAndValue(LHS, Loc, PFS) ||
4892 ParseToken(lltok::comma, "expected ',' after compare value") ||
4893 ParseValue(LHS->getType(), RHS, PFS))
4894 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004895
Chris Lattnerac161bf2009-01-02 07:01:27 +00004896 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004897 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004898 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004899 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004900 } else {
4901 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004902 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004903 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004904 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004905 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004906 }
4907 return false;
4908}
4909
4910//===----------------------------------------------------------------------===//
4911// Other Instructions.
4912//===----------------------------------------------------------------------===//
4913
4914
4915/// ParseCast
4916/// ::= CastOpc TypeAndValue 'to' Type
4917bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4918 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004919 LocTy Loc;
4920 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004921 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 if (ParseTypeAndValue(Op, Loc, PFS) ||
4923 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4924 ParseType(DestTy))
4925 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004926
Chris Lattner89d856e2009-03-01 00:53:13 +00004927 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4928 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004929 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004930 getTypeString(Op->getType()) + "' to '" +
4931 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004932 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004933 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4934 return false;
4935}
4936
4937/// ParseSelect
4938/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4939bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4940 LocTy Loc;
4941 Value *Op0, *Op1, *Op2;
4942 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4943 ParseToken(lltok::comma, "expected ',' after select condition") ||
4944 ParseTypeAndValue(Op1, PFS) ||
4945 ParseToken(lltok::comma, "expected ',' after select value") ||
4946 ParseTypeAndValue(Op2, PFS))
4947 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004948
Chris Lattnerac161bf2009-01-02 07:01:27 +00004949 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4950 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004951
Chris Lattnerac161bf2009-01-02 07:01:27 +00004952 Inst = SelectInst::Create(Op0, Op1, Op2);
4953 return false;
4954}
4955
Chris Lattnerb55ab542009-01-05 08:18:44 +00004956/// ParseVA_Arg
4957/// ::= 'va_arg' TypeAndValue ',' Type
4958bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004959 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004960 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004961 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 if (ParseTypeAndValue(Op, PFS) ||
4963 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004964 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004965 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004966
Chris Lattnerb55ab542009-01-05 08:18:44 +00004967 if (!EltTy->isFirstClassType())
4968 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004969
4970 Inst = new VAArgInst(Op, EltTy);
4971 return false;
4972}
4973
4974/// ParseExtractElement
4975/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4976bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4977 LocTy Loc;
4978 Value *Op0, *Op1;
4979 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4980 ParseToken(lltok::comma, "expected ',' after extract value") ||
4981 ParseTypeAndValue(Op1, PFS))
4982 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004983
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4985 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004986
Eric Christopherc9742252009-07-25 02:28:41 +00004987 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004988 return false;
4989}
4990
4991/// ParseInsertElement
4992/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4993bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4994 LocTy Loc;
4995 Value *Op0, *Op1, *Op2;
4996 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4997 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4998 ParseTypeAndValue(Op1, PFS) ||
4999 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5000 ParseTypeAndValue(Op2, PFS))
5001 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005002
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005004 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5007 return false;
5008}
5009
5010/// ParseShuffleVector
5011/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5012bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5013 LocTy Loc;
5014 Value *Op0, *Op1, *Op2;
5015 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5016 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5017 ParseTypeAndValue(Op1, PFS) ||
5018 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5019 ParseTypeAndValue(Op2, PFS))
5020 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005021
Chris Lattnerac161bf2009-01-02 07:01:27 +00005022 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005023 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005024
Chris Lattnerac161bf2009-01-02 07:01:27 +00005025 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5026 return false;
5027}
5028
5029/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005030/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005031int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005032 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005033 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005034
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005035 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5037 ParseValue(Ty, Op0, PFS) ||
5038 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005039 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005040 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5041 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005042
Chris Lattnerf4f03422009-12-30 05:27:33 +00005043 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005044 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5045 while (1) {
5046 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005047
Chris Lattner3822f632009-01-02 08:05:26 +00005048 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005049 break;
5050
Chris Lattnerf4f03422009-12-30 05:27:33 +00005051 if (Lex.getKind() == lltok::MetadataVar) {
5052 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005053 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005054 }
Devang Patel8f842d32009-10-16 18:45:49 +00005055
Chris Lattner3822f632009-01-02 08:05:26 +00005056 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 ParseValue(Ty, Op0, PFS) ||
5058 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005059 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5061 return true;
5062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005063
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 if (!Ty->isFirstClassType())
5065 return Error(TypeLoc, "phi node must have first class type");
5066
Jay Foad52131342011-03-30 11:28:46 +00005067 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005068 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5069 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5070 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005071 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072}
5073
Bill Wendlingfae14752011-08-12 20:24:12 +00005074/// ParseLandingPad
5075/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5076/// Clause
5077/// ::= 'catch' TypeAndValue
5078/// ::= 'filter'
5079/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5080bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005081 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005082 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005083
5084 if (ParseType(Ty, TyLoc) ||
5085 ParseToken(lltok::kw_personality, "expected 'personality'") ||
5086 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5087 return true;
5088
Owen Andersonf8f259d2015-03-09 07:13:42 +00005089 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005090 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5091
5092 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5093 LandingPadInst::ClauseType CT;
5094 if (EatIfPresent(lltok::kw_catch))
5095 CT = LandingPadInst::Catch;
5096 else if (EatIfPresent(lltok::kw_filter))
5097 CT = LandingPadInst::Filter;
5098 else
5099 return TokError("expected 'catch' or 'filter' clause type");
5100
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005101 Value *V;
5102 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005103 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005104 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005105
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005106 // A 'catch' type expects a non-array constant. A filter clause expects an
5107 // array constant.
5108 if (CT == LandingPadInst::Catch) {
5109 if (isa<ArrayType>(V->getType()))
5110 Error(VLoc, "'catch' clause has an invalid type");
5111 } else {
5112 if (!isa<ArrayType>(V->getType()))
5113 Error(VLoc, "'filter' clause has an invalid type");
5114 }
5115
Owen Andersonf8f259d2015-03-09 07:13:42 +00005116 Constant *CV = dyn_cast<Constant>(V);
5117 if (!CV)
5118 return Error(VLoc, "clause argument must be a constant");
5119 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005120 }
5121
Owen Andersonf8f259d2015-03-09 07:13:42 +00005122 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005123 return false;
5124}
5125
Chris Lattnerac161bf2009-01-02 07:01:27 +00005126/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005127/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5128/// ParameterList OptionalAttrs
5129/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5130/// ParameterList OptionalAttrs
5131/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005132/// ParameterList OptionalAttrs
5133bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005134 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005135 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005136 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005137 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005138 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005139 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 LocTy RetTypeLoc;
5141 ValID CalleeID;
5142 SmallVector<ParamInfo, 16> ArgList;
5143 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005144
Reid Kleckner5772b772014-04-24 20:14:34 +00005145 if ((TCK != CallInst::TCK_None &&
5146 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005148 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005149 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005150 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005151 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5152 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005153 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005154 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005155 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005156
Chris Lattnerac161bf2009-01-02 07:01:27 +00005157 // If RetType is a non-function pointer type, then this is the short syntax
5158 // for the call, which means that RetType is just the return type. Infer the
5159 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005160 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5161 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005163 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005164 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5165 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005166
Chris Lattnerac161bf2009-01-02 07:01:27 +00005167 if (!FunctionType::isValidReturnType(RetType))
5168 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005169
Owen Anderson4056ca92009-07-29 22:17:13 +00005170 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005171 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005172
Chris Lattnerac161bf2009-01-02 07:01:27 +00005173 // Look up the callee.
5174 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005175 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5176 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005177
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005178 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005179 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005180 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005181 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5182 AttributeSet::ReturnIndex,
5183 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005184
Chris Lattnerac161bf2009-01-02 07:01:27 +00005185 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005186
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187 // Loop through FunctionType's arguments and ensure they are specified
5188 // correctly. Also, gather any parameter attributes.
5189 FunctionType::param_iterator I = Ty->param_begin();
5190 FunctionType::param_iterator E = Ty->param_end();
5191 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005192 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005193 if (I != E) {
5194 ExpectedTy = *I++;
5195 } else if (!Ty->isVarArg()) {
5196 return Error(ArgList[i].Loc, "too many arguments specified");
5197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005198
Chris Lattnerac161bf2009-01-02 07:01:27 +00005199 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5200 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005201 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005202 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005203 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5204 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005205 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5206 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005208
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 if (I != E)
5210 return Error(CallLoc, "not enough parameters specified for call");
5211
David Majnemer8d22abd2015-02-23 00:01:32 +00005212 if (FnAttrs.hasAttributes()) {
5213 if (FnAttrs.hasAlignmentAttr())
5214 return Error(CallLoc, "call instructions may not have an alignment");
5215
Bill Wendlingf5075a42013-01-27 02:24:02 +00005216 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5217 AttributeSet::FunctionIndex,
5218 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005219 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005221 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005222 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005223
David Blaikie348de692015-04-23 21:36:23 +00005224 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005225 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005226 CI->setCallingConv(CC);
5227 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005228 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005229 Inst = CI;
5230 return false;
5231}
5232
5233//===----------------------------------------------------------------------===//
5234// Memory Instructions.
5235//===----------------------------------------------------------------------===//
5236
5237/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005238/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005239int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005240 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005241 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005243 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005244
5245 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5246
David Majnemera3b0eb22015-02-16 08:38:03 +00005247 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248
David Majnemera3b0eb22015-02-16 08:38:03 +00005249 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5250 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005251
Chris Lattnerb2f39502009-12-30 05:44:30 +00005252 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005253 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005254 if (Lex.getKind() == lltok::kw_align) {
5255 if (ParseOptionalAlignment(Alignment)) return true;
5256 } else if (Lex.getKind() == lltok::MetadataVar) {
5257 AteExtraComma = true;
5258 } else {
5259 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5260 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5261 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005262 }
5263 }
5264
Dan Gohman2140a742010-05-28 01:14:11 +00005265 if (Size && !Size->getType()->isIntegerTy())
5266 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005267
Reid Kleckner436c42e2014-01-17 23:58:17 +00005268 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5269 AI->setUsedWithInAlloca(IsInAlloca);
5270 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005271 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272}
5273
5274/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005275/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005276/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005277/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005278int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005279 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005280 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005281 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005282 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005283 AtomicOrdering Ordering = NotAtomic;
5284 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005285
5286 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005287 isAtomic = true;
5288 Lex.Lex();
5289 }
5290
Chris Lattnerbc639292011-11-27 06:56:53 +00005291 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005292 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005293 isVolatile = true;
5294 Lex.Lex();
5295 }
5296
David Blaikie15d9a4c2015-04-06 20:59:48 +00005297 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005298 LocTy ExplicitTypeLoc = Lex.getLoc();
5299 if (ParseType(Ty) ||
5300 ParseToken(lltok::comma, "expected comma after load's type") ||
5301 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005302 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005303 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5304 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005305
David Blaikie15d9a4c2015-04-06 20:59:48 +00005306 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005307 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005308 if (isAtomic && !Alignment)
5309 return Error(Loc, "atomic load must have explicit non-zero alignment");
5310 if (Ordering == Release || Ordering == AcquireRelease)
5311 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005312
David Blaikiea79ac142015-02-27 21:17:42 +00005313 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5314 return Error(ExplicitTypeLoc,
5315 "explicit pointee type doesn't match operand's pointee type");
5316
David Blaikie15d9a4c2015-04-06 20:59:48 +00005317 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005318 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005319}
5320
5321/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005322
5323/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5324/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005325/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005326int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005328 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005329 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005330 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005331 AtomicOrdering Ordering = NotAtomic;
5332 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005333
5334 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005335 isAtomic = true;
5336 Lex.Lex();
5337 }
5338
Chris Lattnerbc639292011-11-27 06:56:53 +00005339 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005340 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005341 isVolatile = true;
5342 Lex.Lex();
5343 }
5344
Chris Lattnerac161bf2009-01-02 07:01:27 +00005345 if (ParseTypeAndValue(Val, Loc, PFS) ||
5346 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005347 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005348 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005349 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005350 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005351
Duncan Sands19d0b472010-02-16 11:11:14 +00005352 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 return Error(PtrLoc, "store operand must be a pointer");
5354 if (!Val->getType()->isFirstClassType())
5355 return Error(Loc, "store operand must be a first class value");
5356 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5357 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005358 if (isAtomic && !Alignment)
5359 return Error(Loc, "atomic store must have explicit non-zero alignment");
5360 if (Ordering == Acquire || Ordering == AcquireRelease)
5361 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005362
Eli Friedman59b66882011-08-09 23:02:53 +00005363 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005364 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005365}
5366
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005367/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005368/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5369/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005370int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005371 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5372 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005373 AtomicOrdering SuccessOrdering = NotAtomic;
5374 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005375 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005376 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005377 bool isWeak = false;
5378
5379 if (EatIfPresent(lltok::kw_weak))
5380 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005381
5382 if (EatIfPresent(lltok::kw_volatile))
5383 isVolatile = true;
5384
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005385 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5386 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5387 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5388 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5389 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005390 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5391 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005392 return true;
5393
Tim Northovere94a5182014-03-11 10:48:52 +00005394 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005395 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005396 if (SuccessOrdering < FailureOrdering)
5397 return TokError("cmpxchg must be at least as ordered on success as failure");
5398 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5399 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005400 if (!Ptr->getType()->isPointerTy())
5401 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5402 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5403 return Error(CmpLoc, "compare value and pointer type do not match");
5404 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5405 return Error(NewLoc, "new value and pointer type do not match");
5406 if (!New->getType()->isIntegerTy())
5407 return Error(NewLoc, "cmpxchg operand must be an integer");
5408 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5409 if (Size < 8 || (Size & (Size - 1)))
5410 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5411 " integer");
5412
Tim Northover420a2162014-06-13 14:24:07 +00005413 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5414 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005415 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005416 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005417 Inst = CXI;
5418 return AteExtraComma ? InstExtraComma : InstNormal;
5419}
5420
5421/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005422/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5423/// 'singlethread'? AtomicOrdering
5424int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005425 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5426 bool AteExtraComma = false;
5427 AtomicOrdering Ordering = NotAtomic;
5428 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005429 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005430 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005431
5432 if (EatIfPresent(lltok::kw_volatile))
5433 isVolatile = true;
5434
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005435 switch (Lex.getKind()) {
5436 default: return TokError("expected binary operation in atomicrmw");
5437 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5438 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5439 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5440 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5441 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5442 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5443 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5444 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5445 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5446 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5447 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5448 }
5449 Lex.Lex(); // Eat the operation.
5450
5451 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5452 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5453 ParseTypeAndValue(Val, ValLoc, PFS) ||
5454 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5455 return true;
5456
5457 if (Ordering == Unordered)
5458 return TokError("atomicrmw cannot be unordered");
5459 if (!Ptr->getType()->isPointerTy())
5460 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5461 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5462 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5463 if (!Val->getType()->isIntegerTy())
5464 return Error(ValLoc, "atomicrmw operand must be an integer");
5465 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5466 if (Size < 8 || (Size & (Size - 1)))
5467 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5468 " integer");
5469
5470 AtomicRMWInst *RMWI =
5471 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5472 RMWI->setVolatile(isVolatile);
5473 Inst = RMWI;
5474 return AteExtraComma ? InstExtraComma : InstNormal;
5475}
5476
Eli Friedmanfee02c62011-07-25 23:16:38 +00005477/// ParseFence
5478/// ::= 'fence' 'singlethread'? AtomicOrdering
5479int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5480 AtomicOrdering Ordering = NotAtomic;
5481 SynchronizationScope Scope = CrossThread;
5482 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5483 return true;
5484
5485 if (Ordering == Unordered)
5486 return TokError("fence cannot be unordered");
5487 if (Ordering == Monotonic)
5488 return TokError("fence cannot be monotonic");
5489
5490 Inst = new FenceInst(Context, Ordering, Scope);
5491 return InstNormal;
5492}
5493
Chris Lattnerac161bf2009-01-02 07:01:27 +00005494/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005495/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005496int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005497 Value *Ptr = nullptr;
5498 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005499 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005500
Dan Gohman16cbbe42009-07-29 15:58:36 +00005501 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005502
David Blaikie79e6c742015-02-27 19:29:02 +00005503 Type *Ty = nullptr;
5504 LocTy ExplicitTypeLoc = Lex.getLoc();
5505 if (ParseType(Ty) ||
5506 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5507 ParseTypeAndValue(Ptr, Loc, PFS))
5508 return true;
5509
Eli Benderskyd9806682013-04-22 17:03:42 +00005510 Type *BaseType = Ptr->getType();
5511 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5512 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005513 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005514
David Blaikie8d757942015-03-09 23:08:44 +00005515 if (Ty != BasePointerType->getElementType())
5516 return Error(ExplicitTypeLoc,
5517 "explicit pointee type doesn't match operand's pointee type");
5518
Chris Lattnerac161bf2009-01-02 07:01:27 +00005519 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005520 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005521 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005522 if (Lex.getKind() == lltok::MetadataVar) {
5523 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005524 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005525 }
Chris Lattner3822f632009-01-02 08:05:26 +00005526 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005527 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005528 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00005529 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5530 return Error(EltLoc, "getelementptr index type missmatch");
5531 if (Val->getType()->isVectorTy()) {
5532 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5533 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5534 if (ValNumEl != PtrNumEl)
5535 return Error(EltLoc,
5536 "getelementptr vector index has a wrong number of elements");
5537 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005538 Indices.push_back(Val);
5539 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005540
Owen Andersone90f9922015-03-10 06:34:57 +00005541 SmallPtrSet<const Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005542 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005543 return Error(Loc, "base element of getelementptr must be sized");
5544
David Blaikied33bad32015-04-17 22:32:13 +00005545 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005546 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005547 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005548 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005549 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005550 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005551}
5552
5553/// ParseExtractValue
5554/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005555int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005556 Value *Val; LocTy Loc;
5557 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005558 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005559 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005560 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005561 return true;
5562
Chris Lattner392be582010-02-12 20:49:41 +00005563 if (!Val->getType()->isAggregateType())
5564 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005565
Jay Foad57aa6362011-07-13 10:26:04 +00005566 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005567 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005568 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005569 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005570}
5571
5572/// ParseInsertValue
5573/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005574int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005575 Value *Val0, *Val1; LocTy Loc0, Loc1;
5576 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005577 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005578 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5579 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5580 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005581 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005583
Chris Lattner392be582010-02-12 20:49:41 +00005584 if (!Val0->getType()->isAggregateType())
5585 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005586
David Majnemer30074532015-02-11 07:43:58 +00005587 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5588 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005589 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005590 if (IndexedType != Val1->getType())
5591 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5592 getTypeString(Val1->getType()) + "' instead of '" +
5593 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005594 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005595 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005596}
Nick Lewycky49f89192009-04-04 07:22:01 +00005597
5598//===----------------------------------------------------------------------===//
5599// Embedded metadata.
5600//===----------------------------------------------------------------------===//
5601
5602/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005603/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005604/// Element
5605/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005606bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005607 if (ParseToken(lltok::lbrace, "expected '{' here"))
5608 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005609
Dan Gohman1e0213a2010-07-13 19:33:27 +00005610 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005611 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005612 return false;
5613
Nick Lewycky49f89192009-04-04 07:22:01 +00005614 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005615 // Null is a special case since it is typeless.
5616 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005617 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005618 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005619 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005620
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005621 Metadata *MD;
5622 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005623 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005624 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005625 } while (EatIfPresent(lltok::comma));
5626
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005627 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005628}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005629
5630//===----------------------------------------------------------------------===//
5631// Use-list order directives.
5632//===----------------------------------------------------------------------===//
5633bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5634 SMLoc Loc) {
5635 if (V->use_empty())
5636 return Error(Loc, "value has no uses");
5637
5638 unsigned NumUses = 0;
5639 SmallDenseMap<const Use *, unsigned, 16> Order;
5640 for (const Use &U : V->uses()) {
5641 if (++NumUses > Indexes.size())
5642 break;
5643 Order[&U] = Indexes[NumUses - 1];
5644 }
5645 if (NumUses < 2)
5646 return Error(Loc, "value only has one use");
5647 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5648 return Error(Loc, "wrong number of indexes, expected " +
5649 Twine(std::distance(V->use_begin(), V->use_end())));
5650
5651 V->sortUseList([&](const Use &L, const Use &R) {
5652 return Order.lookup(&L) < Order.lookup(&R);
5653 });
5654 return false;
5655}
5656
5657/// ParseUseListOrderIndexes
5658/// ::= '{' uint32 (',' uint32)+ '}'
5659bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5660 SMLoc Loc = Lex.getLoc();
5661 if (ParseToken(lltok::lbrace, "expected '{' here"))
5662 return true;
5663 if (Lex.getKind() == lltok::rbrace)
5664 return Lex.Error("expected non-empty list of uselistorder indexes");
5665
5666 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5667 // indexes should be distinct numbers in the range [0, size-1], and should
5668 // not be in order.
5669 unsigned Offset = 0;
5670 unsigned Max = 0;
5671 bool IsOrdered = true;
5672 assert(Indexes.empty() && "Expected empty order vector");
5673 do {
5674 unsigned Index;
5675 if (ParseUInt32(Index))
5676 return true;
5677
5678 // Update consistency checks.
5679 Offset += Index - Indexes.size();
5680 Max = std::max(Max, Index);
5681 IsOrdered &= Index == Indexes.size();
5682
5683 Indexes.push_back(Index);
5684 } while (EatIfPresent(lltok::comma));
5685
5686 if (ParseToken(lltok::rbrace, "expected '}' here"))
5687 return true;
5688
5689 if (Indexes.size() < 2)
5690 return Error(Loc, "expected >= 2 uselistorder indexes");
5691 if (Offset != 0 || Max >= Indexes.size())
5692 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5693 if (IsOrdered)
5694 return Error(Loc, "expected uselistorder indexes to change the order");
5695
5696 return false;
5697}
5698
5699/// ParseUseListOrder
5700/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5701bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5702 SMLoc Loc = Lex.getLoc();
5703 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5704 return true;
5705
5706 Value *V;
5707 SmallVector<unsigned, 16> Indexes;
5708 if (ParseTypeAndValue(V, PFS) ||
5709 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5710 ParseUseListOrderIndexes(Indexes))
5711 return true;
5712
5713 return sortUseListOrder(V, Indexes, Loc);
5714}
5715
5716/// ParseUseListOrderBB
5717/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5718bool LLParser::ParseUseListOrderBB() {
5719 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5720 SMLoc Loc = Lex.getLoc();
5721 Lex.Lex();
5722
5723 ValID Fn, Label;
5724 SmallVector<unsigned, 16> Indexes;
5725 if (ParseValID(Fn) ||
5726 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5727 ParseValID(Label) ||
5728 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5729 ParseUseListOrderIndexes(Indexes))
5730 return true;
5731
5732 // Check the function.
5733 GlobalValue *GV;
5734 if (Fn.Kind == ValID::t_GlobalName)
5735 GV = M->getNamedValue(Fn.StrVal);
5736 else if (Fn.Kind == ValID::t_GlobalID)
5737 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5738 else
5739 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5740 if (!GV)
5741 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5742 auto *F = dyn_cast<Function>(GV);
5743 if (!F)
5744 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5745 if (F->isDeclaration())
5746 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5747
5748 // Check the basic block.
5749 if (Label.Kind == ValID::t_LocalID)
5750 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5751 if (Label.Kind != ValID::t_LocalName)
5752 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5753 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5754 if (!V)
5755 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5756 if (!isa<BasicBlock>(V))
5757 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5758
5759 return sortUseListOrder(V, Indexes, Loc);
5760}