blob: e69fa3828edc7e4b3ebfef8bc7be0144e42dff1b [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
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000363/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000364bool 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) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000370 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000371 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000372}
373
Chris Lattner3822f632009-01-02 08:05:26 +0000374/// ParseGlobalType
375/// ::= 'constant'
376/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377bool LLParser::ParseGlobalType(bool &IsConstant) {
378 if (Lex.getKind() == lltok::kw_constant)
379 IsConstant = true;
380 else if (Lex.getKind() == lltok::kw_global)
381 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000382 else {
383 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000385 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000386 Lex.Lex();
387 return false;
388}
389
Dan Gohman466876b2009-08-12 23:32:33 +0000390/// ParseUnnamedGlobal:
391/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000392/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
393/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000394/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000395/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
396/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000397bool LLParser::ParseUnnamedGlobal() {
398 unsigned VarID = NumberedVals.size();
399 std::string Name;
400 LocTy NameLoc = Lex.getLoc();
401
402 // Handle the GlobalID form.
403 if (Lex.getKind() == lltok::GlobalID) {
404 if (Lex.getUIntVal() != VarID)
405 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000406 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000407 Lex.Lex(); // eat GlobalID;
408
409 if (ParseToken(lltok::equal, "expected '=' after name"))
410 return true;
411 }
412
413 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000414 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000415 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000416 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000417 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000418 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000419 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000420 ParseOptionalThreadLocal(TLM) ||
421 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000422 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000423
Rafael Espindola464fe022014-07-30 22:51:54 +0000424 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000425 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000426 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000427 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000428 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000429}
430
Chris Lattnerac161bf2009-01-02 07:01:27 +0000431/// ParseNamedGlobal:
432/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000433/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000435bool LLParser::ParseNamedGlobal() {
436 assert(Lex.getKind() == lltok::GlobalVar);
437 LocTy NameLoc = Lex.getLoc();
438 std::string Name = Lex.getStrVal();
439 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000440
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000442 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000443 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000444 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
446 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000447 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000448 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000449 ParseOptionalThreadLocal(TLM) ||
450 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000452
Rafael Espindola464fe022014-07-30 22:51:54 +0000453 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000454 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000455 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000456
457 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000458 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000459}
460
David Majnemerdad0a642014-06-27 18:19:56 +0000461bool LLParser::parseComdat() {
462 assert(Lex.getKind() == lltok::ComdatVar);
463 std::string Name = Lex.getStrVal();
464 LocTy NameLoc = Lex.getLoc();
465 Lex.Lex();
466
467 if (ParseToken(lltok::equal, "expected '=' here"))
468 return true;
469
470 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
471 return TokError("expected comdat type");
472
473 Comdat::SelectionKind SK;
474 switch (Lex.getKind()) {
475 default:
476 return TokError("unknown selection kind");
477 case lltok::kw_any:
478 SK = Comdat::Any;
479 break;
480 case lltok::kw_exactmatch:
481 SK = Comdat::ExactMatch;
482 break;
483 case lltok::kw_largest:
484 SK = Comdat::Largest;
485 break;
486 case lltok::kw_noduplicates:
487 SK = Comdat::NoDuplicates;
488 break;
489 case lltok::kw_samesize:
490 SK = Comdat::SameSize;
491 break;
492 }
493 Lex.Lex();
494
495 // See if the comdat was forward referenced, if so, use the comdat.
496 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
497 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
498 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
499 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
500
501 Comdat *C;
502 if (I != ComdatSymTab.end())
503 C = &I->second;
504 else
505 C = M->getOrInsertComdat(Name);
506 C->setSelectionKind(SK);
507
508 return false;
509}
510
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000511// MDString:
512// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000513bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000514 std::string Str;
515 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000516 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000517 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000518 return false;
519}
520
521// MDNode:
522// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000523bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000524 // !{ ..., !42, ... }
525 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000526 if (ParseUInt32(MID))
527 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000528
Chris Lattner8eff0152010-04-01 05:14:45 +0000529 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000530 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000531 Result = NumberedMetadata[MID];
532 return false;
533 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000534
Chris Lattner8eff0152010-04-01 05:14:45 +0000535 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000536 auto &FwdRef = ForwardRefMDNodes[MID];
537 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000538
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000539 Result = FwdRef.first.get();
540 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000541 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000542}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000544/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000545/// !foo = !{ !1, !2 }
546bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000547 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000548 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000549 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000550
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000551 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000552 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000553 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000554 return true;
555
Dan Gohman2637cc12010-07-21 23:38:33 +0000556 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000557 if (Lex.getKind() != lltok::rbrace)
558 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000559 if (ParseToken(lltok::exclaim, "Expected '!' here"))
560 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000561
Craig Topper2617dcc2014-04-15 06:32:26 +0000562 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000563 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000564 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000565 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000566
567 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
568 return true;
569
Devang Patelbe626972009-07-29 00:34:02 +0000570 return false;
571}
572
Devang Patel39e64d42009-07-01 19:21:12 +0000573/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000574/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000575bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000576 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000577 Lex.Lex();
578 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000579
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000580 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000581 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000582 ParseToken(lltok::equal, "expected '=' here"))
583 return true;
584
585 // Detect common error, from old metadata syntax.
586 if (Lex.getKind() == lltok::Type)
587 return TokError("unexpected type in metadata definition");
588
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000589 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000590 if (Lex.getKind() == lltok::MetadataVar) {
591 if (ParseSpecializedMDNode(Init, IsDistinct))
592 return true;
593 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
594 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000595 return true;
596
Chris Lattnerfc58af22009-12-30 04:51:58 +0000597 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000598 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000599 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000600 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000601 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000602
Chris Lattnerfc58af22009-12-30 04:51:58 +0000603 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
604 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000605 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000606 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000607 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000608 }
609
Devang Patel39e64d42009-07-01 19:21:12 +0000610 return false;
611}
612
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000613static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
614 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
615 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
616}
617
Chris Lattnerac161bf2009-01-02 07:01:27 +0000618/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000619/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
620/// OptionalDLLStorageClass OptionalThreadLocal
621/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000622///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000623/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000624/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000625///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000626/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000627///
Rafael Espindola464fe022014-07-30 22:51:54 +0000628bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000629 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000630 GlobalVariable::ThreadLocalMode TLM,
631 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000632 assert(Lex.getKind() == lltok::kw_alias);
633 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000634
Rafael Espindola78527052013-10-06 15:10:43 +0000635 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
636
Rafael Espindolacaa43562013-10-09 16:07:32 +0000637 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000638 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000639
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000640 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000641 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000642 "symbol with local linkage must have default visibility");
643
Rafael Espindola64c1e182014-06-03 02:41:57 +0000644 Constant *Aliasee;
645 LocTy AliaseeLoc = Lex.getLoc();
646 if (Lex.getKind() != lltok::kw_bitcast &&
647 Lex.getKind() != lltok::kw_getelementptr &&
648 Lex.getKind() != lltok::kw_addrspacecast &&
649 Lex.getKind() != lltok::kw_inttoptr) {
650 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000651 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000652 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000653 // The bitcast dest type is not present, it is implied by the dest type.
654 ValID ID;
655 if (ParseValID(ID))
656 return true;
657 if (ID.Kind != ValID::t_Constant)
658 return Error(AliaseeLoc, "invalid aliasee");
659 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000661
Rafael Espindola64c1e182014-06-03 02:41:57 +0000662 Type *AliaseeType = Aliasee->getType();
663 auto *PTy = dyn_cast<PointerType>(AliaseeType);
664 if (!PTy)
665 return Error(AliaseeLoc, "An alias must have pointer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000666
667 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000668 std::unique_ptr<GlobalAlias> GA(
David Blaikief64246b2015-04-29 21:22:39 +0000669 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
670 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000671 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000673 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000674 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000675
Chris Lattnerac161bf2009-01-02 07:01:27 +0000676 // See if this value already exists in the symbol table. If so, it is either
677 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000678 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000679 // See if this was a redefinition. If so, there is no entry in
680 // ForwardRefVals.
681 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
682 I = ForwardRefVals.find(Name);
683 if (I == ForwardRefVals.end())
684 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
685
686 // Otherwise, this was a definition of forward ref. Verify that types
687 // agree.
688 if (Val->getType() != GA->getType())
689 return Error(NameLoc,
690 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
Chris Lattnerac161bf2009-01-02 07:01:27 +0000692 // If they agree, just RAUW the old value with the alias and remove the
693 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000694 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000695 Val->eraseFromParent();
696 ForwardRefVals.erase(I);
697 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000698
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000700 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000701 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000702
Rafael Espindolaaa273822014-05-09 21:49:17 +0000703 // The module owns this now
704 GA.release();
705
Chris Lattnerac161bf2009-01-02 07:01:27 +0000706 return false;
707}
708
709/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000710/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000711/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000712/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000713/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000714/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000715/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000716///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000717/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000718/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719///
720bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
721 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000722 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000723 GlobalVariable::ThreadLocalMode TLM,
724 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000725 if (!isValidVisibilityForLinkage(Visibility, Linkage))
726 return Error(NameLoc,
727 "symbol with local linkage must have default visibility");
728
Chris Lattnerac161bf2009-01-02 07:01:27 +0000729 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000730 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000731 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000732 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000733
Craig Topper2617dcc2014-04-15 06:32:26 +0000734 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000735 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000736 ParseOptionalToken(lltok::kw_externally_initialized,
737 IsExternallyInitialized,
738 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739 ParseGlobalType(IsConstant) ||
740 ParseType(Ty, TyLoc))
741 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Chris Lattnerac161bf2009-01-02 07:01:27 +0000743 // If the linkage is specified and is external, then no initializer is
744 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000745 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000746 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 Linkage != GlobalValue::ExternalLinkage)) {
748 if (ParseGlobalValue(Ty, Init))
749 return true;
750 }
751
David Majnemer49b3d9b2015-02-16 08:41:08 +0000752 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000753 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000754
David Majnemer598bd052014-12-09 05:56:09 +0000755 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756
757 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000758 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000759 GVal = M->getNamedValue(Name);
760 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000761 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
762 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000763 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 } else {
765 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
766 I = ForwardRefValIDs.find(NumberedVals.size());
767 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000768 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000769 ForwardRefValIDs.erase(I);
770 }
771 }
772
David Majnemer598bd052014-12-09 05:56:09 +0000773 GlobalVariable *GV;
774 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000775 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
776 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000777 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000779 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000780 return Error(TyLoc,
781 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000782
David Majnemer598bd052014-12-09 05:56:09 +0000783 GV = cast<GlobalVariable>(GVal);
784
Chris Lattnerac161bf2009-01-02 07:01:27 +0000785 // Move the forward-reference to the correct spot in the module.
786 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
787 }
788
789 if (Name.empty())
790 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Set the parsed properties on the global.
793 if (Init)
794 GV->setInitializer(Init);
795 GV->setConstant(IsConstant);
796 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
797 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000798 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000799 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000800 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000801 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
Chris Lattnerac161bf2009-01-02 07:01:27 +0000803 // Parse attributes on the global.
804 while (Lex.getKind() == lltok::comma) {
805 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattnerac161bf2009-01-02 07:01:27 +0000807 if (Lex.getKind() == lltok::kw_section) {
808 Lex.Lex();
809 GV->setSection(Lex.getStrVal());
810 if (ParseToken(lltok::StringConstant, "expected global section string"))
811 return true;
812 } else if (Lex.getKind() == lltok::kw_align) {
813 unsigned Alignment;
814 if (ParseOptionalAlignment(Alignment)) return true;
815 GV->setAlignment(Alignment);
816 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000817 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000818 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000819 return true;
820 if (C)
821 GV->setComdat(C);
822 else
823 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 }
825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 return false;
828}
829
Bill Wendling63b88192013-02-06 06:52:58 +0000830/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000831/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000832bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000833 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000834 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000835 Lex.Lex();
836
David Majnemerb39e22b2014-12-09 18:33:57 +0000837 if (Lex.getKind() != lltok::AttrGrpID)
838 return TokError("expected attribute group id");
839
Bill Wendling63b88192013-02-06 06:52:58 +0000840 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000841 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000842 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000843 Lex.Lex();
844
845 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000846 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000847 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000848 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000849 ParseToken(lltok::rbrace, "expected end of attribute group"))
850 return true;
851
Bill Wendlingb32b0412013-02-08 06:32:06 +0000852 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000853 return Error(AttrGrpLoc, "attribute group has no attributes");
854
855 return false;
856}
857
Bill Wendling8b0321d2013-02-08 00:52:31 +0000858/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000859/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000860bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
861 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000862 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000863 bool HaveError = false;
864
865 B.clear();
866
Bill Wendling63b88192013-02-06 06:52:58 +0000867 while (true) {
868 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000869 if (Token == lltok::kw_builtin)
870 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000871 switch (Token) {
872 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000873 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000874 return Error(Lex.getLoc(), "unterminated attribute group");
875 case lltok::rbrace:
876 // Finished.
877 return false;
878
Bill Wendlingb32b0412013-02-08 06:32:06 +0000879 case lltok::AttrGrpID: {
880 // Allow a function to reference an attribute group:
881 //
882 // define void @foo() #1 { ... }
883 if (inAttrGrp)
884 HaveError |=
885 Error(Lex.getLoc(),
886 "cannot have an attribute group reference in an attribute group");
887
888 unsigned AttrGrpNum = Lex.getUIntVal();
889 if (inAttrGrp) break;
890
891 // Save the reference to the attribute group. We'll fill it in later.
892 FwdRefAttrGrps.push_back(AttrGrpNum);
893 break;
894 }
Bill Wendling63b88192013-02-06 06:52:58 +0000895 // Target-dependent attributes:
896 case lltok::StringConstant: {
897 std::string Attr = Lex.getStrVal();
898 Lex.Lex();
899 std::string Val;
900 if (EatIfPresent(lltok::equal) &&
901 ParseStringConstant(Val))
902 return true;
903
904 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000905 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000906 }
907
908 // Target-independent attributes:
909 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000910 // As a hack, we allow function alignment to be initially parsed as an
911 // attribute on a function declaration/definition or added to an attribute
912 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000913 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000914 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000915 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000916 if (ParseToken(lltok::equal, "expected '=' here") ||
917 ParseUInt32(Alignment))
918 return true;
919 } else {
920 if (ParseOptionalAlignment(Alignment))
921 return true;
922 }
Bill Wendling63b88192013-02-06 06:52:58 +0000923 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000924 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000925 }
926 case lltok::kw_alignstack: {
927 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000928 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000929 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000930 if (ParseToken(lltok::equal, "expected '=' here") ||
931 ParseUInt32(Alignment))
932 return true;
933 } else {
934 if (ParseOptionalStackAlignment(Alignment))
935 return true;
936 }
Bill Wendling63b88192013-02-06 06:52:58 +0000937 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000938 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000939 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000940 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000941 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000942 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000943 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000944 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000945 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
946 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
947 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
948 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
949 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
950 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
951 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
952 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
953 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
954 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000955 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000956 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
957 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
958 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
959 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
960 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
961 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
962 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
963 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
964 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
965 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
966 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000967
968 // Error handling.
969 case lltok::kw_inreg:
970 case lltok::kw_signext:
971 case lltok::kw_zeroext:
972 HaveError |=
973 Error(Lex.getLoc(),
974 "invalid use of attribute on a function");
975 break;
976 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000977 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000978 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +0000979 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000980 case lltok::kw_nest:
981 case lltok::kw_noalias:
982 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000983 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000984 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000985 case lltok::kw_sret:
986 HaveError |=
987 Error(Lex.getLoc(),
988 "invalid use of parameter-only attribute on a function");
989 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000990 }
991
992 Lex.Lex();
993 }
994}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000995
996//===----------------------------------------------------------------------===//
997// GlobalValue Reference/Resolution Routines.
998//===----------------------------------------------------------------------===//
999
1000/// GetGlobalVal - Get a value with the specified name or ID, creating a
1001/// forward reference record if needed. This can return null if the value
1002/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001003GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001004 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001005 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001006 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001007 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001008 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001009 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001010
Chris Lattnerac161bf2009-01-02 07:01:27 +00001011 // Look this name up in the normal function symbol table.
1012 GlobalValue *Val =
1013 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001014
Chris Lattnerac161bf2009-01-02 07:01:27 +00001015 // If this is a forward reference for the value, see if we already created a
1016 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001017 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001018 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1019 I = ForwardRefVals.find(Name);
1020 if (I != ForwardRefVals.end())
1021 Val = I->second.first;
1022 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001023
Chris Lattnerac161bf2009-01-02 07:01:27 +00001024 // If we have the value in the symbol table or fwd-ref table, return it.
1025 if (Val) {
1026 if (Val->getType() == Ty) return Val;
1027 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001028 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001029 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001031
Chris Lattnerac161bf2009-01-02 07:01:27 +00001032 // Otherwise, create a new forward reference for this value and remember it.
1033 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001034 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001035 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001036 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001037 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001038 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1039 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001040 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001041
Chris Lattnerac161bf2009-01-02 07:01:27 +00001042 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1043 return FwdVal;
1044}
1045
Chris Lattner229907c2011-07-18 04:54:35 +00001046GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1047 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001048 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001049 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001050 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001052
Craig Topper2617dcc2014-04-15 06:32:26 +00001053 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001054
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 // If this is a forward reference for the value, see if we already created a
1056 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001057 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001058 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1059 I = ForwardRefValIDs.find(ID);
1060 if (I != ForwardRefValIDs.end())
1061 Val = I->second.first;
1062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001063
Chris Lattnerac161bf2009-01-02 07:01:27 +00001064 // If we have the value in the symbol table or fwd-ref table, return it.
1065 if (Val) {
1066 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001067 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001068 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001069 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001070 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001071
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 // Otherwise, create a new forward reference for this value and remember it.
1073 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001074 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001075 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001076 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001077 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001078 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001079
Chris Lattnerac161bf2009-01-02 07:01:27 +00001080 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1081 return FwdVal;
1082}
1083
1084
1085//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001086// Comdat Reference/Resolution Routines.
1087//===----------------------------------------------------------------------===//
1088
1089Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1090 // Look this name up in the comdat symbol table.
1091 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1092 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1093 if (I != ComdatSymTab.end())
1094 return &I->second;
1095
1096 // Otherwise, create a new forward reference for this value and remember it.
1097 Comdat *C = M->getOrInsertComdat(Name);
1098 ForwardRefComdats[Name] = Loc;
1099 return C;
1100}
1101
1102
1103//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001104// Helper Routines.
1105//===----------------------------------------------------------------------===//
1106
1107/// ParseToken - If the current token has the specified kind, eat it and return
1108/// success. Otherwise, emit the specified error and return failure.
1109bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1110 if (Lex.getKind() != T)
1111 return TokError(ErrMsg);
1112 Lex.Lex();
1113 return false;
1114}
1115
Chris Lattner3822f632009-01-02 08:05:26 +00001116/// ParseStringConstant
1117/// ::= StringConstant
1118bool LLParser::ParseStringConstant(std::string &Result) {
1119 if (Lex.getKind() != lltok::StringConstant)
1120 return TokError("expected string constant");
1121 Result = Lex.getStrVal();
1122 Lex.Lex();
1123 return false;
1124}
1125
1126/// ParseUInt32
1127/// ::= uint32
1128bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001129 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1130 return TokError("expected integer");
1131 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1132 if (Val64 != unsigned(Val64))
1133 return TokError("expected 32-bit integer (too large)");
1134 Val = Val64;
1135 Lex.Lex();
1136 return false;
1137}
1138
Hal Finkelb0407ba2014-07-18 15:51:28 +00001139/// ParseUInt64
1140/// ::= uint64
1141bool LLParser::ParseUInt64(uint64_t &Val) {
1142 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1143 return TokError("expected integer");
1144 Val = Lex.getAPSIntVal().getLimitedValue();
1145 Lex.Lex();
1146 return false;
1147}
1148
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001149/// ParseTLSModel
1150/// := 'localdynamic'
1151/// := 'initialexec'
1152/// := 'localexec'
1153bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1154 switch (Lex.getKind()) {
1155 default:
1156 return TokError("expected localdynamic, initialexec or localexec");
1157 case lltok::kw_localdynamic:
1158 TLM = GlobalVariable::LocalDynamicTLSModel;
1159 break;
1160 case lltok::kw_initialexec:
1161 TLM = GlobalVariable::InitialExecTLSModel;
1162 break;
1163 case lltok::kw_localexec:
1164 TLM = GlobalVariable::LocalExecTLSModel;
1165 break;
1166 }
1167
1168 Lex.Lex();
1169 return false;
1170}
1171
1172/// ParseOptionalThreadLocal
1173/// := /*empty*/
1174/// := 'thread_local'
1175/// := 'thread_local' '(' tlsmodel ')'
1176bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1177 TLM = GlobalVariable::NotThreadLocal;
1178 if (!EatIfPresent(lltok::kw_thread_local))
1179 return false;
1180
1181 TLM = GlobalVariable::GeneralDynamicTLSModel;
1182 if (Lex.getKind() == lltok::lparen) {
1183 Lex.Lex();
1184 return ParseTLSModel(TLM) ||
1185 ParseToken(lltok::rparen, "expected ')' after thread local model");
1186 }
1187 return false;
1188}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001189
1190/// ParseOptionalAddrSpace
1191/// := /*empty*/
1192/// := 'addrspace' '(' uint32 ')'
1193bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1194 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001195 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001196 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001198 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001199 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001200}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201
Bill Wendling34c2eb22012-12-04 23:40:58 +00001202/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1203bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1204 bool HaveError = false;
1205
1206 B.clear();
1207
1208 while (1) {
1209 lltok::Kind Token = Lex.getKind();
1210 switch (Token) {
1211 default: // End of attributes.
1212 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 case lltok::kw_align: {
1214 unsigned Alignment;
1215 if (ParseOptionalAlignment(Alignment))
1216 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001217 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218 continue;
1219 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001220 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001221 case lltok::kw_dereferenceable: {
1222 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001223 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001224 return true;
1225 B.addDereferenceableAttr(Bytes);
1226 continue;
1227 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001228 case lltok::kw_dereferenceable_or_null: {
1229 uint64_t Bytes;
1230 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1231 return true;
1232 B.addDereferenceableOrNullAttr(Bytes);
1233 continue;
1234 }
Reid Klecknera534a382013-12-19 02:14:12 +00001235 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001236 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1237 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1238 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1239 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001240 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001241 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1242 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001243 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001244 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1245 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1246 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001247
Stephen Lin7577ed52013-04-20 13:16:13 +00001248 case lltok::kw_alignstack:
1249 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001250 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001251 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001252 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001253 case lltok::kw_minsize:
1254 case lltok::kw_naked:
1255 case lltok::kw_nobuiltin:
1256 case lltok::kw_noduplicate:
1257 case lltok::kw_noimplicitfloat:
1258 case lltok::kw_noinline:
1259 case lltok::kw_nonlazybind:
1260 case lltok::kw_noredzone:
1261 case lltok::kw_noreturn:
1262 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001263 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001264 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001265 case lltok::kw_returns_twice:
1266 case lltok::kw_sanitize_address:
1267 case lltok::kw_sanitize_memory:
1268 case lltok::kw_sanitize_thread:
1269 case lltok::kw_ssp:
1270 case lltok::kw_sspreq:
1271 case lltok::kw_sspstrong:
1272 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001273 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1274 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001275 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001276
Bill Wendling34c2eb22012-12-04 23:40:58 +00001277 Lex.Lex();
1278 }
1279}
1280
1281/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1282bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1283 bool HaveError = false;
1284
1285 B.clear();
1286
1287 while (1) {
1288 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001289 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001290 default: // End of attributes.
1291 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001292 case lltok::kw_dereferenceable: {
1293 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001294 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001295 return true;
1296 B.addDereferenceableAttr(Bytes);
1297 continue;
1298 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001299 case lltok::kw_dereferenceable_or_null: {
1300 uint64_t Bytes;
1301 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1302 return true;
1303 B.addDereferenceableOrNullAttr(Bytes);
1304 continue;
1305 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001306 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1307 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001308 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001309 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1310 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001311
Bill Wendling34c2eb22012-12-04 23:40:58 +00001312 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001313 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001314 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001315 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001316 case lltok::kw_nest:
1317 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001318 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001319 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001320 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001321 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001322
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001323 case lltok::kw_alignstack:
1324 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001325 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001326 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001327 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001328 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001329 case lltok::kw_minsize:
1330 case lltok::kw_naked:
1331 case lltok::kw_nobuiltin:
1332 case lltok::kw_noduplicate:
1333 case lltok::kw_noimplicitfloat:
1334 case lltok::kw_noinline:
1335 case lltok::kw_nonlazybind:
1336 case lltok::kw_noredzone:
1337 case lltok::kw_noreturn:
1338 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001339 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001340 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001341 case lltok::kw_returns_twice:
1342 case lltok::kw_sanitize_address:
1343 case lltok::kw_sanitize_memory:
1344 case lltok::kw_sanitize_thread:
1345 case lltok::kw_ssp:
1346 case lltok::kw_sspreq:
1347 case lltok::kw_sspstrong:
1348 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001349 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001350 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001351
1352 case lltok::kw_readnone:
1353 case lltok::kw_readonly:
1354 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001355 }
1356
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357 Lex.Lex();
1358 }
1359}
1360
1361/// ParseOptionalLinkage
1362/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001363/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364/// ::= 'internal'
1365/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001366/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001367/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001368/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001369/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001370/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001371/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372/// ::= 'extern_weak'
1373/// ::= 'external'
1374bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1375 HasLinkage = false;
1376 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001377 default: Res=GlobalValue::ExternalLinkage; return false;
1378 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001379 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1380 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1381 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1382 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1383 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001384 case lltok::kw_available_externally:
1385 Res = GlobalValue::AvailableExternallyLinkage;
1386 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001387 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001388 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001389 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1390 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391 }
1392 Lex.Lex();
1393 HasLinkage = true;
1394 return false;
1395}
1396
1397/// ParseOptionalVisibility
1398/// ::= /*empty*/
1399/// ::= 'default'
1400/// ::= 'hidden'
1401/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001402///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001403bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1404 switch (Lex.getKind()) {
1405 default: Res = GlobalValue::DefaultVisibility; return false;
1406 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1407 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1408 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1409 }
1410 Lex.Lex();
1411 return false;
1412}
1413
Nico Rieck7157bb72014-01-14 15:22:47 +00001414/// ParseOptionalDLLStorageClass
1415/// ::= /*empty*/
1416/// ::= 'dllimport'
1417/// ::= 'dllexport'
1418///
1419bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1420 switch (Lex.getKind()) {
1421 default: Res = GlobalValue::DefaultStorageClass; return false;
1422 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1423 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1424 }
1425 Lex.Lex();
1426 return false;
1427}
1428
Chris Lattnerac161bf2009-01-02 07:01:27 +00001429/// ParseOptionalCallingConv
1430/// ::= /*empty*/
1431/// ::= 'ccc'
1432/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001433/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001434/// ::= 'coldcc'
1435/// ::= 'x86_stdcallcc'
1436/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001437/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001438/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001439/// ::= 'arm_apcscc'
1440/// ::= 'arm_aapcscc'
1441/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001442/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001443/// ::= 'ptx_kernel'
1444/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001445/// ::= 'spir_func'
1446/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001447/// ::= 'x86_64_sysvcc'
1448/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001449/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001450/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001451/// ::= 'preserve_mostcc'
1452/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001453/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001454/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001455///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001456bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001457 switch (Lex.getKind()) {
1458 default: CC = CallingConv::C; return false;
1459 case lltok::kw_ccc: CC = CallingConv::C; break;
1460 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1461 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1462 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1463 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001464 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001465 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001466 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1467 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1468 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001469 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001470 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1471 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001472 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1473 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001474 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001475 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1476 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001477 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001478 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001479 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1480 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001481 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001482 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001483 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001484 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001485 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001486 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001487
Chris Lattnerac161bf2009-01-02 07:01:27 +00001488 Lex.Lex();
1489 return false;
1490}
1491
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001492/// ParseMetadataAttachment
1493/// ::= !dbg !42
1494bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1495 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1496
1497 std::string Name = Lex.getStrVal();
1498 Kind = M->getMDKindID(Name);
1499 Lex.Lex();
1500
1501 return ParseMDNode(MD);
1502}
1503
Chris Lattner5c427632009-12-30 05:31:19 +00001504/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001505/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001506bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001507 do {
1508 if (Lex.getKind() != lltok::MetadataVar)
1509 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001510
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001511 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001512 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001513 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001514 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001515
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001516 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001517 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001518 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001519
Chris Lattner596760d2009-12-29 21:25:40 +00001520 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001521 } while (EatIfPresent(lltok::comma));
1522 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001523}
1524
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001525/// ParseOptionalFunctionMetadata
1526/// ::= (!dbg !57)*
1527bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1528 while (Lex.getKind() == lltok::MetadataVar) {
1529 unsigned MDK;
1530 MDNode *N;
1531 if (ParseMetadataAttachment(MDK, N))
1532 return true;
1533
1534 F.setMetadata(MDK, N);
1535 }
1536 return false;
1537}
1538
Chris Lattnerac161bf2009-01-02 07:01:27 +00001539/// ParseOptionalAlignment
1540/// ::= /* empty */
1541/// ::= 'align' 4
1542bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1543 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001544 if (!EatIfPresent(lltok::kw_align))
1545 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001546 LocTy AlignLoc = Lex.getLoc();
1547 if (ParseUInt32(Alignment)) return true;
1548 if (!isPowerOf2_32(Alignment))
1549 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001550 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001551 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001552 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001553}
1554
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001555/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001556/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001557/// ::= AttrKind '(' 4 ')'
1558///
1559/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1560bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1561 uint64_t &Bytes) {
1562 assert((AttrKind == lltok::kw_dereferenceable ||
1563 AttrKind == lltok::kw_dereferenceable_or_null) &&
1564 "contract!");
1565
Hal Finkelb0407ba2014-07-18 15:51:28 +00001566 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001567 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001568 return false;
1569 LocTy ParenLoc = Lex.getLoc();
1570 if (!EatIfPresent(lltok::lparen))
1571 return Error(ParenLoc, "expected '('");
1572 LocTy DerefLoc = Lex.getLoc();
1573 if (ParseUInt64(Bytes)) return true;
1574 ParenLoc = Lex.getLoc();
1575 if (!EatIfPresent(lltok::rparen))
1576 return Error(ParenLoc, "expected ')'");
1577 if (!Bytes)
1578 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1579 return false;
1580}
1581
Chris Lattnerb2f39502009-12-30 05:44:30 +00001582/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001583/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001584/// ::= ',' align 4
1585///
1586/// This returns with AteExtraComma set to true if it ate an excess comma at the
1587/// end.
1588bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1589 bool &AteExtraComma) {
1590 AteExtraComma = false;
1591 while (EatIfPresent(lltok::comma)) {
1592 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001593 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001594 AteExtraComma = true;
1595 return false;
1596 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001597
Chris Lattner95b0ff42010-04-23 00:50:50 +00001598 if (Lex.getKind() != lltok::kw_align)
1599 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001600
Chris Lattner95b0ff42010-04-23 00:50:50 +00001601 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001602 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001603
Devang Patelea8a4b92009-09-17 23:04:48 +00001604 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001605}
1606
Eli Friedmanfee02c62011-07-25 23:16:38 +00001607/// ParseScopeAndOrdering
1608/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1609/// else: ::=
1610///
1611/// This sets Scope and Ordering to the parsed values.
1612bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1613 AtomicOrdering &Ordering) {
1614 if (!isAtomic)
1615 return false;
1616
1617 Scope = CrossThread;
1618 if (EatIfPresent(lltok::kw_singlethread))
1619 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001620
1621 return ParseOrdering(Ordering);
1622}
1623
1624/// ParseOrdering
1625/// ::= AtomicOrdering
1626///
1627/// This sets Ordering to the parsed value.
1628bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001629 switch (Lex.getKind()) {
1630 default: return TokError("Expected ordering on atomic instruction");
1631 case lltok::kw_unordered: Ordering = Unordered; break;
1632 case lltok::kw_monotonic: Ordering = Monotonic; break;
1633 case lltok::kw_acquire: Ordering = Acquire; break;
1634 case lltok::kw_release: Ordering = Release; break;
1635 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1636 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1637 }
1638 Lex.Lex();
1639 return false;
1640}
1641
Charles Davisbe5557e2010-02-12 00:31:15 +00001642/// ParseOptionalStackAlignment
1643/// ::= /* empty */
1644/// ::= 'alignstack' '(' 4 ')'
1645bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1646 Alignment = 0;
1647 if (!EatIfPresent(lltok::kw_alignstack))
1648 return false;
1649 LocTy ParenLoc = Lex.getLoc();
1650 if (!EatIfPresent(lltok::lparen))
1651 return Error(ParenLoc, "expected '('");
1652 LocTy AlignLoc = Lex.getLoc();
1653 if (ParseUInt32(Alignment)) return true;
1654 ParenLoc = Lex.getLoc();
1655 if (!EatIfPresent(lltok::rparen))
1656 return Error(ParenLoc, "expected ')'");
1657 if (!isPowerOf2_32(Alignment))
1658 return Error(AlignLoc, "stack alignment is not a power of two");
1659 return false;
1660}
Devang Patelea8a4b92009-09-17 23:04:48 +00001661
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001662/// ParseIndexList - This parses the index list for an insert/extractvalue
1663/// instruction. This sets AteExtraComma in the case where we eat an extra
1664/// comma at the end of the line and find that it is followed by metadata.
1665/// Clients that don't allow metadata can call the version of this function that
1666/// only takes one argument.
1667///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001668/// ParseIndexList
1669/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001670///
1671bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1672 bool &AteExtraComma) {
1673 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001674
Chris Lattnerac161bf2009-01-02 07:01:27 +00001675 if (Lex.getKind() != lltok::comma)
1676 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001677
Chris Lattner3822f632009-01-02 08:05:26 +00001678 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001679 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001680 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001681 AteExtraComma = true;
1682 return false;
1683 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001684 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001685 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 Indices.push_back(Idx);
1687 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001688
Chris Lattnerac161bf2009-01-02 07:01:27 +00001689 return false;
1690}
1691
1692//===----------------------------------------------------------------------===//
1693// Type Parsing.
1694//===----------------------------------------------------------------------===//
1695
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001696/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001697bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001698 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001699 switch (Lex.getKind()) {
1700 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001701 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001702 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001703 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001705 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001706 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001707 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001708 // Type ::= StructType
1709 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001710 return true;
1711 break;
1712 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001714 Lex.Lex(); // eat the lsquare.
1715 if (ParseArrayVectorType(Result, false))
1716 return true;
1717 break;
1718 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001719 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001720 Lex.Lex();
1721 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001722 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001723 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 } else if (ParseArrayVectorType(Result, true))
1726 return true;
1727 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001728 case lltok::LocalVar: {
1729 // Type ::= %foo
1730 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001731
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 // If the type hasn't been defined yet, create a forward definition and
1733 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001734 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001735 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001736 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001738 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 Lex.Lex();
1740 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001742
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 case lltok::LocalVarID: {
1744 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001746
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 // If the type hasn't been defined yet, create a forward definition and
1748 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001749 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001750 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 Lex.Lex();
1755 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756 }
1757 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001758
1759 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760 while (1) {
1761 switch (Lex.getKind()) {
1762 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763 default:
1764 if (!AllowVoid && Result->isVoidTy())
1765 return Error(TypeLoc, "void type only allowed for function results");
1766 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001767
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001768 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001769 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001770 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 if (Result->isVoidTy())
1773 return TokError("pointers to void are invalid - use i8* instead");
1774 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001775 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001776 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001777 Lex.Lex();
1778 break;
1779
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001780 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001781 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001782 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001783 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001784 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001785 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001786 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001787 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001788 unsigned AddrSpace;
1789 if (ParseOptionalAddrSpace(AddrSpace) ||
1790 ParseToken(lltok::star, "expected '*' in address space"))
1791 return true;
1792
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001794 break;
1795 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001796
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1798 case lltok::lparen:
1799 if (ParseFunctionType(Result))
1800 return true;
1801 break;
1802 }
1803 }
1804}
1805
1806/// ParseParameterList
1807/// ::= '(' ')'
1808/// ::= '(' Arg (',' Arg)* ')'
1809/// Arg
1810/// ::= Type OptionalAttributes Value OptionalAttributes
1811bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001812 PerFunctionState &PFS, bool IsMustTailCall,
1813 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 if (ParseToken(lltok::lparen, "expected '(' in call"))
1815 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001816
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001817 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001818 while (Lex.getKind() != lltok::rparen) {
1819 // If this isn't the first argument, we need a comma.
1820 if (!ArgList.empty() &&
1821 ParseToken(lltok::comma, "expected ',' in argument list"))
1822 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001823
Reid Kleckner83498642014-08-26 00:33:28 +00001824 // Parse an ellipsis if this is a musttail call in a variadic function.
1825 if (Lex.getKind() == lltok::dotdotdot) {
1826 const char *Msg = "unexpected ellipsis in argument list for ";
1827 if (!IsMustTailCall)
1828 return TokError(Twine(Msg) + "non-musttail call");
1829 if (!InVarArgsFunc)
1830 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1831 Lex.Lex(); // Lex the '...', it is purely for readability.
1832 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1833 }
1834
Chris Lattnerac161bf2009-01-02 07:01:27 +00001835 // Parse the argument.
1836 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001837 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001838 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001840 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001841 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001842
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001843 if (ArgTy->isMetadataTy()) {
1844 if (ParseMetadataAsValue(V, PFS))
1845 return true;
1846 } else {
1847 // Otherwise, handle normal operands.
1848 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1849 return true;
1850 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001851 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1852 AttrIndex++,
1853 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 }
1855
Reid Kleckner83498642014-08-26 00:33:28 +00001856 if (IsMustTailCall && InVarArgsFunc)
1857 return TokError("expected '...' at end of argument list for musttail call "
1858 "in varargs function");
1859
Chris Lattnerac161bf2009-01-02 07:01:27 +00001860 Lex.Lex(); // Lex the ')'.
1861 return false;
1862}
1863
1864
1865
Chris Lattner2ed06b42009-01-05 18:34:07 +00001866/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868/// ::= '(' ArgTypeListI ')'
1869/// ArgTypeListI
1870/// ::= /*empty*/
1871/// ::= '...'
1872/// ::= ArgTypeList ',' '...'
1873/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001874///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001875bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1876 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001877 isVarArg = false;
1878 assert(Lex.getKind() == lltok::lparen);
1879 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001880
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881 if (Lex.getKind() == lltok::rparen) {
1882 // empty
1883 } else if (Lex.getKind() == lltok::dotdotdot) {
1884 isVarArg = true;
1885 Lex.Lex();
1886 } else {
1887 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001888 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001889 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001890 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001891
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001893 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001894
Chris Lattnerfdd87902009-10-05 05:54:46 +00001895 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001896 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001897
Chris Lattnerdef19492011-06-17 06:36:20 +00001898 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001899 Name = Lex.getStrVal();
1900 Lex.Lex();
1901 }
Chris Lattner3822f632009-01-02 08:05:26 +00001902
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001903 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001904 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001906 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001907 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001908 AttributeSet::get(ArgTy->getContext(),
1909 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001910
Chris Lattner3822f632009-01-02 08:05:26 +00001911 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001912 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001913 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001915 break;
1916 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001917
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918 // Otherwise must be an argument type.
1919 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001920 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001921
Chris Lattnerfdd87902009-10-05 05:54:46 +00001922 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001923 return Error(TypeLoc, "argument can not have void type");
1924
Chris Lattnerdef19492011-06-17 06:36:20 +00001925 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001926 Name = Lex.getStrVal();
1927 Lex.Lex();
1928 } else {
1929 Name = "";
1930 }
Chris Lattner3822f632009-01-02 08:05:26 +00001931
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001933 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001934
Bill Wendlingd079a442012-10-15 04:46:55 +00001935 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001936 AttributeSet::get(ArgTy->getContext(),
1937 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001938 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001939 }
1940 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001941
Chris Lattner3822f632009-01-02 08:05:26 +00001942 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945/// ParseFunctionType
1946/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001947bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001948 assert(Lex.getKind() == lltok::lparen);
1949
Chris Lattnerce473c72009-01-05 08:04:33 +00001950 if (!FunctionType::isValidReturnType(Result))
1951 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001952
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001953 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001957
Chris Lattnerac161bf2009-01-02 07:01:27 +00001958 // Reject names on the arguments lists.
1959 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1960 if (!ArgList[i].Name.empty())
1961 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001962 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001963 return Error(ArgList[i].Loc,
1964 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001966
Jay Foadb804a2b2011-07-12 14:06:48 +00001967 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001969 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001971 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001972 return false;
1973}
1974
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001975/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1976/// other structs.
1977bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1978 SmallVector<Type*, 8> Elts;
1979 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001980
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981 Result = StructType::get(Context, Elts, Packed);
1982 return false;
1983}
1984
1985/// ParseStructDefinition - Parse a struct in a 'type' definition.
1986bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1987 std::pair<Type*, LocTy> &Entry,
1988 Type *&ResultTy) {
1989 // If the type was already defined, diagnose the redefinition.
1990 if (Entry.first && !Entry.second.isValid())
1991 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 // If we have opaque, just return without filling in the definition for the
1994 // struct. This counts as a definition as far as the .ll file goes.
1995 if (EatIfPresent(lltok::kw_opaque)) {
1996 // This type is being defined, so clear the location to indicate this.
1997 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001998
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002000 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002001 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002 ResultTy = Entry.first;
2003 return false;
2004 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002005
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002006 // If the type starts with '<', then it is either a packed struct or a vector.
2007 bool isPacked = EatIfPresent(lltok::less);
2008
2009 // If we don't have a struct, then we have a random type alias, which we
2010 // accept for compatibility with old files. These types are not allowed to be
2011 // forward referenced and not allowed to be recursive.
2012 if (Lex.getKind() != lltok::lbrace) {
2013 if (Entry.first)
2014 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002015
Craig Topper2617dcc2014-04-15 06:32:26 +00002016 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 if (isPacked)
2018 return ParseArrayVectorType(ResultTy, true);
2019 return ParseType(ResultTy);
2020 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002021
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 // This type is being defined, so clear the location to indicate this.
2023 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002024
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002026 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002027 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002028
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002029 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 SmallVector<Type*, 8> Body;
2032 if (ParseStructBody(Body) ||
2033 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2034 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002035
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002036 STy->setBody(Body, isPacked);
2037 ResultTy = STy;
2038 return false;
2039}
2040
2041
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047/// ::= '<' '{' Type (',' Type)* '}' '>'
2048bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002049 assert(Lex.getKind() == lltok::lbrace);
2050 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002051
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052 // Handle the empty struct.
2053 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055
Chris Lattnerf880ca22009-03-09 04:49:14 +00002056 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002057 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058 if (ParseType(Ty)) return true;
2059 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002060
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002062 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002063
Chris Lattner3822f632009-01-02 08:05:26 +00002064 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002065 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002066 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002067
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002068 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002069 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002070
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002071 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075}
2076
2077/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2078/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002079/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080/// ::= '[' APSINTVAL 'x' Types ']'
2081/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002082bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2084 Lex.getAPSIntVal().getBitWidth() > 64)
2085 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002086
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 LocTy SizeLoc = Lex.getLoc();
2088 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002089 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002090
Chris Lattner3822f632009-01-02 08:05:26 +00002091 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2092 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093
2094 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002095 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002096 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002097
Chris Lattner3822f632009-01-02 08:05:26 +00002098 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2099 "expected end of sequential type"))
2100 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002103 if (Size == 0)
2104 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 if ((unsigned)Size != Size)
2106 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002107 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002108 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002109 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002111 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002112 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 }
2115 return false;
2116}
2117
2118//===----------------------------------------------------------------------===//
2119// Function Semantic Analysis.
2120//===----------------------------------------------------------------------===//
2121
Chris Lattner3432c622009-10-28 03:39:23 +00002122LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2123 int functionNumber)
2124 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125
2126 // Insert unnamed arguments into the NumberedVals list.
2127 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2128 AI != E; ++AI)
2129 if (!AI->hasName())
2130 NumberedVals.push_back(AI);
2131}
2132
2133LLParser::PerFunctionState::~PerFunctionState() {
2134 // If there were any forward referenced non-basicblock values, delete them.
2135 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2136 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2137 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002138 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002139 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002141 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002143
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2145 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2146 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002147 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002148 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002150 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 }
2152}
2153
Chris Lattner3432c622009-10-28 03:39:23 +00002154bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155 if (!ForwardRefVals.empty())
2156 return P.Error(ForwardRefVals.begin()->second.second,
2157 "use of undefined value '%" + ForwardRefVals.begin()->first +
2158 "'");
2159 if (!ForwardRefValIDs.empty())
2160 return P.Error(ForwardRefValIDs.begin()->second.second,
2161 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002162 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 return false;
2164}
2165
2166
2167/// GetVal - Get a value with the specified name or ID, creating a
2168/// forward reference record if needed. This can return null if the value
2169/// exists but does not have the right type.
2170Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002171 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 // Look this name up in the normal function symbol table.
2173 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002174
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 // If this is a forward reference for the value, see if we already created a
2176 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002177 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2179 I = ForwardRefVals.find(Name);
2180 if (I != ForwardRefVals.end())
2181 Val = I->second.first;
2182 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002183
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 // If we have the value in the symbol table or fwd-ref table, return it.
2185 if (Val) {
2186 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002187 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002188 P.Error(Loc, "'%" + Name + "' is not a basic block");
2189 else
2190 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002191 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002192 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002194
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002196 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002198 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 // Otherwise, create a new forward reference for this value and remember it.
2202 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002203 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002204 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 else
2206 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002207
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2209 return FwdVal;
2210}
2211
Chris Lattner229907c2011-07-18 04:54:35 +00002212Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 LocTy Loc) {
2214 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002215 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 // If this is a forward reference for the value, see if we already created a
2218 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002219 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002220 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2221 I = ForwardRefValIDs.find(ID);
2222 if (I != ForwardRefValIDs.end())
2223 Val = I->second.first;
2224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002225
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226 // If we have the value in the symbol table or fwd-ref table, return it.
2227 if (Val) {
2228 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002229 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002230 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002232 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002233 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002234 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002237 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002238 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002239 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002240 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002241
Chris Lattnerac161bf2009-01-02 07:01:27 +00002242 // Otherwise, create a new forward reference for this value and remember it.
2243 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002244 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002245 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 else
2247 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2250 return FwdVal;
2251}
2252
2253/// SetInstName - After an instruction is parsed and inserted into its
2254/// basic block, this installs its name.
2255bool LLParser::PerFunctionState::SetInstName(int NameID,
2256 const std::string &NameStr,
2257 LocTy NameLoc, Instruction *Inst) {
2258 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002259 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 if (NameID != -1 || !NameStr.empty())
2261 return P.Error(NameLoc, "instructions returning void cannot have a name");
2262 return false;
2263 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002264
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 // If this was a numbered instruction, verify that the instruction is the
2266 // expected value and resolve any forward references.
2267 if (NameStr.empty()) {
2268 // If neither a name nor an ID was specified, just use the next ID.
2269 if (NameID == -1)
2270 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002271
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 if (unsigned(NameID) != NumberedVals.size())
2273 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002274 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002275
Chris Lattnerac161bf2009-01-02 07:01:27 +00002276 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2277 ForwardRefValIDs.find(NameID);
2278 if (FI != ForwardRefValIDs.end()) {
2279 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002280 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002281 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002283 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284 ForwardRefValIDs.erase(FI);
2285 }
2286
2287 NumberedVals.push_back(Inst);
2288 return false;
2289 }
2290
2291 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2292 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2293 FI = ForwardRefVals.find(NameStr);
2294 if (FI != ForwardRefVals.end()) {
2295 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002296 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002297 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002298 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002299 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 ForwardRefVals.erase(FI);
2301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303 // Set the name on the instruction.
2304 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002305
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002306 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002307 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 NameStr + "'");
2309 return false;
2310}
2311
2312/// GetBB - Get a basic block with the specified name or ID, creating a
2313/// forward reference record if needed.
2314BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2315 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002316 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2317 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002318}
2319
2320BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002321 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2322 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323}
2324
2325/// DefineBB - Define the specified basic block, which is either named or
2326/// unnamed. If there is an error, this returns null otherwise it returns
2327/// the block being defined.
2328BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2329 LocTy Loc) {
2330 BasicBlock *BB;
2331 if (Name.empty())
2332 BB = GetBB(NumberedVals.size(), Loc);
2333 else
2334 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002335 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002336
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 // Move the block to the end of the function. Forward ref'd blocks are
2338 // inserted wherever they happen to be referenced.
2339 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002340
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 // Remove the block from forward ref sets.
2342 if (Name.empty()) {
2343 ForwardRefValIDs.erase(NumberedVals.size());
2344 NumberedVals.push_back(BB);
2345 } else {
2346 // BB forward references are already in the function symbol table.
2347 ForwardRefVals.erase(Name);
2348 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 return BB;
2351}
2352
2353//===----------------------------------------------------------------------===//
2354// Constants.
2355//===----------------------------------------------------------------------===//
2356
2357/// ParseValID - Parse an abstract value that doesn't necessarily have a
2358/// type implied. For example, if we parse "4" we don't know what integer type
2359/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002360/// sanity. PFS is used to convert function-local operands of metadata (since
2361/// metadata operands are not just parsed here but also converted to values).
2362/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002363bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 ID.Loc = Lex.getLoc();
2365 switch (Lex.getKind()) {
2366 default: return TokError("expected value token");
2367 case lltok::GlobalID: // @42
2368 ID.UIntVal = Lex.getUIntVal();
2369 ID.Kind = ValID::t_GlobalID;
2370 break;
2371 case lltok::GlobalVar: // @foo
2372 ID.StrVal = Lex.getStrVal();
2373 ID.Kind = ValID::t_GlobalName;
2374 break;
2375 case lltok::LocalVarID: // %42
2376 ID.UIntVal = Lex.getUIntVal();
2377 ID.Kind = ValID::t_LocalID;
2378 break;
2379 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380 ID.StrVal = Lex.getStrVal();
2381 ID.Kind = ValID::t_LocalName;
2382 break;
2383 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 ID.Kind = ValID::t_APSInt;
2386 break;
2387 case lltok::APFloat:
2388 ID.APFloatVal = Lex.getAPFloatVal();
2389 ID.Kind = ValID::t_APFloat;
2390 break;
2391 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002392 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 ID.Kind = ValID::t_Constant;
2394 break;
2395 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002396 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 ID.Kind = ValID::t_Constant;
2398 break;
2399 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2400 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2401 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002402
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 case lltok::lbrace: {
2404 // ValID ::= '{' ConstVector '}'
2405 Lex.Lex();
2406 SmallVector<Constant*, 16> Elts;
2407 if (ParseGlobalValueVector(Elts) ||
2408 ParseToken(lltok::rbrace, "expected end of struct constant"))
2409 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002410
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002411 ID.ConstantStructElts = new Constant*[Elts.size()];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002412 ID.UIntVal = Elts.size();
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002413 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002414 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 return false;
2416 }
2417 case lltok::less: {
2418 // ValID ::= '<' ConstVector '>' --> Vector.
2419 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2420 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002421 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002422
Chris Lattnerac161bf2009-01-02 07:01:27 +00002423 SmallVector<Constant*, 16> Elts;
2424 LocTy FirstEltLoc = Lex.getLoc();
2425 if (ParseGlobalValueVector(Elts) ||
2426 (isPackedStruct &&
2427 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2428 ParseToken(lltok::greater, "expected end of constant"))
2429 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002430
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 if (isPackedStruct) {
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002432 ID.ConstantStructElts = new Constant*[Elts.size()];
2433 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002434 ID.UIntVal = Elts.size();
2435 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 return false;
2437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002438
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439 if (Elts.empty())
2440 return Error(ID.Loc, "constant vector must not be empty");
2441
Duncan Sands9dff9be2010-02-15 16:12:20 +00002442 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002443 !Elts[0]->getType()->isFloatingPointTy() &&
2444 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002446 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002447
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 // Verify that all the vector elements have the same type.
2449 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2450 if (Elts[i]->getType() != Elts[0]->getType())
2451 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002452 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002453 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002454
Chris Lattner69229312011-02-15 00:14:00 +00002455 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 ID.Kind = ValID::t_Constant;
2457 return false;
2458 }
2459 case lltok::lsquare: { // Array Constant
2460 Lex.Lex();
2461 SmallVector<Constant*, 16> Elts;
2462 LocTy FirstEltLoc = Lex.getLoc();
2463 if (ParseGlobalValueVector(Elts) ||
2464 ParseToken(lltok::rsquare, "expected end of array constant"))
2465 return true;
2466
2467 // Handle empty element.
2468 if (Elts.empty()) {
2469 // Use undef instead of an array because it's inconvenient to determine
2470 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002471 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 return false;
2473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002476 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002477 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002478
Owen Anderson4056ca92009-07-29 22:17:13 +00002479 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002482 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 if (Elts[i]->getType() != Elts[0]->getType())
2484 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002485 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002486 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Jay Foad83be3612011-06-22 09:24:39 +00002489 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 ID.Kind = ValID::t_Constant;
2491 return false;
2492 }
2493 case lltok::kw_c: // c "foo"
2494 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002495 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2496 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2498 ID.Kind = ValID::t_Constant;
2499 return false;
2500
2501 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002502 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2503 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002504 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 Lex.Lex();
2506 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002507 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002508 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002509 ParseStringConstant(ID.StrVal) ||
2510 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 ParseToken(lltok::StringConstant, "expected constraint string"))
2512 return true;
2513 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002514 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002515 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 ID.Kind = ValID::t_InlineAsm;
2517 return false;
2518 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002519
Chris Lattner3432c622009-10-28 03:39:23 +00002520 case lltok::kw_blockaddress: {
2521 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2522 Lex.Lex();
2523
2524 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002525
Chris Lattner3432c622009-10-28 03:39:23 +00002526 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2527 ParseValID(Fn) ||
2528 ParseToken(lltok::comma, "expected comma in block address expression")||
2529 ParseValID(Label) ||
2530 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2531 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002532
Chris Lattner3432c622009-10-28 03:39:23 +00002533 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2534 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002535 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002536 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002537
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002538 // Try to find the function (but skip it if it's forward-referenced).
2539 GlobalValue *GV = nullptr;
2540 if (Fn.Kind == ValID::t_GlobalID) {
2541 if (Fn.UIntVal < NumberedVals.size())
2542 GV = NumberedVals[Fn.UIntVal];
2543 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2544 GV = M->getNamedValue(Fn.StrVal);
2545 }
2546 Function *F = nullptr;
2547 if (GV) {
2548 // Confirm that it's actually a function with a definition.
2549 if (!isa<Function>(GV))
2550 return Error(Fn.Loc, "expected function name in blockaddress");
2551 F = cast<Function>(GV);
2552 if (F->isDeclaration())
2553 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2554 }
2555
2556 if (!F) {
2557 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002558 GlobalValue *&FwdRef =
2559 ForwardRefBlockAddresses.insert(std::make_pair(
2560 std::move(Fn),
2561 std::map<ValID, GlobalValue *>()))
2562 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2563 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002564 if (!FwdRef)
2565 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2566 GlobalValue::InternalLinkage, nullptr, "");
2567 ID.ConstantVal = FwdRef;
2568 ID.Kind = ValID::t_Constant;
2569 return false;
2570 }
2571
2572 // We found the function; now find the basic block. Don't use PFS, since we
2573 // might be inside a constant expression.
2574 BasicBlock *BB;
2575 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2576 if (Label.Kind == ValID::t_LocalID)
2577 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2578 else
2579 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2580 if (!BB)
2581 return Error(Label.Loc, "referenced value is not a basic block");
2582 } else {
2583 if (Label.Kind == ValID::t_LocalID)
2584 return Error(Label.Loc, "cannot take address of numeric label after "
2585 "the function is defined");
2586 BB = dyn_cast_or_null<BasicBlock>(
2587 F->getValueSymbolTable().lookup(Label.StrVal));
2588 if (!BB)
2589 return Error(Label.Loc, "referenced value is not a basic block");
2590 }
2591
2592 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002593 ID.Kind = ValID::t_Constant;
2594 return false;
2595 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002596
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 case lltok::kw_trunc:
2598 case lltok::kw_zext:
2599 case lltok::kw_sext:
2600 case lltok::kw_fptrunc:
2601 case lltok::kw_fpext:
2602 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002603 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002604 case lltok::kw_uitofp:
2605 case lltok::kw_sitofp:
2606 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002607 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002609 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002610 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002611 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612 Constant *SrcVal;
2613 Lex.Lex();
2614 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2615 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002616 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 ParseType(DestTy) ||
2618 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2619 return true;
2620 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2621 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002622 getTypeString(SrcVal->getType()) + "' to '" +
2623 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002624 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002625 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 ID.Kind = ValID::t_Constant;
2627 return false;
2628 }
2629 case lltok::kw_extractvalue: {
2630 Lex.Lex();
2631 Constant *Val;
2632 SmallVector<unsigned, 4> Indices;
2633 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2634 ParseGlobalTypeAndValue(Val) ||
2635 ParseIndexList(Indices) ||
2636 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2637 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002638
Chris Lattner392be582010-02-12 20:49:41 +00002639 if (!Val->getType()->isAggregateType())
2640 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002641 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002642 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002643 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 ID.Kind = ValID::t_Constant;
2645 return false;
2646 }
2647 case lltok::kw_insertvalue: {
2648 Lex.Lex();
2649 Constant *Val0, *Val1;
2650 SmallVector<unsigned, 4> Indices;
2651 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2652 ParseGlobalTypeAndValue(Val0) ||
2653 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2654 ParseGlobalTypeAndValue(Val1) ||
2655 ParseIndexList(Indices) ||
2656 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2657 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002658 if (!Val0->getType()->isAggregateType())
2659 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002660 Type *IndexedType =
2661 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2662 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002664 if (IndexedType != Val1->getType())
2665 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2666 getTypeString(Val1->getType()) +
2667 "' instead of '" + getTypeString(IndexedType) +
2668 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002669 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 ID.Kind = ValID::t_Constant;
2671 return false;
2672 }
2673 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002674 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 unsigned PredVal, Opc = Lex.getUIntVal();
2676 Constant *Val0, *Val1;
2677 Lex.Lex();
2678 if (ParseCmpPredicate(PredVal, Opc) ||
2679 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2680 ParseGlobalTypeAndValue(Val0) ||
2681 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2682 ParseGlobalTypeAndValue(Val1) ||
2683 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2684 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002685
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 if (Val0->getType() != Val1->getType())
2687 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002688
Chris Lattnerac161bf2009-01-02 07:01:27 +00002689 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002692 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002694 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002695 } else {
2696 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002697 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002698 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002700 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701 }
2702 ID.Kind = ValID::t_Constant;
2703 return false;
2704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 // Binary Operators.
2707 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002708 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002710 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002712 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 case lltok::kw_udiv:
2714 case lltok::kw_sdiv:
2715 case lltok::kw_fdiv:
2716 case lltok::kw_urem:
2717 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002718 case lltok::kw_frem:
2719 case lltok::kw_shl:
2720 case lltok::kw_lshr:
2721 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002722 bool NUW = false;
2723 bool NSW = false;
2724 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002725 unsigned Opc = Lex.getUIntVal();
2726 Constant *Val0, *Val1;
2727 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002728 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002729 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2730 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002731 if (EatIfPresent(lltok::kw_nuw))
2732 NUW = true;
2733 if (EatIfPresent(lltok::kw_nsw)) {
2734 NSW = true;
2735 if (EatIfPresent(lltok::kw_nuw))
2736 NUW = true;
2737 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002738 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2739 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002740 if (EatIfPresent(lltok::kw_exact))
2741 Exact = true;
2742 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2744 ParseGlobalTypeAndValue(Val0) ||
2745 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2746 ParseGlobalTypeAndValue(Val1) ||
2747 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2748 return true;
2749 if (Val0->getType() != Val1->getType())
2750 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002751 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002752 if (NUW)
2753 return Error(ModifierLoc, "nuw only applies to integer operations");
2754 if (NSW)
2755 return Error(ModifierLoc, "nsw only applies to integer operations");
2756 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002757 // Check that the type is valid for the operator.
2758 switch (Opc) {
2759 case Instruction::Add:
2760 case Instruction::Sub:
2761 case Instruction::Mul:
2762 case Instruction::UDiv:
2763 case Instruction::SDiv:
2764 case Instruction::URem:
2765 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002766 case Instruction::Shl:
2767 case Instruction::AShr:
2768 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002769 if (!Val0->getType()->isIntOrIntVectorTy())
2770 return Error(ID.Loc, "constexpr requires integer operands");
2771 break;
2772 case Instruction::FAdd:
2773 case Instruction::FSub:
2774 case Instruction::FMul:
2775 case Instruction::FDiv:
2776 case Instruction::FRem:
2777 if (!Val0->getType()->isFPOrFPVectorTy())
2778 return Error(ID.Loc, "constexpr requires fp operands");
2779 break;
2780 default: llvm_unreachable("Unknown binary operator!");
2781 }
Dan Gohman1b849082009-09-07 23:54:19 +00002782 unsigned Flags = 0;
2783 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2784 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002785 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002786 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002787 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 ID.Kind = ValID::t_Constant;
2789 return false;
2790 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002791
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 case lltok::kw_and:
2794 case lltok::kw_or:
2795 case lltok::kw_xor: {
2796 unsigned Opc = Lex.getUIntVal();
2797 Constant *Val0, *Val1;
2798 Lex.Lex();
2799 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2800 ParseGlobalTypeAndValue(Val0) ||
2801 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2802 ParseGlobalTypeAndValue(Val1) ||
2803 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2804 return true;
2805 if (Val0->getType() != Val1->getType())
2806 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002807 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 return Error(ID.Loc,
2809 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002810 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 ID.Kind = ValID::t_Constant;
2812 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002813 }
2814
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 case lltok::kw_getelementptr:
2816 case lltok::kw_shufflevector:
2817 case lltok::kw_insertelement:
2818 case lltok::kw_extractelement:
2819 case lltok::kw_select: {
2820 unsigned Opc = Lex.getUIntVal();
2821 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002822 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002823 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002825
Dan Gohman1639c392009-07-27 21:53:46 +00002826 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002827 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002828
2829 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2830 return true;
2831
2832 LocTy ExplicitTypeLoc = Lex.getLoc();
2833 if (Opc == Instruction::GetElementPtr) {
2834 if (ParseType(Ty) ||
2835 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2836 return true;
2837 }
2838
2839 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2841 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002842
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002844 if (Elts.size() == 0 ||
2845 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002846 return Error(ID.Loc, "base of getelementptr must be a pointer");
2847
2848 Type *BaseType = Elts[0]->getType();
2849 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002850 if (Ty != BasePointerType->getElementType())
2851 return Error(
2852 ExplicitTypeLoc,
2853 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002854
Jay Foaded8db7d2011-07-21 14:31:17 +00002855 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002856 for (Constant *Val : Indices) {
2857 Type *ValTy = Val->getType();
2858 if (!ValTy->getScalarType()->isIntegerTy())
2859 return Error(ID.Loc, "getelementptr index must be an integer");
2860 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2861 return Error(ID.Loc, "getelementptr index type missmatch");
2862 if (ValTy->isVectorTy()) {
2863 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2864 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2865 if (ValNumEl != PtrNumEl)
2866 return Error(
2867 ID.Loc,
2868 "getelementptr vector index has a wrong number of elements");
2869 }
2870 }
2871
Owen Andersone90f9922015-03-10 06:34:57 +00002872 SmallPtrSet<const Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00002873 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002874 return Error(ID.Loc, "base element of getelementptr must be sized");
2875
David Blaikie4a2e73b2015-04-02 18:55:32 +00002876 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002877 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002878 ID.ConstantVal =
2879 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002880 } else if (Opc == Instruction::Select) {
2881 if (Elts.size() != 3)
2882 return Error(ID.Loc, "expected three operands to select");
2883 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2884 Elts[2]))
2885 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002886 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887 } else if (Opc == Instruction::ShuffleVector) {
2888 if (Elts.size() != 3)
2889 return Error(ID.Loc, "expected three operands to shufflevector");
2890 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2891 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002892 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002893 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 } else if (Opc == Instruction::ExtractElement) {
2895 if (Elts.size() != 2)
2896 return Error(ID.Loc, "expected two operands to extractelement");
2897 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2898 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002899 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002900 } else {
2901 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2902 if (Elts.size() != 3)
2903 return Error(ID.Loc, "expected three operands to insertelement");
2904 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2905 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002906 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002907 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002908 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002909
Chris Lattnerac161bf2009-01-02 07:01:27 +00002910 ID.Kind = ValID::t_Constant;
2911 return false;
2912 }
2913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002914
Chris Lattnerac161bf2009-01-02 07:01:27 +00002915 Lex.Lex();
2916 return false;
2917}
2918
2919/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002920bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002921 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002922 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002923 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002924 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002925 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002926 if (V && !(C = dyn_cast<Constant>(V)))
2927 return Error(ID.Loc, "global values must be constants");
2928 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929}
2930
Victor Hernandez9d75c962010-01-11 22:31:58 +00002931bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002932 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002933 return ParseType(Ty) ||
2934 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002935}
2936
Rafael Espindola83a362c2015-01-06 22:55:16 +00002937bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002938 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002939
2940 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002941 if (!EatIfPresent(lltok::kw_comdat))
2942 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002943
2944 if (EatIfPresent(lltok::lparen)) {
2945 if (Lex.getKind() != lltok::ComdatVar)
2946 return TokError("expected comdat variable");
2947 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2948 Lex.Lex();
2949 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2950 return true;
2951 } else {
2952 if (GlobalName.empty())
2953 return TokError("comdat cannot be unnamed");
2954 C = getComdat(GlobalName, KwLoc);
2955 }
2956
David Majnemerdad0a642014-06-27 18:19:56 +00002957 return false;
2958}
2959
Victor Hernandez9d75c962010-01-11 22:31:58 +00002960/// ParseGlobalValueVector
2961/// ::= /*empty*/
2962/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002963bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002964 // Empty list.
2965 if (Lex.getKind() == lltok::rbrace ||
2966 Lex.getKind() == lltok::rsquare ||
2967 Lex.getKind() == lltok::greater ||
2968 Lex.getKind() == lltok::rparen)
2969 return false;
2970
2971 Constant *C;
2972 if (ParseGlobalTypeAndValue(C)) return true;
2973 Elts.push_back(C);
2974
2975 while (EatIfPresent(lltok::comma)) {
2976 if (ParseGlobalTypeAndValue(C)) return true;
2977 Elts.push_back(C);
2978 }
2979
2980 return false;
2981}
2982
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002983bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002984 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002985 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002986 return true;
2987
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002988 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002989 return false;
2990}
2991
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002992/// MDNode:
2993/// ::= !{ ... }
2994/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002995/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002996bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002997 if (Lex.getKind() == lltok::MetadataVar)
2998 return ParseSpecializedMDNode(N);
2999
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003000 return ParseToken(lltok::exclaim, "expected '!' here") ||
3001 ParseMDNodeTail(N);
3002}
3003
3004bool LLParser::ParseMDNodeTail(MDNode *&N) {
3005 // !{ ... }
3006 if (Lex.getKind() == lltok::lbrace)
3007 return ParseMDTuple(N);
3008
3009 // !42
3010 return ParseMDNodeID(N);
3011}
3012
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003013namespace {
3014
3015/// Structure to represent an optional metadata field.
3016template <class FieldTy> struct MDFieldImpl {
3017 typedef MDFieldImpl ImplTy;
3018 FieldTy Val;
3019 bool Seen;
3020
3021 void assign(FieldTy Val) {
3022 Seen = true;
3023 this->Val = std::move(Val);
3024 }
3025
3026 explicit MDFieldImpl(FieldTy Default)
3027 : Val(std::move(Default)), Seen(false) {}
3028};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003029
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003030struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3031 uint64_t Max;
3032
3033 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3034 : ImplTy(Default), Max(Max) {}
3035};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003036struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003037 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003038};
3039struct ColumnField : public MDUnsignedField {
3040 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3041};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003042struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003043 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003044 DwarfTagField(dwarf::Tag DefaultTag)
3045 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003046};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003047struct DwarfAttEncodingField : public MDUnsignedField {
3048 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3049};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003050struct DwarfVirtualityField : public MDUnsignedField {
3051 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3052};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003053struct DwarfLangField : public MDUnsignedField {
3054 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3055};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003056
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003057struct DIFlagField : public MDUnsignedField {
3058 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3059};
3060
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003061struct MDSignedField : public MDFieldImpl<int64_t> {
3062 int64_t Min;
3063 int64_t Max;
3064
3065 MDSignedField(int64_t Default = 0)
3066 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3067 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3068 : ImplTy(Default), Min(Min), Max(Max) {}
3069};
3070
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003071struct MDBoolField : public MDFieldImpl<bool> {
3072 MDBoolField(bool Default = false) : ImplTy(Default) {}
3073};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003074struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003075 bool AllowNull;
3076
3077 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003078};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003079struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3080 MDConstant() : ImplTy(nullptr) {}
3081};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003082struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003083 bool AllowEmpty;
3084 MDStringField(bool AllowEmpty = true)
3085 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003086};
3087struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3088 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3089};
3090
3091} // end namespace
3092
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003093namespace llvm {
3094
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003095template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003096bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003097 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003098 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3099 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003100
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003101 auto &U = Lex.getAPSIntVal();
3102 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003103 return TokError("value for '" + Name + "' too large, limit is " +
3104 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003105 Result.assign(U.getZExtValue());
3106 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003107 Lex.Lex();
3108 return false;
3109}
3110
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003111template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003112bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3113 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3114}
3115template <>
3116bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3117 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3118}
3119
3120template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003121bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3122 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003123 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003124
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003125 if (Lex.getKind() != lltok::DwarfTag)
3126 return TokError("expected DWARF tag");
3127
3128 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3129 if (Tag == dwarf::DW_TAG_invalid)
3130 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003131 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003132
3133 Result.assign(Tag);
3134 Lex.Lex();
3135 return false;
3136}
3137
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003138template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003139bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3140 DwarfVirtualityField &Result) {
3141 if (Lex.getKind() == lltok::APSInt)
3142 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3143
3144 if (Lex.getKind() != lltok::DwarfVirtuality)
3145 return TokError("expected DWARF virtuality code");
3146
3147 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3148 if (!Virtuality)
3149 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3150 Lex.getStrVal() + "'");
3151 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3152 Result.assign(Virtuality);
3153 Lex.Lex();
3154 return false;
3155}
3156
3157template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003158bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3159 if (Lex.getKind() == lltok::APSInt)
3160 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3161
3162 if (Lex.getKind() != lltok::DwarfLang)
3163 return TokError("expected DWARF language");
3164
3165 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3166 if (!Lang)
3167 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3168 "'");
3169 assert(Lang <= Result.Max && "Expected valid DWARF language");
3170 Result.assign(Lang);
3171 Lex.Lex();
3172 return false;
3173}
3174
3175template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003176bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003177 DwarfAttEncodingField &Result) {
3178 if (Lex.getKind() == lltok::APSInt)
3179 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3180
3181 if (Lex.getKind() != lltok::DwarfAttEncoding)
3182 return TokError("expected DWARF type attribute encoding");
3183
3184 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3185 if (!Encoding)
3186 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3187 Lex.getStrVal() + "'");
3188 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3189 Result.assign(Encoding);
3190 Lex.Lex();
3191 return false;
3192}
3193
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003194/// DIFlagField
3195/// ::= uint32
3196/// ::= DIFlagVector
3197/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3198template <>
3199bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3200 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3201
3202 // Parser for a single flag.
3203 auto parseFlag = [&](unsigned &Val) {
3204 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3205 return ParseUInt32(Val);
3206
3207 if (Lex.getKind() != lltok::DIFlag)
3208 return TokError("expected debug info flag");
3209
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003210 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003211 if (!Val)
3212 return TokError(Twine("invalid debug info flag flag '") +
3213 Lex.getStrVal() + "'");
3214 Lex.Lex();
3215 return false;
3216 };
3217
3218 // Parse the flags and combine them together.
3219 unsigned Combined = 0;
3220 do {
3221 unsigned Val;
3222 if (parseFlag(Val))
3223 return true;
3224 Combined |= Val;
3225 } while (EatIfPresent(lltok::bar));
3226
3227 Result.assign(Combined);
3228 return false;
3229}
3230
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003231template <>
3232bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003233 MDSignedField &Result) {
3234 if (Lex.getKind() != lltok::APSInt)
3235 return TokError("expected signed integer");
3236
3237 auto &S = Lex.getAPSIntVal();
3238 if (S < Result.Min)
3239 return TokError("value for '" + Name + "' too small, limit is " +
3240 Twine(Result.Min));
3241 if (S > Result.Max)
3242 return TokError("value for '" + Name + "' too large, limit is " +
3243 Twine(Result.Max));
3244 Result.assign(S.getExtValue());
3245 assert(Result.Val >= Result.Min && "Expected value in range");
3246 assert(Result.Val <= Result.Max && "Expected value in range");
3247 Lex.Lex();
3248 return false;
3249}
3250
3251template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003252bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3253 switch (Lex.getKind()) {
3254 default:
3255 return TokError("expected 'true' or 'false'");
3256 case lltok::kw_true:
3257 Result.assign(true);
3258 break;
3259 case lltok::kw_false:
3260 Result.assign(false);
3261 break;
3262 }
3263 Lex.Lex();
3264 return false;
3265}
3266
3267template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003268bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003269 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003270 if (!Result.AllowNull)
3271 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003272 Lex.Lex();
3273 Result.assign(nullptr);
3274 return false;
3275 }
3276
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003277 Metadata *MD;
3278 if (ParseMetadata(MD, nullptr))
3279 return true;
3280
3281 Result.assign(MD);
3282 return false;
3283}
3284
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003285template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003286bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3287 Metadata *MD;
3288 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3289 return true;
3290
3291 Result.assign(cast<ConstantAsMetadata>(MD));
3292 return false;
3293}
3294
3295template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003296bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003297 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003298 std::string S;
3299 if (ParseStringConstant(S))
3300 return true;
3301
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003302 if (!Result.AllowEmpty && S.empty())
3303 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3304
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003305 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003306 return false;
3307}
3308
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003309template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003310bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3311 SmallVector<Metadata *, 4> MDs;
3312 if (ParseMDNodeVector(MDs))
3313 return true;
3314
3315 Result.assign(std::move(MDs));
3316 return false;
3317}
3318
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003319} // end namespace llvm
3320
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003321template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003322bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003323 do {
3324 if (Lex.getKind() != lltok::LabelStr)
3325 return TokError("expected field label here");
3326
3327 if (parseField())
3328 return true;
3329 } while (EatIfPresent(lltok::comma));
3330
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003331 return false;
3332}
3333
3334template <class ParserTy>
3335bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3336 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3337 Lex.Lex();
3338
3339 if (ParseToken(lltok::lparen, "expected '(' here"))
3340 return true;
3341 if (Lex.getKind() != lltok::rparen)
3342 if (ParseMDFieldsImplBody(parseField))
3343 return true;
3344
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003345 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003346 return ParseToken(lltok::rparen, "expected ')' here");
3347}
3348
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003349template <class FieldTy>
3350bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3351 if (Result.Seen)
3352 return TokError("field '" + Name + "' cannot be specified more than once");
3353
3354 LocTy Loc = Lex.getLoc();
3355 Lex.Lex();
3356 return ParseMDField(Loc, Name, Result);
3357}
3358
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003359bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3360 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003361
3362#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003363 if (Lex.getStrVal() == #CLASS) \
3364 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003365#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003366
3367 return TokError("expected metadata type");
3368}
3369
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003370#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3371#define NOP_FIELD(NAME, TYPE, INIT)
3372#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3373 if (!NAME.Seen) \
3374 return Error(ClosingLoc, "missing required field '" #NAME "'");
3375#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003376 if (Lex.getStrVal() == #NAME) \
3377 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003378#define PARSE_MD_FIELDS() \
3379 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3380 do { \
3381 LocTy ClosingLoc; \
3382 if (ParseMDFieldsImpl([&]() -> bool { \
3383 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3384 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3385 }, ClosingLoc)) \
3386 return true; \
3387 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3388 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003389#define GET_OR_DISTINCT(CLASS, ARGS) \
3390 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003391
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003392/// ParseDILocationFields:
3393/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3394bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003395#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003396 OPTIONAL(line, LineField, ); \
3397 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003398 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003399 OPTIONAL(inlinedAt, MDField, );
3400 PARSE_MD_FIELDS();
3401#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003402
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003403 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003404 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003405 return false;
3406}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003407
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003408/// ParseGenericDINode:
3409/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3410bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003411#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003412 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003413 OPTIONAL(header, MDStringField, ); \
3414 OPTIONAL(operands, MDFieldList, );
3415 PARSE_MD_FIELDS();
3416#undef VISIT_MD_FIELDS
3417
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003418 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003419 (Context, tag.Val, header.Val, operands.Val));
3420 return false;
3421}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003422
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003423/// ParseDISubrange:
3424/// ::= !DISubrange(count: 30, lowerBound: 2)
3425bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003426#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003427 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003428 OPTIONAL(lowerBound, MDSignedField, );
3429 PARSE_MD_FIELDS();
3430#undef VISIT_MD_FIELDS
3431
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003432 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003433 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003434}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003435
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003436/// ParseDIEnumerator:
3437/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3438bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003439#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003440 REQUIRED(name, MDStringField, ); \
3441 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003442 PARSE_MD_FIELDS();
3443#undef VISIT_MD_FIELDS
3444
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003445 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003446 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003447}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003448
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003449/// ParseDIBasicType:
3450/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3451bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003452#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003453 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003454 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003455 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3456 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003457 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003458 PARSE_MD_FIELDS();
3459#undef VISIT_MD_FIELDS
3460
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003461 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003462 align.Val, encoding.Val));
3463 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003464}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003465
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003466/// ParseDIDerivedType:
3467/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003468/// line: 7, scope: !1, baseType: !2, size: 32,
3469/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003470bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003471#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3472 REQUIRED(tag, DwarfTagField, ); \
3473 OPTIONAL(name, MDStringField, ); \
3474 OPTIONAL(file, MDField, ); \
3475 OPTIONAL(line, LineField, ); \
3476 OPTIONAL(scope, MDField, ); \
3477 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003478 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3479 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3480 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003481 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003482 OPTIONAL(extraData, MDField, );
3483 PARSE_MD_FIELDS();
3484#undef VISIT_MD_FIELDS
3485
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003486 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003487 (Context, tag.Val, name.Val, file.Val, line.Val,
3488 scope.Val, baseType.Val, size.Val, align.Val,
3489 offset.Val, flags.Val, extraData.Val));
3490 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003491}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003492
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003493bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003494#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3495 REQUIRED(tag, DwarfTagField, ); \
3496 OPTIONAL(name, MDStringField, ); \
3497 OPTIONAL(file, MDField, ); \
3498 OPTIONAL(line, LineField, ); \
3499 OPTIONAL(scope, MDField, ); \
3500 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003501 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3502 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3503 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003504 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003505 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003506 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003507 OPTIONAL(vtableHolder, MDField, ); \
3508 OPTIONAL(templateParams, MDField, ); \
3509 OPTIONAL(identifier, MDStringField, );
3510 PARSE_MD_FIELDS();
3511#undef VISIT_MD_FIELDS
3512
3513 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003514 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003515 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3516 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3517 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3518 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003519}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003520
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003521bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003522#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003523 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003524 REQUIRED(types, MDField, );
3525 PARSE_MD_FIELDS();
3526#undef VISIT_MD_FIELDS
3527
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003528 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003529 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003530}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003531
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003532/// ParseDIFileType:
3533/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3534bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003535#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3536 REQUIRED(filename, MDStringField, ); \
3537 REQUIRED(directory, MDStringField, );
3538 PARSE_MD_FIELDS();
3539#undef VISIT_MD_FIELDS
3540
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003541 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003542 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003543}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003544
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003545/// ParseDICompileUnit:
3546/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003547/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3548/// splitDebugFilename: "abc.debug", emissionKind: 1,
3549/// enums: !1, retainedTypes: !2, subprograms: !3,
3550/// globals: !4, imports: !5)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003551bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003552#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3553 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003554 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003555 OPTIONAL(producer, MDStringField, ); \
3556 OPTIONAL(isOptimized, MDBoolField, ); \
3557 OPTIONAL(flags, MDStringField, ); \
3558 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3559 OPTIONAL(splitDebugFilename, MDStringField, ); \
3560 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3561 OPTIONAL(enums, MDField, ); \
3562 OPTIONAL(retainedTypes, MDField, ); \
3563 OPTIONAL(subprograms, MDField, ); \
3564 OPTIONAL(globals, MDField, ); \
3565 OPTIONAL(imports, MDField, );
3566 PARSE_MD_FIELDS();
3567#undef VISIT_MD_FIELDS
3568
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003569 Result = GET_OR_DISTINCT(DICompileUnit,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003570 (Context, language.Val, file.Val, producer.Val,
3571 isOptimized.Val, flags.Val, runtimeVersion.Val,
3572 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3573 retainedTypes.Val, subprograms.Val, globals.Val,
3574 imports.Val));
3575 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003576}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003577
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003578/// ParseDISubprogram:
3579/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003580/// file: !1, line: 7, type: !2, isLocal: false,
3581/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003582/// virtuality: DW_VIRTUALTIY_pure_virtual,
3583/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003584/// isOptimized: false, function: void ()* @_Z3foov,
3585/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003586bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003587#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3588 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003589 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003590 OPTIONAL(linkageName, MDStringField, ); \
3591 OPTIONAL(file, MDField, ); \
3592 OPTIONAL(line, LineField, ); \
3593 OPTIONAL(type, MDField, ); \
3594 OPTIONAL(isLocal, MDBoolField, ); \
3595 OPTIONAL(isDefinition, MDBoolField, (true)); \
3596 OPTIONAL(scopeLine, LineField, ); \
3597 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003598 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003599 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003600 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003601 OPTIONAL(isOptimized, MDBoolField, ); \
3602 OPTIONAL(function, MDConstant, ); \
3603 OPTIONAL(templateParams, MDField, ); \
3604 OPTIONAL(declaration, MDField, ); \
3605 OPTIONAL(variables, MDField, );
3606 PARSE_MD_FIELDS();
3607#undef VISIT_MD_FIELDS
3608
3609 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003610 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003611 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3612 scopeLine.Val, containingType.Val, virtuality.Val,
3613 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3614 templateParams.Val, declaration.Val, variables.Val));
3615 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003616}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003617
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003618/// ParseDILexicalBlock:
3619/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3620bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003621#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003622 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003623 OPTIONAL(file, MDField, ); \
3624 OPTIONAL(line, LineField, ); \
3625 OPTIONAL(column, ColumnField, );
3626 PARSE_MD_FIELDS();
3627#undef VISIT_MD_FIELDS
3628
3629 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003630 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003631 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003632}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003633
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003634/// ParseDILexicalBlockFile:
3635/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3636bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003637#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003638 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003639 OPTIONAL(file, MDField, ); \
3640 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3641 PARSE_MD_FIELDS();
3642#undef VISIT_MD_FIELDS
3643
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003644 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003645 (Context, scope.Val, file.Val, discriminator.Val));
3646 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003647}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003648
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003649/// ParseDINamespace:
3650/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3651bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003652#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3653 REQUIRED(scope, MDField, ); \
3654 OPTIONAL(file, MDField, ); \
3655 OPTIONAL(name, MDStringField, ); \
3656 OPTIONAL(line, LineField, );
3657 PARSE_MD_FIELDS();
3658#undef VISIT_MD_FIELDS
3659
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003660 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003661 (Context, scope.Val, file.Val, name.Val, line.Val));
3662 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003663}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003664
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003665/// ParseDITemplateTypeParameter:
3666/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3667bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003668#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003669 OPTIONAL(name, MDStringField, ); \
3670 REQUIRED(type, MDField, );
3671 PARSE_MD_FIELDS();
3672#undef VISIT_MD_FIELDS
3673
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003674 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003675 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003676 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003677}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003678
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003679/// ParseDITemplateValueParameter:
3680/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003681/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003682bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003683#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003684 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003685 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003686 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003687 REQUIRED(value, MDField, );
3688 PARSE_MD_FIELDS();
3689#undef VISIT_MD_FIELDS
3690
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003691 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003692 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003693 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003694}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003695
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003696/// ParseDIGlobalVariable:
3697/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003698/// file: !1, line: 7, type: !2, isLocal: false,
3699/// isDefinition: true, variable: i32* @foo,
3700/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003701bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003702#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003703 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003704 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003705 OPTIONAL(linkageName, MDStringField, ); \
3706 OPTIONAL(file, MDField, ); \
3707 OPTIONAL(line, LineField, ); \
3708 OPTIONAL(type, MDField, ); \
3709 OPTIONAL(isLocal, MDBoolField, ); \
3710 OPTIONAL(isDefinition, MDBoolField, (true)); \
3711 OPTIONAL(variable, MDConstant, ); \
3712 OPTIONAL(declaration, MDField, );
3713 PARSE_MD_FIELDS();
3714#undef VISIT_MD_FIELDS
3715
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003716 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003717 (Context, scope.Val, name.Val, linkageName.Val,
3718 file.Val, line.Val, type.Val, isLocal.Val,
3719 isDefinition.Val, variable.Val, declaration.Val));
3720 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003721}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003722
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003723/// ParseDILocalVariable:
3724/// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003725/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003726bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003727#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3728 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003729 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003730 OPTIONAL(name, MDStringField, ); \
3731 OPTIONAL(file, MDField, ); \
3732 OPTIONAL(line, LineField, ); \
3733 OPTIONAL(type, MDField, ); \
3734 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003735 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003736 PARSE_MD_FIELDS();
3737#undef VISIT_MD_FIELDS
3738
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003739 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003740 (Context, tag.Val, scope.Val, name.Val, file.Val,
3741 line.Val, type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003742 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003743}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003744
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003745/// ParseDIExpression:
3746/// ::= !DIExpression(0, 7, -1)
3747bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003748 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3749 Lex.Lex();
3750
3751 if (ParseToken(lltok::lparen, "expected '(' here"))
3752 return true;
3753
3754 SmallVector<uint64_t, 8> Elements;
3755 if (Lex.getKind() != lltok::rparen)
3756 do {
3757 if (Lex.getKind() == lltok::DwarfOp) {
3758 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3759 Lex.Lex();
3760 Elements.push_back(Op);
3761 continue;
3762 }
3763 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3764 }
3765
3766 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3767 return TokError("expected unsigned integer");
3768
3769 auto &U = Lex.getAPSIntVal();
3770 if (U.ugt(UINT64_MAX))
3771 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3772 Elements.push_back(U.getZExtValue());
3773 Lex.Lex();
3774 } while (EatIfPresent(lltok::comma));
3775
3776 if (ParseToken(lltok::rparen, "expected ')' here"))
3777 return true;
3778
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003779 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003780 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003781}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003782
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783/// ParseDIObjCProperty:
3784/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003785/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003786bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003787#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003788 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003789 OPTIONAL(file, MDField, ); \
3790 OPTIONAL(line, LineField, ); \
3791 OPTIONAL(setter, MDStringField, ); \
3792 OPTIONAL(getter, MDStringField, ); \
3793 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3794 OPTIONAL(type, MDField, );
3795 PARSE_MD_FIELDS();
3796#undef VISIT_MD_FIELDS
3797
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003798 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003799 (Context, name.Val, file.Val, line.Val, setter.Val,
3800 getter.Val, attributes.Val, type.Val));
3801 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003802}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003803
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003804/// ParseDIImportedEntity:
3805/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003806/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003807bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003808#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3809 REQUIRED(tag, DwarfTagField, ); \
3810 REQUIRED(scope, MDField, ); \
3811 OPTIONAL(entity, MDField, ); \
3812 OPTIONAL(line, LineField, ); \
3813 OPTIONAL(name, MDStringField, );
3814 PARSE_MD_FIELDS();
3815#undef VISIT_MD_FIELDS
3816
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003817 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003818 entity.Val, line.Val, name.Val));
3819 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003820}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003821
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003822#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003823#undef NOP_FIELD
3824#undef REQUIRE_FIELD
3825#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003826
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003827/// ParseMetadataAsValue
3828/// ::= metadata i32 %local
3829/// ::= metadata i32 @global
3830/// ::= metadata i32 7
3831/// ::= metadata !0
3832/// ::= metadata !{...}
3833/// ::= metadata !"string"
3834bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3835 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003836 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003837 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003838 return true;
3839
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003840 V = MetadataAsValue::get(Context, MD);
3841 return false;
3842}
3843
3844/// ParseValueAsMetadata
3845/// ::= i32 %local
3846/// ::= i32 @global
3847/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003848bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3849 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003850 Type *Ty;
3851 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003852 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003853 return true;
3854 if (Ty->isMetadataTy())
3855 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3856
3857 Value *V;
3858 if (ParseValue(Ty, V, PFS))
3859 return true;
3860
3861 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003862 return false;
3863}
3864
3865/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003866/// ::= i32 %local
3867/// ::= i32 @global
3868/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003869/// ::= !42
3870/// ::= !{...}
3871/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003872/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003873bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003874 if (Lex.getKind() == lltok::MetadataVar) {
3875 MDNode *N;
3876 if (ParseSpecializedMDNode(N))
3877 return true;
3878 MD = N;
3879 return false;
3880 }
3881
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003882 // ValueAsMetadata:
3883 // <type> <value>
3884 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003885 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003886
3887 // '!'.
3888 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3889 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003890
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003891 // MDString:
3892 // ::= '!' STRINGCONSTANT
3893 if (Lex.getKind() == lltok::StringConstant) {
3894 MDString *S;
3895 if (ParseMDString(S))
3896 return true;
3897 MD = S;
3898 return false;
3899 }
3900
Dan Gohman8939ba332010-07-14 18:26:50 +00003901 // MDNode:
3902 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003903 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003904 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003905 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003906 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003907 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003908 return false;
3909}
3910
Victor Hernandez9d75c962010-01-11 22:31:58 +00003911
3912//===----------------------------------------------------------------------===//
3913// Function Parsing.
3914//===----------------------------------------------------------------------===//
3915
Chris Lattner229907c2011-07-18 04:54:35 +00003916bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003917 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003918 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003919 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003920
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003922 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003923 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3924 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003925 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003926 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003927 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3928 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003929 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003930 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003931 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003932 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003933 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003934 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3935 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003936 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003937 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003938 return false;
3939 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003940 case ValID::t_GlobalName:
3941 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003942 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003943 case ValID::t_GlobalID:
3944 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003945 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003946 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003947 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003948 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003949 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003950 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003951 return false;
3952 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003953 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003954 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3955 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003956
Dan Gohman518cda42011-12-17 00:04:22 +00003957 // The lexer has no type info, so builds all half, float, and double FP
3958 // constants as double. Fix this here. Long double does not need this.
3959 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003960 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003961 if (Ty->isHalfTy())
3962 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3963 &Ignored);
3964 else if (Ty->isFloatTy())
3965 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3966 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003967 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003968 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003969
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003970 if (V->getType() != Ty)
3971 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003972 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003973
Chris Lattnerac161bf2009-01-02 07:01:27 +00003974 return false;
3975 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003976 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003977 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003978 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003979 return false;
3980 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003981 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003982 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003983 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003984 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003985 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003986 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003987 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003988 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003989 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003990 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003991 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003992 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003993 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003994 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003995 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003996 return false;
3997 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003998 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003999 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004000
Chris Lattnerac161bf2009-01-02 07:01:27 +00004001 V = ID.ConstantVal;
4002 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004003 case ValID::t_ConstantStruct:
4004 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004005 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004006 if (ST->getNumElements() != ID.UIntVal)
4007 return Error(ID.Loc,
4008 "initializer with struct type has wrong # elements");
4009 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4010 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004011
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004012 // Verify that the elements are compatible with the structtype.
4013 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4014 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4015 return Error(ID.Loc, "element " + Twine(i) +
4016 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004017
Reid Kleckner2ae03e12015-03-04 18:31:10 +00004018 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4019 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004020 } else
4021 return Error(ID.Loc, "constant expression type mismatch");
4022 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004023 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004024 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004025}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004026
Chris Lattner229907c2011-07-18 04:54:35 +00004027bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004028 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004029 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004030 return ParseValID(ID, PFS) ||
4031 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004032}
4033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004034bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004035 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004036 return ParseType(Ty) ||
4037 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038}
4039
Chris Lattner3ed871f2009-10-27 19:13:16 +00004040bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4041 PerFunctionState &PFS) {
4042 Value *V;
4043 Loc = Lex.getLoc();
4044 if (ParseTypeAndValue(V, PFS)) return true;
4045 if (!isa<BasicBlock>(V))
4046 return Error(Loc, "expected a basic block");
4047 BB = cast<BasicBlock>(V);
4048 return false;
4049}
4050
4051
Chris Lattnerac161bf2009-01-02 07:01:27 +00004052/// FunctionHeader
4053/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004054/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004055/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4057 // Parse the linkage.
4058 LocTy LinkageLoc = Lex.getLoc();
4059 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004060
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004061 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004062 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004063 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004064 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004065 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004066 LocTy RetTypeLoc = Lex.getLoc();
4067 if (ParseOptionalLinkage(Linkage) ||
4068 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004069 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004071 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004072 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004073 return true;
4074
4075 // Verify that the linkage is ok.
4076 switch ((GlobalValue::LinkageTypes)Linkage) {
4077 case GlobalValue::ExternalLinkage:
4078 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004079 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 if (isDefine)
4081 return Error(LinkageLoc, "invalid linkage for function definition");
4082 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004083 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004084 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004085 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004086 case GlobalValue::LinkOnceAnyLinkage:
4087 case GlobalValue::LinkOnceODRLinkage:
4088 case GlobalValue::WeakAnyLinkage:
4089 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004090 if (!isDefine)
4091 return Error(LinkageLoc, "invalid linkage for function declaration");
4092 break;
4093 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004094 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004095 return Error(LinkageLoc, "invalid function linkage type");
4096 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004097
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004098 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4099 return Error(LinkageLoc,
4100 "symbol with local linkage must have default visibility");
4101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004102 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004103 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004104
Chris Lattnerac161bf2009-01-02 07:01:27 +00004105 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004106
4107 std::string FunctionName;
4108 if (Lex.getKind() == lltok::GlobalVar) {
4109 FunctionName = Lex.getStrVal();
4110 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4111 unsigned NameID = Lex.getUIntVal();
4112
4113 if (NameID != NumberedVals.size())
4114 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004115 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004116 } else {
4117 return TokError("expected function name");
4118 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004119
Chris Lattner3822f632009-01-02 08:05:26 +00004120 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004121
Chris Lattner3822f632009-01-02 08:05:26 +00004122 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004123 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004124
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004125 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004126 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004127 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004128 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004129 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004130 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004131 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004132 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004133 bool UnnamedAddr;
4134 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004135 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004136 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004137 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004139 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004140 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4141 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004142 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004143 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004144 (EatIfPresent(lltok::kw_section) &&
4145 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004146 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004147 ParseOptionalAlignment(Alignment) ||
4148 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004149 ParseStringConstant(GC)) ||
4150 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004151 ParseGlobalTypeAndValue(Prefix)) ||
4152 (EatIfPresent(lltok::kw_prologue) &&
4153 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00004154 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004155
Michael Gottesman41748d72013-06-27 00:25:01 +00004156 if (FuncAttrs.contains(Attribute::Builtin))
4157 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004158
Chris Lattnerac161bf2009-01-02 07:01:27 +00004159 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004160 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004161 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004162 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004163 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004164
Chris Lattnerac161bf2009-01-02 07:01:27 +00004165 // Okay, if we got here, the function is syntactically valid. Convert types
4166 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004167 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004168 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004169
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004170 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004171 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4172 AttributeSet::ReturnIndex,
4173 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004174
Chris Lattnerac161bf2009-01-02 07:01:27 +00004175 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004176 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004177 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4178 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004179 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4180 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004181 }
4182
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004183 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004184 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4185 AttributeSet::FunctionIndex,
4186 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004187
Bill Wendlinge94d8432012-12-07 23:16:57 +00004188 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004189
Bill Wendling749a43d2012-12-30 13:50:49 +00004190 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004191 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4192
Chris Lattner229907c2011-07-18 04:54:35 +00004193 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004194 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004195 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004196
Craig Topper2617dcc2014-04-15 06:32:26 +00004197 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004198 if (!FunctionName.empty()) {
4199 // If this was a definition of a forward reference, remove the definition
4200 // from the forward reference table and fill in the forward ref.
4201 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4202 ForwardRefVals.find(FunctionName);
4203 if (FRVI != ForwardRefVals.end()) {
4204 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004205 if (!Fn)
4206 return Error(FRVI->second.second, "invalid forward reference to "
4207 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004208 if (Fn->getType() != PFT)
4209 return Error(FRVI->second.second, "invalid forward reference to "
4210 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004211
Chris Lattnerac161bf2009-01-02 07:01:27 +00004212 ForwardRefVals.erase(FRVI);
4213 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004214 // Reject redefinitions.
4215 return Error(NameLoc, "invalid redefinition of function '" +
4216 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004217 } else if (M->getNamedValue(FunctionName)) {
4218 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004219 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004220
Dan Gohman399d6ae2009-08-29 23:37:49 +00004221 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222 // If this is a definition of a forward referenced function, make sure the
4223 // types agree.
4224 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4225 = ForwardRefValIDs.find(NumberedVals.size());
4226 if (I != ForwardRefValIDs.end()) {
4227 Fn = cast<Function>(I->second.first);
4228 if (Fn->getType() != PFT)
4229 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004230 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004231 ForwardRefValIDs.erase(I);
4232 }
4233 }
4234
Craig Topper2617dcc2014-04-15 06:32:26 +00004235 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004236 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4237 else // Move the forward-reference to the correct spot in the module.
4238 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4239
4240 if (FunctionName.empty())
4241 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004242
Chris Lattnerac161bf2009-01-02 07:01:27 +00004243 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4244 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004245 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 Fn->setCallingConv(CC);
4247 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004248 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004249 Fn->setAlignment(Alignment);
4250 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004251 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004252 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004253 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004254 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004255 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004256
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 // Add all of the arguments we parsed to the function.
4258 Function::arg_iterator ArgIt = Fn->arg_begin();
4259 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4260 // If the argument has a name, insert it into the argument symbol table.
4261 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004262
Chris Lattnerac161bf2009-01-02 07:01:27 +00004263 // Set the name, if it conflicted, it will be auto-renamed.
4264 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004265
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004266 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004267 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4268 ArgList[i].Name + "'");
4269 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004270
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004271 if (isDefine)
4272 return false;
4273
Robin Morisset039781e2014-08-29 21:53:01 +00004274 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004275 ValID ID;
4276 if (FunctionName.empty()) {
4277 ID.Kind = ValID::t_GlobalID;
4278 ID.UIntVal = NumberedVals.size() - 1;
4279 } else {
4280 ID.Kind = ValID::t_GlobalName;
4281 ID.StrVal = FunctionName;
4282 }
4283 auto Blocks = ForwardRefBlockAddresses.find(ID);
4284 if (Blocks != ForwardRefBlockAddresses.end())
4285 return Error(Blocks->first.Loc,
4286 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004287 return false;
4288}
4289
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004290bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4291 ValID ID;
4292 if (FunctionNumber == -1) {
4293 ID.Kind = ValID::t_GlobalName;
4294 ID.StrVal = F.getName();
4295 } else {
4296 ID.Kind = ValID::t_GlobalID;
4297 ID.UIntVal = FunctionNumber;
4298 }
4299
4300 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4301 if (Blocks == P.ForwardRefBlockAddresses.end())
4302 return false;
4303
4304 for (const auto &I : Blocks->second) {
4305 const ValID &BBID = I.first;
4306 GlobalValue *GV = I.second;
4307
4308 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4309 "Expected local id or name");
4310 BasicBlock *BB;
4311 if (BBID.Kind == ValID::t_LocalName)
4312 BB = GetBB(BBID.StrVal, BBID.Loc);
4313 else
4314 BB = GetBB(BBID.UIntVal, BBID.Loc);
4315 if (!BB)
4316 return P.Error(BBID.Loc, "referenced value is not a basic block");
4317
4318 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4319 GV->eraseFromParent();
4320 }
4321
4322 P.ForwardRefBlockAddresses.erase(Blocks);
4323 return false;
4324}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004325
4326/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004327/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004329 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004330 return TokError("expected '{' in function body");
4331 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004332
Chris Lattner3432c622009-10-28 03:39:23 +00004333 int FunctionNumber = -1;
4334 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004335
Chris Lattner3432c622009-10-28 03:39:23 +00004336 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004337
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004338 // Resolve block addresses and allow basic blocks to be forward-declared
4339 // within this function.
4340 if (PFS.resolveForwardRefBlockAddresses())
4341 return true;
4342 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4343
Chris Lattnerbbddd962010-01-09 19:20:07 +00004344 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004345 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004346 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004347
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004348 while (Lex.getKind() != lltok::rbrace &&
4349 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004351
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004352 while (Lex.getKind() != lltok::rbrace)
4353 if (ParseUseListOrder(&PFS))
4354 return true;
4355
Chris Lattnerac161bf2009-01-02 07:01:27 +00004356 // Eat the }.
4357 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004358
Chris Lattnerac161bf2009-01-02 07:01:27 +00004359 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004360 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361}
4362
4363/// ParseBasicBlock
4364/// ::= LabelStr? Instruction*
4365bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4366 // If this basic block starts out with a name, remember it.
4367 std::string Name;
4368 LocTy NameLoc = Lex.getLoc();
4369 if (Lex.getKind() == lltok::LabelStr) {
4370 Name = Lex.getStrVal();
4371 Lex.Lex();
4372 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004373
Chris Lattnerac161bf2009-01-02 07:01:27 +00004374 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004375 if (!BB)
4376 return Error(NameLoc,
4377 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004378
Chris Lattnerac161bf2009-01-02 07:01:27 +00004379 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004380
Chris Lattnerac161bf2009-01-02 07:01:27 +00004381 // Parse the instructions in this block until we get a terminator.
4382 Instruction *Inst;
4383 do {
4384 // This instruction may have three possibilities for a name: a) none
4385 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4386 LocTy NameLoc = Lex.getLoc();
4387 int NameID = -1;
4388 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004389
Chris Lattnerac161bf2009-01-02 07:01:27 +00004390 if (Lex.getKind() == lltok::LocalVarID) {
4391 NameID = Lex.getUIntVal();
4392 Lex.Lex();
4393 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4394 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004395 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396 NameStr = Lex.getStrVal();
4397 Lex.Lex();
4398 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4399 return true;
4400 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004401
Chris Lattner77b89dc2009-12-30 05:23:43 +00004402 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004403 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004404 case InstError: return true;
4405 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004406 BB->getInstList().push_back(Inst);
4407
Chris Lattner77b89dc2009-12-30 05:23:43 +00004408 // With a normal result, we check to see if the instruction is followed by
4409 // a comma and metadata.
4410 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004411 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004412 return true;
4413 break;
4414 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004415 BB->getInstList().push_back(Inst);
4416
Chris Lattner77b89dc2009-12-30 05:23:43 +00004417 // If the instruction parser ate an extra comma at the end of it, it
4418 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004419 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004420 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004421 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004422 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004423
Chris Lattnerac161bf2009-01-02 07:01:27 +00004424 // Set the name on the instruction.
4425 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4426 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004427
Chris Lattnerac161bf2009-01-02 07:01:27 +00004428 return false;
4429}
4430
4431//===----------------------------------------------------------------------===//
4432// Instruction Parsing.
4433//===----------------------------------------------------------------------===//
4434
4435/// ParseInstruction - Parse one of the many different instructions.
4436///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004437int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4438 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 lltok::Kind Token = Lex.getKind();
4440 if (Token == lltok::Eof)
4441 return TokError("found end of file when expecting more instructions");
4442 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004443 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004444 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004445
Chris Lattnerac161bf2009-01-02 07:01:27 +00004446 switch (Token) {
4447 default: return Error(Loc, "expected instruction opcode");
4448 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004449 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004450 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4451 case lltok::kw_br: return ParseBr(Inst, PFS);
4452 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004453 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004454 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004455 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004456 // Binary Operators.
4457 case lltok::kw_add:
4458 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004459 case lltok::kw_mul:
4460 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004461 bool NUW = EatIfPresent(lltok::kw_nuw);
4462 bool NSW = EatIfPresent(lltok::kw_nsw);
4463 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004464
Chris Lattnera676c0f2011-02-07 16:40:21 +00004465 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004466
Chris Lattnera676c0f2011-02-07 16:40:21 +00004467 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4468 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4469 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004470 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004471 case lltok::kw_fadd:
4472 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004473 case lltok::kw_fmul:
4474 case lltok::kw_fdiv:
4475 case lltok::kw_frem: {
4476 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4477 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4478 if (Res != 0)
4479 return Res;
4480 if (FMF.any())
4481 Inst->setFastMathFlags(FMF);
4482 return 0;
4483 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004484
Chris Lattner35315d02011-02-06 21:44:57 +00004485 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004486 case lltok::kw_udiv:
4487 case lltok::kw_lshr:
4488 case lltok::kw_ashr: {
4489 bool Exact = EatIfPresent(lltok::kw_exact);
4490
4491 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4492 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4493 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004494 }
4495
Chris Lattnerac161bf2009-01-02 07:01:27 +00004496 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004497 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004498 case lltok::kw_and:
4499 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004500 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004501 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004502 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004503 // Casts.
4504 case lltok::kw_trunc:
4505 case lltok::kw_zext:
4506 case lltok::kw_sext:
4507 case lltok::kw_fptrunc:
4508 case lltok::kw_fpext:
4509 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004510 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004511 case lltok::kw_uitofp:
4512 case lltok::kw_sitofp:
4513 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004514 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004516 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004517 // Other.
4518 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004519 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4521 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4522 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4523 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004524 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004525 // Call.
4526 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4527 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4528 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004529 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004530 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004531 case lltok::kw_load: return ParseLoad(Inst, PFS);
4532 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004533 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4534 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004535 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004536 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4537 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4538 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4539 }
4540}
4541
4542/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4543bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004544 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004546 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004547 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4548 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4549 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4550 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4551 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4552 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4553 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4554 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4555 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4556 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4557 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4558 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4559 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4560 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4561 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4562 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4563 }
4564 } else {
4565 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004566 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004567 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4568 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4569 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4570 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4571 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4572 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4573 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4574 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4575 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4576 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4577 }
4578 }
4579 Lex.Lex();
4580 return false;
4581}
4582
4583//===----------------------------------------------------------------------===//
4584// Terminator Instructions.
4585//===----------------------------------------------------------------------===//
4586
4587/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004588/// ::= 'ret' void (',' !dbg, !1)*
4589/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004590bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004591 PerFunctionState &PFS) {
4592 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004593 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004594 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004595
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004596 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004597
Chris Lattnerfdd87902009-10-05 05:54:46 +00004598 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004599 if (!ResType->isVoidTy())
4600 return Error(TypeLoc, "value doesn't match function result type '" +
4601 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004602
Owen Anderson55f1c092009-08-13 21:58:54 +00004603 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004604 return false;
4605 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004606
Chris Lattnerac161bf2009-01-02 07:01:27 +00004607 Value *RV;
4608 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004610 if (ResType != RV->getType())
4611 return Error(TypeLoc, "value doesn't match function result type '" +
4612 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004613
Owen Anderson55f1c092009-08-13 21:58:54 +00004614 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004615 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004616}
4617
4618
4619/// ParseBr
4620/// ::= 'br' TypeAndValue
4621/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4622bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4623 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004624 Value *Op0;
4625 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004626 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004627
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4629 Inst = BranchInst::Create(BB);
4630 return false;
4631 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004632
Owen Anderson55f1c092009-08-13 21:58:54 +00004633 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004635
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004637 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004638 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004639 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004640 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004641
Chris Lattner3ed871f2009-10-27 19:13:16 +00004642 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 return false;
4644}
4645
4646/// ParseSwitch
4647/// Instruction
4648/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4649/// JumpTable
4650/// ::= (TypeAndValue ',' TypeAndValue)*
4651bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4652 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004653 Value *Cond;
4654 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004655 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4656 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004657 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4659 return true;
4660
Duncan Sands19d0b472010-02-16 11:11:14 +00004661 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004662 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004663
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 // Parse the jump table pairs.
4665 SmallPtrSet<Value*, 32> SeenCases;
4666 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4667 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004668 Value *Constant;
4669 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004670
Chris Lattnerac161bf2009-01-02 07:01:27 +00004671 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4672 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004673 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004675
David Blaikie70573dc2014-11-19 07:49:26 +00004676 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004677 return Error(CondLoc, "duplicate case value in switch");
4678 if (!isa<ConstantInt>(Constant))
4679 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004680
Chris Lattner3ed871f2009-10-27 19:13:16 +00004681 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004682 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004683
Chris Lattnerac161bf2009-01-02 07:01:27 +00004684 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004685
Chris Lattner3ed871f2009-10-27 19:13:16 +00004686 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004687 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4688 SI->addCase(Table[i].first, Table[i].second);
4689 Inst = SI;
4690 return false;
4691}
4692
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004693/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004694/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004695/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4696bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004697 LocTy AddrLoc;
4698 Value *Address;
4699 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004700 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4701 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004702 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004703
Duncan Sands19d0b472010-02-16 11:11:14 +00004704 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004705 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004706
Chris Lattner3ed871f2009-10-27 19:13:16 +00004707 // Parse the destination list.
4708 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004709
Chris Lattner3ed871f2009-10-27 19:13:16 +00004710 if (Lex.getKind() != lltok::rsquare) {
4711 BasicBlock *DestBB;
4712 if (ParseTypeAndBasicBlock(DestBB, PFS))
4713 return true;
4714 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004715
Chris Lattner3ed871f2009-10-27 19:13:16 +00004716 while (EatIfPresent(lltok::comma)) {
4717 if (ParseTypeAndBasicBlock(DestBB, PFS))
4718 return true;
4719 DestList.push_back(DestBB);
4720 }
4721 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004722
Chris Lattner3ed871f2009-10-27 19:13:16 +00004723 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4724 return true;
4725
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004726 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004727 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4728 IBI->addDestination(DestList[i]);
4729 Inst = IBI;
4730 return false;
4731}
4732
4733
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734/// ParseInvoke
4735/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4736/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4737bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4738 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004739 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004740 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004741 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004742 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004743 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004744 LocTy RetTypeLoc;
4745 ValID CalleeID;
4746 SmallVector<ParamInfo, 16> ArgList;
4747
Chris Lattner3ed871f2009-10-27 19:13:16 +00004748 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004749 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004750 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004751 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752 ParseValID(CalleeID) ||
4753 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004754 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4755 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004757 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004758 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004759 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 // If RetType is a non-function pointer type, then this is the short syntax
4763 // for the call, which means that RetType is just the return type. Infer the
4764 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004765 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4766 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004768 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004769 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4770 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004771
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772 if (!FunctionType::isValidReturnType(RetType))
4773 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004774
Owen Anderson4056ca92009-07-29 22:17:13 +00004775 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004777
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 // Look up the callee.
4779 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004780 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4781 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004782
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004783 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004784 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004785 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004786 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4787 AttributeSet::ReturnIndex,
4788 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004789
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004791
Chris Lattnerac161bf2009-01-02 07:01:27 +00004792 // Loop through FunctionType's arguments and ensure they are specified
4793 // correctly. Also, gather any parameter attributes.
4794 FunctionType::param_iterator I = Ty->param_begin();
4795 FunctionType::param_iterator E = Ty->param_end();
4796 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004797 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004798 if (I != E) {
4799 ExpectedTy = *I++;
4800 } else if (!Ty->isVarArg()) {
4801 return Error(ArgList[i].Loc, "too many arguments specified");
4802 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004803
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4805 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004806 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004808 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4809 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004810 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4811 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004813
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 if (I != E)
4815 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004816
David Majnemer8d22abd2015-02-23 00:01:32 +00004817 if (FnAttrs.hasAttributes()) {
4818 if (FnAttrs.hasAlignmentAttr())
4819 return Error(CallLoc, "invoke instructions may not have an alignment");
4820
Bill Wendlingf5075a42013-01-27 02:24:02 +00004821 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4822 AttributeSet::FunctionIndex,
4823 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004824 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004825
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004826 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004827 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004828
Jay Foad5bd375a2011-07-15 08:37:34 +00004829 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 II->setCallingConv(CC);
4831 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004832 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833 Inst = II;
4834 return false;
4835}
4836
Bill Wendlingf891bf82011-07-31 06:30:59 +00004837/// ParseResume
4838/// ::= 'resume' TypeAndValue
4839bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4840 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004841 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4842 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004843
Bill Wendlingf891bf82011-07-31 06:30:59 +00004844 ResumeInst *RI = ResumeInst::Create(Exn);
4845 Inst = RI;
4846 return false;
4847}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848
4849//===----------------------------------------------------------------------===//
4850// Binary Operators.
4851//===----------------------------------------------------------------------===//
4852
4853/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004854/// ::= ArithmeticOps TypeAndValue ',' Value
4855///
4856/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4857/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004858bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004859 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 LocTy Loc; Value *LHS, *RHS;
4861 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4862 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4863 ParseValue(LHS->getType(), RHS, PFS))
4864 return true;
4865
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004866 bool Valid;
4867 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004868 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004869 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004870 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4871 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004872 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004873 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4874 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004875 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004876
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004877 if (!Valid)
4878 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004879
Chris Lattnerac161bf2009-01-02 07:01:27 +00004880 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4881 return false;
4882}
4883
4884/// ParseLogical
4885/// ::= ArithmeticOps TypeAndValue ',' Value {
4886bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4887 unsigned Opc) {
4888 LocTy Loc; Value *LHS, *RHS;
4889 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4890 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4891 ParseValue(LHS->getType(), RHS, PFS))
4892 return true;
4893
Duncan Sands9dff9be2010-02-15 16:12:20 +00004894 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004895 return Error(Loc,"instruction requires integer or integer vector operands");
4896
4897 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4898 return false;
4899}
4900
4901
4902/// ParseCompare
4903/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4904/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4906 unsigned Opc) {
4907 // Parse the integer/fp comparison predicate.
4908 LocTy Loc;
4909 unsigned Pred;
4910 Value *LHS, *RHS;
4911 if (ParseCmpPredicate(Pred, Opc) ||
4912 ParseTypeAndValue(LHS, Loc, PFS) ||
4913 ParseToken(lltok::comma, "expected ',' after compare value") ||
4914 ParseValue(LHS->getType(), RHS, PFS))
4915 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004916
Chris Lattnerac161bf2009-01-02 07:01:27 +00004917 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004918 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004920 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004921 } else {
4922 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004923 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004924 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004926 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004927 }
4928 return false;
4929}
4930
4931//===----------------------------------------------------------------------===//
4932// Other Instructions.
4933//===----------------------------------------------------------------------===//
4934
4935
4936/// ParseCast
4937/// ::= CastOpc TypeAndValue 'to' Type
4938bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4939 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004940 LocTy Loc;
4941 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004942 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 if (ParseTypeAndValue(Op, Loc, PFS) ||
4944 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4945 ParseType(DestTy))
4946 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004947
Chris Lattner89d856e2009-03-01 00:53:13 +00004948 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4949 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004951 getTypeString(Op->getType()) + "' to '" +
4952 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004953 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004954 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4955 return false;
4956}
4957
4958/// ParseSelect
4959/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4960bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4961 LocTy Loc;
4962 Value *Op0, *Op1, *Op2;
4963 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4964 ParseToken(lltok::comma, "expected ',' after select condition") ||
4965 ParseTypeAndValue(Op1, PFS) ||
4966 ParseToken(lltok::comma, "expected ',' after select value") ||
4967 ParseTypeAndValue(Op2, PFS))
4968 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004969
Chris Lattnerac161bf2009-01-02 07:01:27 +00004970 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4971 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004972
Chris Lattnerac161bf2009-01-02 07:01:27 +00004973 Inst = SelectInst::Create(Op0, Op1, Op2);
4974 return false;
4975}
4976
Chris Lattnerb55ab542009-01-05 08:18:44 +00004977/// ParseVA_Arg
4978/// ::= 'va_arg' TypeAndValue ',' Type
4979bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004980 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004981 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004982 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004983 if (ParseTypeAndValue(Op, PFS) ||
4984 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004985 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004986 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004987
Chris Lattnerb55ab542009-01-05 08:18:44 +00004988 if (!EltTy->isFirstClassType())
4989 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990
4991 Inst = new VAArgInst(Op, EltTy);
4992 return false;
4993}
4994
4995/// ParseExtractElement
4996/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4997bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4998 LocTy Loc;
4999 Value *Op0, *Op1;
5000 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5001 ParseToken(lltok::comma, "expected ',' after extract value") ||
5002 ParseTypeAndValue(Op1, PFS))
5003 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005004
Chris Lattnerac161bf2009-01-02 07:01:27 +00005005 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5006 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005007
Eric Christopherc9742252009-07-25 02:28:41 +00005008 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005009 return false;
5010}
5011
5012/// ParseInsertElement
5013/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5014bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5015 LocTy Loc;
5016 Value *Op0, *Op1, *Op2;
5017 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5018 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5019 ParseTypeAndValue(Op1, PFS) ||
5020 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5021 ParseTypeAndValue(Op2, PFS))
5022 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005023
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005025 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005026
Chris Lattnerac161bf2009-01-02 07:01:27 +00005027 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5028 return false;
5029}
5030
5031/// ParseShuffleVector
5032/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5033bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5034 LocTy Loc;
5035 Value *Op0, *Op1, *Op2;
5036 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5037 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5038 ParseTypeAndValue(Op1, PFS) ||
5039 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5040 ParseTypeAndValue(Op2, PFS))
5041 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005042
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005044 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005045
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5047 return false;
5048}
5049
5050/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005051/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005052int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005053 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005054 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005055
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005056 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5058 ParseValue(Ty, Op0, PFS) ||
5059 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005060 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5062 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005063
Chris Lattnerf4f03422009-12-30 05:27:33 +00005064 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005065 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5066 while (1) {
5067 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005068
Chris Lattner3822f632009-01-02 08:05:26 +00005069 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005070 break;
5071
Chris Lattnerf4f03422009-12-30 05:27:33 +00005072 if (Lex.getKind() == lltok::MetadataVar) {
5073 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005074 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005075 }
Devang Patel8f842d32009-10-16 18:45:49 +00005076
Chris Lattner3822f632009-01-02 08:05:26 +00005077 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005078 ParseValue(Ty, Op0, PFS) ||
5079 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005080 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005081 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5082 return true;
5083 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005084
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085 if (!Ty->isFirstClassType())
5086 return Error(TypeLoc, "phi node must have first class type");
5087
Jay Foad52131342011-03-30 11:28:46 +00005088 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005089 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5090 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5091 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005092 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005093}
5094
Bill Wendlingfae14752011-08-12 20:24:12 +00005095/// ParseLandingPad
5096/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5097/// Clause
5098/// ::= 'catch' TypeAndValue
5099/// ::= 'filter'
5100/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5101bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005102 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005103 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005104
5105 if (ParseType(Ty, TyLoc) ||
5106 ParseToken(lltok::kw_personality, "expected 'personality'") ||
5107 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5108 return true;
5109
Owen Andersonf8f259d2015-03-09 07:13:42 +00005110 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005111 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5112
5113 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5114 LandingPadInst::ClauseType CT;
5115 if (EatIfPresent(lltok::kw_catch))
5116 CT = LandingPadInst::Catch;
5117 else if (EatIfPresent(lltok::kw_filter))
5118 CT = LandingPadInst::Filter;
5119 else
5120 return TokError("expected 'catch' or 'filter' clause type");
5121
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005122 Value *V;
5123 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005124 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005125 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005126
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005127 // A 'catch' type expects a non-array constant. A filter clause expects an
5128 // array constant.
5129 if (CT == LandingPadInst::Catch) {
5130 if (isa<ArrayType>(V->getType()))
5131 Error(VLoc, "'catch' clause has an invalid type");
5132 } else {
5133 if (!isa<ArrayType>(V->getType()))
5134 Error(VLoc, "'filter' clause has an invalid type");
5135 }
5136
Owen Andersonf8f259d2015-03-09 07:13:42 +00005137 Constant *CV = dyn_cast<Constant>(V);
5138 if (!CV)
5139 return Error(VLoc, "clause argument must be a constant");
5140 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005141 }
5142
Owen Andersonf8f259d2015-03-09 07:13:42 +00005143 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005144 return false;
5145}
5146
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005148/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5149/// ParameterList OptionalAttrs
5150/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5151/// ParameterList OptionalAttrs
5152/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005153/// ParameterList OptionalAttrs
5154bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005155 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005156 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005157 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005158 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005159 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005160 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005161 LocTy RetTypeLoc;
5162 ValID CalleeID;
5163 SmallVector<ParamInfo, 16> ArgList;
5164 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005165
Reid Kleckner5772b772014-04-24 20:14:34 +00005166 if ((TCK != CallInst::TCK_None &&
5167 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005169 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005170 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005171 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005172 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5173 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005174 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005175 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005177
Chris Lattnerac161bf2009-01-02 07:01:27 +00005178 // If RetType is a non-function pointer type, then this is the short syntax
5179 // for the call, which means that RetType is just the return type. Infer the
5180 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005181 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5182 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005183 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005184 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005185 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5186 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005187
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 if (!FunctionType::isValidReturnType(RetType))
5189 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005190
Owen Anderson4056ca92009-07-29 22:17:13 +00005191 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005193
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 // Look up the callee.
5195 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005196 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5197 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005198
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005199 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005200 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005201 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005202 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5203 AttributeSet::ReturnIndex,
5204 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005205
Chris Lattnerac161bf2009-01-02 07:01:27 +00005206 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005207
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 // Loop through FunctionType's arguments and ensure they are specified
5209 // correctly. Also, gather any parameter attributes.
5210 FunctionType::param_iterator I = Ty->param_begin();
5211 FunctionType::param_iterator E = Ty->param_end();
5212 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005213 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005214 if (I != E) {
5215 ExpectedTy = *I++;
5216 } else if (!Ty->isVarArg()) {
5217 return Error(ArgList[i].Loc, "too many arguments specified");
5218 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005219
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5221 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005222 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005223 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005224 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5225 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005226 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5227 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005228 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005229
Chris Lattnerac161bf2009-01-02 07:01:27 +00005230 if (I != E)
5231 return Error(CallLoc, "not enough parameters specified for call");
5232
David Majnemer8d22abd2015-02-23 00:01:32 +00005233 if (FnAttrs.hasAttributes()) {
5234 if (FnAttrs.hasAlignmentAttr())
5235 return Error(CallLoc, "call instructions may not have an alignment");
5236
Bill Wendlingf5075a42013-01-27 02:24:02 +00005237 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5238 AttributeSet::FunctionIndex,
5239 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005240 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005242 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005243 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005244
David Blaikie348de692015-04-23 21:36:23 +00005245 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005246 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247 CI->setCallingConv(CC);
5248 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005249 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005250 Inst = CI;
5251 return false;
5252}
5253
5254//===----------------------------------------------------------------------===//
5255// Memory Instructions.
5256//===----------------------------------------------------------------------===//
5257
5258/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005259/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005260int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005261 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005262 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005263 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005264 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005265
5266 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5267
David Majnemera3b0eb22015-02-16 08:38:03 +00005268 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269
David Majnemera3b0eb22015-02-16 08:38:03 +00005270 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5271 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005272
Chris Lattnerb2f39502009-12-30 05:44:30 +00005273 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005274 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005275 if (Lex.getKind() == lltok::kw_align) {
5276 if (ParseOptionalAlignment(Alignment)) return true;
5277 } else if (Lex.getKind() == lltok::MetadataVar) {
5278 AteExtraComma = true;
5279 } else {
5280 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5281 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5282 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283 }
5284 }
5285
Dan Gohman2140a742010-05-28 01:14:11 +00005286 if (Size && !Size->getType()->isIntegerTy())
5287 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005288
Reid Kleckner436c42e2014-01-17 23:58:17 +00005289 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5290 AI->setUsedWithInAlloca(IsInAlloca);
5291 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005292 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005293}
5294
5295/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005296/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005297/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005298/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005299int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005300 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005301 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005302 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005303 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005304 AtomicOrdering Ordering = NotAtomic;
5305 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005306
5307 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005308 isAtomic = true;
5309 Lex.Lex();
5310 }
5311
Chris Lattnerbc639292011-11-27 06:56:53 +00005312 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005313 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005314 isVolatile = true;
5315 Lex.Lex();
5316 }
5317
David Blaikie15d9a4c2015-04-06 20:59:48 +00005318 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005319 LocTy ExplicitTypeLoc = Lex.getLoc();
5320 if (ParseType(Ty) ||
5321 ParseToken(lltok::comma, "expected comma after load's type") ||
5322 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005323 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005324 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5325 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005326
David Blaikie15d9a4c2015-04-06 20:59:48 +00005327 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005328 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005329 if (isAtomic && !Alignment)
5330 return Error(Loc, "atomic load must have explicit non-zero alignment");
5331 if (Ordering == Release || Ordering == AcquireRelease)
5332 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005333
David Blaikiea79ac142015-02-27 21:17:42 +00005334 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5335 return Error(ExplicitTypeLoc,
5336 "explicit pointee type doesn't match operand's pointee type");
5337
David Blaikie15d9a4c2015-04-06 20:59:48 +00005338 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005339 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340}
5341
5342/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005343
5344/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5345/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005346/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005347int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005349 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005350 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005351 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005352 AtomicOrdering Ordering = NotAtomic;
5353 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005354
5355 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005356 isAtomic = true;
5357 Lex.Lex();
5358 }
5359
Chris Lattnerbc639292011-11-27 06:56:53 +00005360 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005361 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005362 isVolatile = true;
5363 Lex.Lex();
5364 }
5365
Chris Lattnerac161bf2009-01-02 07:01:27 +00005366 if (ParseTypeAndValue(Val, Loc, PFS) ||
5367 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005368 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005369 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005370 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005371 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005372
Duncan Sands19d0b472010-02-16 11:11:14 +00005373 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005374 return Error(PtrLoc, "store operand must be a pointer");
5375 if (!Val->getType()->isFirstClassType())
5376 return Error(Loc, "store operand must be a first class value");
5377 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5378 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005379 if (isAtomic && !Alignment)
5380 return Error(Loc, "atomic store must have explicit non-zero alignment");
5381 if (Ordering == Acquire || Ordering == AcquireRelease)
5382 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005383
Eli Friedman59b66882011-08-09 23:02:53 +00005384 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005385 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005386}
5387
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005388/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005389/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5390/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005391int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005392 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5393 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005394 AtomicOrdering SuccessOrdering = NotAtomic;
5395 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005396 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005397 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005398 bool isWeak = false;
5399
5400 if (EatIfPresent(lltok::kw_weak))
5401 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005402
5403 if (EatIfPresent(lltok::kw_volatile))
5404 isVolatile = true;
5405
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005406 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5407 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5408 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5409 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5410 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005411 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5412 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005413 return true;
5414
Tim Northovere94a5182014-03-11 10:48:52 +00005415 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005416 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005417 if (SuccessOrdering < FailureOrdering)
5418 return TokError("cmpxchg must be at least as ordered on success as failure");
5419 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5420 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005421 if (!Ptr->getType()->isPointerTy())
5422 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5423 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5424 return Error(CmpLoc, "compare value and pointer type do not match");
5425 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5426 return Error(NewLoc, "new value and pointer type do not match");
5427 if (!New->getType()->isIntegerTy())
5428 return Error(NewLoc, "cmpxchg operand must be an integer");
5429 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5430 if (Size < 8 || (Size & (Size - 1)))
5431 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5432 " integer");
5433
Tim Northover420a2162014-06-13 14:24:07 +00005434 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5435 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005436 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005437 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005438 Inst = CXI;
5439 return AteExtraComma ? InstExtraComma : InstNormal;
5440}
5441
5442/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005443/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5444/// 'singlethread'? AtomicOrdering
5445int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005446 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5447 bool AteExtraComma = false;
5448 AtomicOrdering Ordering = NotAtomic;
5449 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005450 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005451 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005452
5453 if (EatIfPresent(lltok::kw_volatile))
5454 isVolatile = true;
5455
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005456 switch (Lex.getKind()) {
5457 default: return TokError("expected binary operation in atomicrmw");
5458 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5459 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5460 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5461 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5462 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5463 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5464 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5465 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5466 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5467 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5468 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5469 }
5470 Lex.Lex(); // Eat the operation.
5471
5472 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5473 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5474 ParseTypeAndValue(Val, ValLoc, PFS) ||
5475 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5476 return true;
5477
5478 if (Ordering == Unordered)
5479 return TokError("atomicrmw cannot be unordered");
5480 if (!Ptr->getType()->isPointerTy())
5481 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5482 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5483 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5484 if (!Val->getType()->isIntegerTy())
5485 return Error(ValLoc, "atomicrmw operand must be an integer");
5486 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5487 if (Size < 8 || (Size & (Size - 1)))
5488 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5489 " integer");
5490
5491 AtomicRMWInst *RMWI =
5492 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5493 RMWI->setVolatile(isVolatile);
5494 Inst = RMWI;
5495 return AteExtraComma ? InstExtraComma : InstNormal;
5496}
5497
Eli Friedmanfee02c62011-07-25 23:16:38 +00005498/// ParseFence
5499/// ::= 'fence' 'singlethread'? AtomicOrdering
5500int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5501 AtomicOrdering Ordering = NotAtomic;
5502 SynchronizationScope Scope = CrossThread;
5503 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5504 return true;
5505
5506 if (Ordering == Unordered)
5507 return TokError("fence cannot be unordered");
5508 if (Ordering == Monotonic)
5509 return TokError("fence cannot be monotonic");
5510
5511 Inst = new FenceInst(Context, Ordering, Scope);
5512 return InstNormal;
5513}
5514
Chris Lattnerac161bf2009-01-02 07:01:27 +00005515/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005516/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005517int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005518 Value *Ptr = nullptr;
5519 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005520 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005521
Dan Gohman16cbbe42009-07-29 15:58:36 +00005522 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005523
David Blaikie79e6c742015-02-27 19:29:02 +00005524 Type *Ty = nullptr;
5525 LocTy ExplicitTypeLoc = Lex.getLoc();
5526 if (ParseType(Ty) ||
5527 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5528 ParseTypeAndValue(Ptr, Loc, PFS))
5529 return true;
5530
Eli Benderskyd9806682013-04-22 17:03:42 +00005531 Type *BaseType = Ptr->getType();
5532 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5533 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005534 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
David Blaikie8d757942015-03-09 23:08:44 +00005536 if (Ty != BasePointerType->getElementType())
5537 return Error(ExplicitTypeLoc,
5538 "explicit pointee type doesn't match operand's pointee type");
5539
Chris Lattnerac161bf2009-01-02 07:01:27 +00005540 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005541 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005542 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005543 if (Lex.getKind() == lltok::MetadataVar) {
5544 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005545 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005546 }
Chris Lattner3822f632009-01-02 08:05:26 +00005547 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005548 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00005550 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5551 return Error(EltLoc, "getelementptr index type missmatch");
5552 if (Val->getType()->isVectorTy()) {
5553 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5554 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5555 if (ValNumEl != PtrNumEl)
5556 return Error(EltLoc,
5557 "getelementptr vector index has a wrong number of elements");
5558 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005559 Indices.push_back(Val);
5560 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005561
Owen Andersone90f9922015-03-10 06:34:57 +00005562 SmallPtrSet<const Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005563 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005564 return Error(Loc, "base element of getelementptr must be sized");
5565
David Blaikied33bad32015-04-17 22:32:13 +00005566 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005567 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005568 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005569 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005570 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005571 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005572}
5573
5574/// ParseExtractValue
5575/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005576int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005577 Value *Val; LocTy Loc;
5578 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005579 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005580 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005581 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 return true;
5583
Chris Lattner392be582010-02-12 20:49:41 +00005584 if (!Val->getType()->isAggregateType())
5585 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005586
Jay Foad57aa6362011-07-13 10:26:04 +00005587 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005588 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005589 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005590 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005591}
5592
5593/// ParseInsertValue
5594/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005595int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005596 Value *Val0, *Val1; LocTy Loc0, Loc1;
5597 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005598 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005599 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5600 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5601 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005602 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005603 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005604
Chris Lattner392be582010-02-12 20:49:41 +00005605 if (!Val0->getType()->isAggregateType())
5606 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005607
David Majnemer30074532015-02-11 07:43:58 +00005608 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5609 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005610 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005611 if (IndexedType != Val1->getType())
5612 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5613 getTypeString(Val1->getType()) + "' instead of '" +
5614 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005615 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005616 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005617}
Nick Lewycky49f89192009-04-04 07:22:01 +00005618
5619//===----------------------------------------------------------------------===//
5620// Embedded metadata.
5621//===----------------------------------------------------------------------===//
5622
5623/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005624/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005625/// Element
5626/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005627bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005628 if (ParseToken(lltok::lbrace, "expected '{' here"))
5629 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005630
Dan Gohman1e0213a2010-07-13 19:33:27 +00005631 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005632 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005633 return false;
5634
Nick Lewycky49f89192009-04-04 07:22:01 +00005635 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005636 // Null is a special case since it is typeless.
5637 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005638 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005639 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005640 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005641
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005642 Metadata *MD;
5643 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005644 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005645 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005646 } while (EatIfPresent(lltok::comma));
5647
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005648 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005649}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005650
5651//===----------------------------------------------------------------------===//
5652// Use-list order directives.
5653//===----------------------------------------------------------------------===//
5654bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5655 SMLoc Loc) {
5656 if (V->use_empty())
5657 return Error(Loc, "value has no uses");
5658
5659 unsigned NumUses = 0;
5660 SmallDenseMap<const Use *, unsigned, 16> Order;
5661 for (const Use &U : V->uses()) {
5662 if (++NumUses > Indexes.size())
5663 break;
5664 Order[&U] = Indexes[NumUses - 1];
5665 }
5666 if (NumUses < 2)
5667 return Error(Loc, "value only has one use");
5668 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5669 return Error(Loc, "wrong number of indexes, expected " +
5670 Twine(std::distance(V->use_begin(), V->use_end())));
5671
5672 V->sortUseList([&](const Use &L, const Use &R) {
5673 return Order.lookup(&L) < Order.lookup(&R);
5674 });
5675 return false;
5676}
5677
5678/// ParseUseListOrderIndexes
5679/// ::= '{' uint32 (',' uint32)+ '}'
5680bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5681 SMLoc Loc = Lex.getLoc();
5682 if (ParseToken(lltok::lbrace, "expected '{' here"))
5683 return true;
5684 if (Lex.getKind() == lltok::rbrace)
5685 return Lex.Error("expected non-empty list of uselistorder indexes");
5686
5687 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5688 // indexes should be distinct numbers in the range [0, size-1], and should
5689 // not be in order.
5690 unsigned Offset = 0;
5691 unsigned Max = 0;
5692 bool IsOrdered = true;
5693 assert(Indexes.empty() && "Expected empty order vector");
5694 do {
5695 unsigned Index;
5696 if (ParseUInt32(Index))
5697 return true;
5698
5699 // Update consistency checks.
5700 Offset += Index - Indexes.size();
5701 Max = std::max(Max, Index);
5702 IsOrdered &= Index == Indexes.size();
5703
5704 Indexes.push_back(Index);
5705 } while (EatIfPresent(lltok::comma));
5706
5707 if (ParseToken(lltok::rbrace, "expected '}' here"))
5708 return true;
5709
5710 if (Indexes.size() < 2)
5711 return Error(Loc, "expected >= 2 uselistorder indexes");
5712 if (Offset != 0 || Max >= Indexes.size())
5713 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5714 if (IsOrdered)
5715 return Error(Loc, "expected uselistorder indexes to change the order");
5716
5717 return false;
5718}
5719
5720/// ParseUseListOrder
5721/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5722bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5723 SMLoc Loc = Lex.getLoc();
5724 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5725 return true;
5726
5727 Value *V;
5728 SmallVector<unsigned, 16> Indexes;
5729 if (ParseTypeAndValue(V, PFS) ||
5730 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5731 ParseUseListOrderIndexes(Indexes))
5732 return true;
5733
5734 return sortUseListOrder(V, Indexes, Loc);
5735}
5736
5737/// ParseUseListOrderBB
5738/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5739bool LLParser::ParseUseListOrderBB() {
5740 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5741 SMLoc Loc = Lex.getLoc();
5742 Lex.Lex();
5743
5744 ValID Fn, Label;
5745 SmallVector<unsigned, 16> Indexes;
5746 if (ParseValID(Fn) ||
5747 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5748 ParseValID(Label) ||
5749 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5750 ParseUseListOrderIndexes(Indexes))
5751 return true;
5752
5753 // Check the function.
5754 GlobalValue *GV;
5755 if (Fn.Kind == ValID::t_GlobalName)
5756 GV = M->getNamedValue(Fn.StrVal);
5757 else if (Fn.Kind == ValID::t_GlobalID)
5758 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5759 else
5760 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5761 if (!GV)
5762 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5763 auto *F = dyn_cast<Function>(GV);
5764 if (!F)
5765 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5766 if (F->isDeclaration())
5767 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5768
5769 // Check the basic block.
5770 if (Label.Kind == ValID::t_LocalID)
5771 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5772 if (Label.Kind != ValID::t_LocalName)
5773 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5774 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5775 if (!V)
5776 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5777 if (!isa<BasicBlock>(V))
5778 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5779
5780 return sortUseListOrder(V, Indexes, Loc);
5781}