blob: 64ed2a2b7e3e23b4573a90e7e88eab0562bedd4d [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000019#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000020#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/InlineAsm.h"
23#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000024#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
27#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000028#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000030#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000031#include "llvm/Support/raw_ostream.h"
32using namespace llvm;
33
Chris Lattner229907c2011-07-18 04:54:35 +000034static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000035 std::string Result;
36 raw_string_ostream Tmp(Result);
37 Tmp << *T;
38 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000039}
40
Chris Lattner3822f632009-01-02 08:05:26 +000041/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000042bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000043 // Prime the lexer.
44 Lex.Lex();
45
Chris Lattnerad6f3352009-01-04 20:44:11 +000046 return ParseTopLevelEntities() ||
47 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000048}
49
50/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51/// module.
52bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000053 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55
Bill Wendlingb32b0412013-02-08 06:32:06 +000056 // Handle any function attribute group forward references.
57 for (std::map<Value*, std::vector<unsigned> >::iterator
58 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
59 I != E; ++I) {
60 Value *V = I->first;
61 std::vector<unsigned> &Vec = I->second;
62 AttrBuilder B;
63
64 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65 VI != VE; ++VI)
66 B.merge(NumberedAttrBuilders[*VI]);
67
68 if (Function *Fn = dyn_cast<Function>(V)) {
69 AttributeSet AS = Fn->getAttributes();
70 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72 AS.getFnAttributes());
73
74 FnAttrs.merge(B);
75
76 // If the alignment was parsed as an attribute, move to the alignment
77 // field.
78 if (FnAttrs.hasAlignmentAttr()) {
79 Fn->setAlignment(FnAttrs.getAlignment());
80 FnAttrs.removeAttribute(Attribute::Alignment);
81 }
82
83 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84 AttributeSet::get(Context,
85 AttributeSet::FunctionIndex,
86 FnAttrs));
87 Fn->setAttributes(AS);
88 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89 AttributeSet AS = CI->getAttributes();
90 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000093 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000094 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95 AttributeSet::get(Context,
96 AttributeSet::FunctionIndex,
97 FnAttrs));
98 CI->setAttributes(AS);
99 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100 AttributeSet AS = II->getAttributes();
101 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000104 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000105 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106 AttributeSet::get(Context,
107 AttributeSet::FunctionIndex,
108 FnAttrs));
109 II->setAttributes(AS);
110 } else {
111 llvm_unreachable("invalid object with forward attribute group reference");
112 }
113 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000114
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000115 // If there are entries in ForwardRefBlockAddresses at this point, the
116 // function was never defined.
117 if (!ForwardRefBlockAddresses.empty())
118 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000120
David Majnemer19b51052015-02-11 07:43:56 +0000121 for (const auto &NT : NumberedTypes)
122 if (NT.second.second.isValid())
123 return Error(NT.second.second,
124 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000125
126 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128 if (I->second.second.isValid())
129 return Error(I->second.second,
130 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000131
David Majnemerdad0a642014-06-27 18:19:56 +0000132 if (!ForwardRefComdats.empty())
133 return Error(ForwardRefComdats.begin()->second,
134 "use of undefined comdat '$" +
135 ForwardRefComdats.begin()->first + "'");
136
Chris Lattnerac161bf2009-01-02 07:01:27 +0000137 if (!ForwardRefVals.empty())
138 return Error(ForwardRefVals.begin()->second.second,
139 "use of undefined value '@" + ForwardRefVals.begin()->first +
140 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000141
Chris Lattnerac161bf2009-01-02 07:01:27 +0000142 if (!ForwardRefValIDs.empty())
143 return Error(ForwardRefValIDs.begin()->second.second,
144 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000145 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000146
Devang Pateld2541152009-07-08 19:23:54 +0000147 if (!ForwardRefMDNodes.empty())
148 return Error(ForwardRefMDNodes.begin()->second.second,
149 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000150 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000151
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000152 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000153 for (auto &N : NumberedMetadata) {
154 if (N.second && !N.second->isResolved())
155 N.second->resolveCycles();
156 }
Devang Pateld2541152009-07-08 19:23:54 +0000157
Chris Lattnerac161bf2009-01-02 07:01:27 +0000158 // Look for intrinsic functions and CallInst that need to be upgraded
159 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000161
Manman Ren8b4306c2013-12-02 21:29:56 +0000162 UpgradeDebugInfo(*M);
163
Chris Lattnerac161bf2009-01-02 07:01:27 +0000164 return false;
165}
166
167//===----------------------------------------------------------------------===//
168// Top-Level Entities
169//===----------------------------------------------------------------------===//
170
171bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000172 while (1) {
173 switch (Lex.getKind()) {
174 default: return TokError("expected top-level entity");
175 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000176 case lltok::kw_declare: if (ParseDeclare()) return true; break;
177 case lltok::kw_define: if (ParseDefine()) return true; break;
178 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
179 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000180 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000181 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000182 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000183 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000185 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000186 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000187 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000188
189 // The Global variable production with no name can have many different
190 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000191 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000193 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000194 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000195 case lltok::kw_internal: // OptionalLinkage
196 case lltok::kw_weak: // OptionalLinkage
197 case lltok::kw_weak_odr: // OptionalLinkage
198 case lltok::kw_linkonce: // OptionalLinkage
199 case lltok::kw_linkonce_odr: // OptionalLinkage
200 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000201 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000202 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000203 case lltok::kw_external: // OptionalLinkage
204 case lltok::kw_default: // OptionalVisibility
205 case lltok::kw_hidden: // OptionalVisibility
206 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000207 case lltok::kw_dllimport: // OptionalDLLStorageClass
208 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000209 case lltok::kw_thread_local: // OptionalThreadLocal
210 case lltok::kw_addrspace: // OptionalAddrSpace
211 case lltok::kw_constant: // GlobalType
212 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000213 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000214 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000215 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000216 bool HasLinkage;
217 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000218 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000219 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000220 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000221 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000222 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000223 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000224 return true;
225 break;
226 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000227
228 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000229 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230 case lltok::kw_uselistorder_bb:
231 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000232 }
233 }
234}
235
236
237/// toplevelentity
238/// ::= 'module' 'asm' STRINGCONSTANT
239bool LLParser::ParseModuleAsm() {
240 assert(Lex.getKind() == lltok::kw_module);
241 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000242
243 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000244 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000246
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000247 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000248 return false;
249}
250
251/// toplevelentity
252/// ::= 'target' 'triple' '=' STRINGCONSTANT
253/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
254bool LLParser::ParseTargetDefinition() {
255 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000256 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000257 switch (Lex.Lex()) {
258 default: return TokError("unknown target property");
259 case lltok::kw_triple:
260 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000261 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000263 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000264 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 return false;
266 case lltok::kw_datalayout:
267 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000268 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000270 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000271 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000272 return false;
273 }
274}
275
Bill Wendling706d3d62012-11-28 08:41:48 +0000276/// toplevelentity
277/// ::= 'deplibs' '=' '[' ']'
278/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279/// FIXME: Remove in 4.0. Currently parse, but ignore.
280bool LLParser::ParseDepLibs() {
281 assert(Lex.getKind() == lltok::kw_deplibs);
282 Lex.Lex();
283 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285 return true;
286
287 if (EatIfPresent(lltok::rsquare))
288 return false;
289
290 do {
291 std::string Str;
292 if (ParseStringConstant(Str)) return true;
293 } while (EatIfPresent(lltok::comma));
294
295 return ParseToken(lltok::rsquare, "expected ']' at end of list");
296}
297
Dan Gohman466876b2009-08-12 23:32:33 +0000298/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000299/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000300bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000301 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000302 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000303 Lex.Lex(); // eat LocalVarID;
304
305 if (ParseToken(lltok::equal, "expected '=' after name") ||
306 ParseToken(lltok::kw_type, "expected 'type' after '='"))
307 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000308
Craig Topper2617dcc2014-04-15 06:32:26 +0000309 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000310 if (ParseStructDefinition(TypeLoc, "",
311 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000313 if (!isa<StructType>(Result)) {
314 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315 if (Entry.first)
316 return Error(TypeLoc, "non-struct types may not be recursive");
317 Entry.first = Result;
318 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000320
Chris Lattnerac161bf2009-01-02 07:01:27 +0000321 return false;
322}
323
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000324
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325/// toplevelentity
326/// ::= LocalVar '=' 'type' type
327bool LLParser::ParseNamedType() {
328 std::string Name = Lex.getStrVal();
329 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000330 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000331
Chris Lattner3822f632009-01-02 08:05:26 +0000332 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000334 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000335
Craig Topper2617dcc2014-04-15 06:32:26 +0000336 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000337 if (ParseStructDefinition(NameLoc, Name,
338 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000339
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000340 if (!isa<StructType>(Result)) {
341 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342 if (Entry.first)
343 return Error(NameLoc, "non-struct types may not be recursive");
344 Entry.first = Result;
345 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000346 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000348 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000349}
350
351
352/// toplevelentity
353/// ::= 'declare' FunctionHeader
354bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
356 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000357
Chris Lattnerac161bf2009-01-02 07:01:27 +0000358 Function *F;
359 return ParseFunctionHeader(F, false);
360}
361
362/// toplevelentity
363/// ::= 'define' FunctionHeader '{' ...
364bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
366 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000367
Chris Lattnerac161bf2009-01-02 07:01:27 +0000368 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371}
372
Chris Lattner3822f632009-01-02 08:05:26 +0000373/// ParseGlobalType
374/// ::= 'constant'
375/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
378 IsConstant = true;
379 else if (Lex.getKind() == lltok::kw_global)
380 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000381 else {
382 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000384 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385 Lex.Lex();
386 return false;
387}
388
Dan Gohman466876b2009-08-12 23:32:33 +0000389/// ParseUnnamedGlobal:
390/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000391/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000393/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000394/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000396bool LLParser::ParseUnnamedGlobal() {
397 unsigned VarID = NumberedVals.size();
398 std::string Name;
399 LocTy NameLoc = Lex.getLoc();
400
401 // Handle the GlobalID form.
402 if (Lex.getKind() == lltok::GlobalID) {
403 if (Lex.getUIntVal() != VarID)
404 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000405 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000406 Lex.Lex(); // eat GlobalID;
407
408 if (ParseToken(lltok::equal, "expected '=' after name"))
409 return true;
410 }
411
412 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000413 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000414 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000415 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000416 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000417 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000418 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000419 ParseOptionalThreadLocal(TLM) ||
420 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000421 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000422
Rafael Espindola464fe022014-07-30 22:51:54 +0000423 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000425 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000426 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000427 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000428}
429
Chris Lattnerac161bf2009-01-02 07:01:27 +0000430/// ParseNamedGlobal:
431/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000432/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434bool LLParser::ParseNamedGlobal() {
435 assert(Lex.getKind() == lltok::GlobalVar);
436 LocTy NameLoc = Lex.getLoc();
437 std::string Name = Lex.getStrVal();
438 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000439
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000441 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000442 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000443 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000446 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000447 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000448 ParseOptionalThreadLocal(TLM) ||
449 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Rafael Espindola464fe022014-07-30 22:51:54 +0000452 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000454 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000455
456 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000457 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458}
459
David Majnemerdad0a642014-06-27 18:19:56 +0000460bool LLParser::parseComdat() {
461 assert(Lex.getKind() == lltok::ComdatVar);
462 std::string Name = Lex.getStrVal();
463 LocTy NameLoc = Lex.getLoc();
464 Lex.Lex();
465
466 if (ParseToken(lltok::equal, "expected '=' here"))
467 return true;
468
469 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470 return TokError("expected comdat type");
471
472 Comdat::SelectionKind SK;
473 switch (Lex.getKind()) {
474 default:
475 return TokError("unknown selection kind");
476 case lltok::kw_any:
477 SK = Comdat::Any;
478 break;
479 case lltok::kw_exactmatch:
480 SK = Comdat::ExactMatch;
481 break;
482 case lltok::kw_largest:
483 SK = Comdat::Largest;
484 break;
485 case lltok::kw_noduplicates:
486 SK = Comdat::NoDuplicates;
487 break;
488 case lltok::kw_samesize:
489 SK = Comdat::SameSize;
490 break;
491 }
492 Lex.Lex();
493
494 // See if the comdat was forward referenced, if so, use the comdat.
495 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
499
500 Comdat *C;
501 if (I != ComdatSymTab.end())
502 C = &I->second;
503 else
504 C = M->getOrInsertComdat(Name);
505 C->setSelectionKind(SK);
506
507 return false;
508}
509
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000510// MDString:
511// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000512bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000513 std::string Str;
514 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000515 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000516 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000517 return false;
518}
519
520// MDNode:
521// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000522bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000523 // !{ ..., !42, ... }
524 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000525 if (ParseUInt32(MID))
526 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000527
Chris Lattner8eff0152010-04-01 05:14:45 +0000528 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000529 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000530 Result = NumberedMetadata[MID];
531 return false;
532 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000533
Chris Lattner8eff0152010-04-01 05:14:45 +0000534 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000535 auto &FwdRef = ForwardRefMDNodes[MID];
536 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000537
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000538 Result = FwdRef.first.get();
539 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000540 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000541}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000542
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000543/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000544/// !foo = !{ !1, !2 }
545bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000546 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000547 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000548 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000549
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000550 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000551 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000552 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000553 return true;
554
Dan Gohman2637cc12010-07-21 23:38:33 +0000555 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000556 if (Lex.getKind() != lltok::rbrace)
557 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000558 if (ParseToken(lltok::exclaim, "Expected '!' here"))
559 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000560
Craig Topper2617dcc2014-04-15 06:32:26 +0000561 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000562 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000563 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000564 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000565
566 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
567 return true;
568
Devang Patelbe626972009-07-29 00:34:02 +0000569 return false;
570}
571
Devang Patel39e64d42009-07-01 19:21:12 +0000572/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000574bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000575 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000576 Lex.Lex();
577 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000578
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000579 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000580 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000581 ParseToken(lltok::equal, "expected '=' here"))
582 return true;
583
584 // Detect common error, from old metadata syntax.
585 if (Lex.getKind() == lltok::Type)
586 return TokError("unexpected type in metadata definition");
587
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000588 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000589 if (Lex.getKind() == lltok::MetadataVar) {
590 if (ParseSpecializedMDNode(Init, IsDistinct))
591 return true;
592 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
593 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000594 return true;
595
Chris Lattnerfc58af22009-12-30 04:51:58 +0000596 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000597 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000598 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000599 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000600 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000601
Chris Lattnerfc58af22009-12-30 04:51:58 +0000602 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
603 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000604 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000605 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000606 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000607 }
608
Devang Patel39e64d42009-07-01 19:21:12 +0000609 return false;
610}
611
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000612static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
613 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
614 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
615}
616
Chris Lattnerac161bf2009-01-02 07:01:27 +0000617/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000618/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
619/// OptionalDLLStorageClass OptionalThreadLocal
620/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000621///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000622/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000623/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000624///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000625/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000626///
Rafael Espindola464fe022014-07-30 22:51:54 +0000627bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000628 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000629 GlobalVariable::ThreadLocalMode TLM,
630 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631 assert(Lex.getKind() == lltok::kw_alias);
632 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000633
Rafael Espindola78527052013-10-06 15:10:43 +0000634 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
635
Rafael Espindolacaa43562013-10-09 16:07:32 +0000636 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000637 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000638
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000639 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000640 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000641 "symbol with local linkage must have default visibility");
642
Rafael Espindola64c1e182014-06-03 02:41:57 +0000643 Constant *Aliasee;
644 LocTy AliaseeLoc = Lex.getLoc();
645 if (Lex.getKind() != lltok::kw_bitcast &&
646 Lex.getKind() != lltok::kw_getelementptr &&
647 Lex.getKind() != lltok::kw_addrspacecast &&
648 Lex.getKind() != lltok::kw_inttoptr) {
649 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000650 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000651 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000652 // The bitcast dest type is not present, it is implied by the dest type.
653 ValID ID;
654 if (ParseValID(ID))
655 return true;
656 if (ID.Kind != ValID::t_Constant)
657 return Error(AliaseeLoc, "invalid aliasee");
658 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000660
Rafael Espindola64c1e182014-06-03 02:41:57 +0000661 Type *AliaseeType = Aliasee->getType();
662 auto *PTy = dyn_cast<PointerType>(AliaseeType);
663 if (!PTy)
664 return Error(AliaseeLoc, "An alias must have pointer type");
665 Type *Ty = PTy->getElementType();
666 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000667
668 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000669 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000670 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
671 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000672 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000673 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000674 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000675 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000676
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677 // See if this value already exists in the symbol table. If so, it is either
678 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000679 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000680 // See if this was a redefinition. If so, there is no entry in
681 // ForwardRefVals.
682 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
683 I = ForwardRefVals.find(Name);
684 if (I == ForwardRefVals.end())
685 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
686
687 // Otherwise, this was a definition of forward ref. Verify that types
688 // agree.
689 if (Val->getType() != GA->getType())
690 return Error(NameLoc,
691 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000692
Chris Lattnerac161bf2009-01-02 07:01:27 +0000693 // If they agree, just RAUW the old value with the alias and remove the
694 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000695 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696 Val->eraseFromParent();
697 ForwardRefVals.erase(I);
698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000699
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000701 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000702 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000703
Rafael Espindolaaa273822014-05-09 21:49:17 +0000704 // The module owns this now
705 GA.release();
706
Chris Lattnerac161bf2009-01-02 07:01:27 +0000707 return false;
708}
709
710/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000711/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000712/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000713/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000714/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000715/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000716/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000717///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000718/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000719/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720///
721bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
722 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000723 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000724 GlobalVariable::ThreadLocalMode TLM,
725 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000726 if (!isValidVisibilityForLinkage(Visibility, Linkage))
727 return Error(NameLoc,
728 "symbol with local linkage must have default visibility");
729
Chris Lattnerac161bf2009-01-02 07:01:27 +0000730 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000731 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000732 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000733 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Craig Topper2617dcc2014-04-15 06:32:26 +0000735 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000736 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000737 ParseOptionalToken(lltok::kw_externally_initialized,
738 IsExternallyInitialized,
739 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000740 ParseGlobalType(IsConstant) ||
741 ParseType(Ty, TyLoc))
742 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000743
Chris Lattnerac161bf2009-01-02 07:01:27 +0000744 // If the linkage is specified and is external, then no initializer is
745 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000746 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000747 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 Linkage != GlobalValue::ExternalLinkage)) {
749 if (ParseGlobalValue(Ty, Init))
750 return true;
751 }
752
David Majnemer49b3d9b2015-02-16 08:41:08 +0000753 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000754 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
David Majnemer598bd052014-12-09 05:56:09 +0000756 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000757
758 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000759 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000760 GVal = M->getNamedValue(Name);
761 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000762 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
763 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000764 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765 } else {
766 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
767 I = ForwardRefValIDs.find(NumberedVals.size());
768 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000769 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000770 ForwardRefValIDs.erase(I);
771 }
772 }
773
David Majnemer598bd052014-12-09 05:56:09 +0000774 GlobalVariable *GV;
775 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000776 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
777 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000778 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000780 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000781 return Error(TyLoc,
782 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
David Majnemer598bd052014-12-09 05:56:09 +0000784 GV = cast<GlobalVariable>(GVal);
785
Chris Lattnerac161bf2009-01-02 07:01:27 +0000786 // Move the forward-reference to the correct spot in the module.
787 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
788 }
789
790 if (Name.empty())
791 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000792
Chris Lattnerac161bf2009-01-02 07:01:27 +0000793 // Set the parsed properties on the global.
794 if (Init)
795 GV->setInitializer(Init);
796 GV->setConstant(IsConstant);
797 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
798 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000799 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000800 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000801 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000802 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 // Parse attributes on the global.
805 while (Lex.getKind() == lltok::comma) {
806 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000807
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 if (Lex.getKind() == lltok::kw_section) {
809 Lex.Lex();
810 GV->setSection(Lex.getStrVal());
811 if (ParseToken(lltok::StringConstant, "expected global section string"))
812 return true;
813 } else if (Lex.getKind() == lltok::kw_align) {
814 unsigned Alignment;
815 if (ParseOptionalAlignment(Alignment)) return true;
816 GV->setAlignment(Alignment);
817 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000818 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000819 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000820 return true;
821 if (C)
822 GV->setComdat(C);
823 else
824 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 }
826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 return false;
829}
830
Bill Wendling63b88192013-02-06 06:52:58 +0000831/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000832/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000833bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000834 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000835 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000836 Lex.Lex();
837
David Majnemerb39e22b2014-12-09 18:33:57 +0000838 if (Lex.getKind() != lltok::AttrGrpID)
839 return TokError("expected attribute group id");
840
Bill Wendling63b88192013-02-06 06:52:58 +0000841 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000842 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000843 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000844 Lex.Lex();
845
846 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000847 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000848 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000849 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000850 ParseToken(lltok::rbrace, "expected end of attribute group"))
851 return true;
852
Bill Wendlingb32b0412013-02-08 06:32:06 +0000853 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000854 return Error(AttrGrpLoc, "attribute group has no attributes");
855
856 return false;
857}
858
Bill Wendling8b0321d2013-02-08 00:52:31 +0000859/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000860/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000861bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
862 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000863 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000864 bool HaveError = false;
865
866 B.clear();
867
Bill Wendling63b88192013-02-06 06:52:58 +0000868 while (true) {
869 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000870 if (Token == lltok::kw_builtin)
871 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000872 switch (Token) {
873 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000874 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000875 return Error(Lex.getLoc(), "unterminated attribute group");
876 case lltok::rbrace:
877 // Finished.
878 return false;
879
Bill Wendlingb32b0412013-02-08 06:32:06 +0000880 case lltok::AttrGrpID: {
881 // Allow a function to reference an attribute group:
882 //
883 // define void @foo() #1 { ... }
884 if (inAttrGrp)
885 HaveError |=
886 Error(Lex.getLoc(),
887 "cannot have an attribute group reference in an attribute group");
888
889 unsigned AttrGrpNum = Lex.getUIntVal();
890 if (inAttrGrp) break;
891
892 // Save the reference to the attribute group. We'll fill it in later.
893 FwdRefAttrGrps.push_back(AttrGrpNum);
894 break;
895 }
Bill Wendling63b88192013-02-06 06:52:58 +0000896 // Target-dependent attributes:
897 case lltok::StringConstant: {
898 std::string Attr = Lex.getStrVal();
899 Lex.Lex();
900 std::string Val;
901 if (EatIfPresent(lltok::equal) &&
902 ParseStringConstant(Val))
903 return true;
904
905 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000906 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000907 }
908
909 // Target-independent attributes:
910 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000911 // As a hack, we allow function alignment to be initially parsed as an
912 // attribute on a function declaration/definition or added to an attribute
913 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000914 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000915 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000916 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000917 if (ParseToken(lltok::equal, "expected '=' here") ||
918 ParseUInt32(Alignment))
919 return true;
920 } else {
921 if (ParseOptionalAlignment(Alignment))
922 return true;
923 }
Bill Wendling63b88192013-02-06 06:52:58 +0000924 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000925 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000926 }
927 case lltok::kw_alignstack: {
928 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000929 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000930 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
933 return true;
934 } else {
935 if (ParseOptionalStackAlignment(Alignment))
936 return true;
937 }
Bill Wendling63b88192013-02-06 06:52:58 +0000938 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000940 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000941 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000942 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000943 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000944 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000945 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000946 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
947 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
948 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
949 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
950 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
951 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
952 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
953 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
954 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
955 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000956 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000957 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
958 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
959 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
960 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
961 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
962 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
963 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
964 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
965 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
966 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
967 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000968
969 // Error handling.
970 case lltok::kw_inreg:
971 case lltok::kw_signext:
972 case lltok::kw_zeroext:
973 HaveError |=
974 Error(Lex.getLoc(),
975 "invalid use of attribute on a function");
976 break;
977 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000978 case lltok::kw_dereferenceable:
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;
1223 if (ParseOptionalDereferenceableBytes(Bytes))
1224 return true;
1225 B.addDereferenceableAttr(Bytes);
1226 continue;
1227 }
Reid Klecknera534a382013-12-19 02:14:12 +00001228 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001229 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1230 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1231 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1232 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001233 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001234 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1235 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001236 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001237 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1238 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1239 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001240
Stephen Lin7577ed52013-04-20 13:16:13 +00001241 case lltok::kw_alignstack:
1242 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001243 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001244 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001245 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001246 case lltok::kw_minsize:
1247 case lltok::kw_naked:
1248 case lltok::kw_nobuiltin:
1249 case lltok::kw_noduplicate:
1250 case lltok::kw_noimplicitfloat:
1251 case lltok::kw_noinline:
1252 case lltok::kw_nonlazybind:
1253 case lltok::kw_noredzone:
1254 case lltok::kw_noreturn:
1255 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001256 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001257 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001258 case lltok::kw_returns_twice:
1259 case lltok::kw_sanitize_address:
1260 case lltok::kw_sanitize_memory:
1261 case lltok::kw_sanitize_thread:
1262 case lltok::kw_ssp:
1263 case lltok::kw_sspreq:
1264 case lltok::kw_sspstrong:
1265 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001266 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1267 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001268 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001269
Bill Wendling34c2eb22012-12-04 23:40:58 +00001270 Lex.Lex();
1271 }
1272}
1273
1274/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1275bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1276 bool HaveError = false;
1277
1278 B.clear();
1279
1280 while (1) {
1281 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001282 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001283 default: // End of attributes.
1284 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001285 case lltok::kw_dereferenceable: {
1286 uint64_t Bytes;
1287 if (ParseOptionalDereferenceableBytes(Bytes))
1288 return true;
1289 B.addDereferenceableAttr(Bytes);
1290 continue;
1291 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001292 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1293 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001294 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001295 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1296 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001297
Bill Wendling34c2eb22012-12-04 23:40:58 +00001298 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001299 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001300 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001301 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001302 case lltok::kw_nest:
1303 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001304 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001305 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001306 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001307 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001308
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001309 case lltok::kw_alignstack:
1310 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001311 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001312 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001313 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001314 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001315 case lltok::kw_minsize:
1316 case lltok::kw_naked:
1317 case lltok::kw_nobuiltin:
1318 case lltok::kw_noduplicate:
1319 case lltok::kw_noimplicitfloat:
1320 case lltok::kw_noinline:
1321 case lltok::kw_nonlazybind:
1322 case lltok::kw_noredzone:
1323 case lltok::kw_noreturn:
1324 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001325 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001326 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001327 case lltok::kw_returns_twice:
1328 case lltok::kw_sanitize_address:
1329 case lltok::kw_sanitize_memory:
1330 case lltok::kw_sanitize_thread:
1331 case lltok::kw_ssp:
1332 case lltok::kw_sspreq:
1333 case lltok::kw_sspstrong:
1334 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001335 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001336 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001337
1338 case lltok::kw_readnone:
1339 case lltok::kw_readonly:
1340 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001341 }
1342
Chris Lattnerac161bf2009-01-02 07:01:27 +00001343 Lex.Lex();
1344 }
1345}
1346
1347/// ParseOptionalLinkage
1348/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001349/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001350/// ::= 'internal'
1351/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001352/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001353/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001354/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001355/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001358/// ::= 'extern_weak'
1359/// ::= 'external'
1360bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1361 HasLinkage = false;
1362 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001363 default: Res=GlobalValue::ExternalLinkage; return false;
1364 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001365 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1366 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1367 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1368 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1369 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001370 case lltok::kw_available_externally:
1371 Res = GlobalValue::AvailableExternallyLinkage;
1372 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001373 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001374 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001375 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1376 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001377 }
1378 Lex.Lex();
1379 HasLinkage = true;
1380 return false;
1381}
1382
1383/// ParseOptionalVisibility
1384/// ::= /*empty*/
1385/// ::= 'default'
1386/// ::= 'hidden'
1387/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001388///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001389bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1390 switch (Lex.getKind()) {
1391 default: Res = GlobalValue::DefaultVisibility; return false;
1392 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1393 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1394 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1395 }
1396 Lex.Lex();
1397 return false;
1398}
1399
Nico Rieck7157bb72014-01-14 15:22:47 +00001400/// ParseOptionalDLLStorageClass
1401/// ::= /*empty*/
1402/// ::= 'dllimport'
1403/// ::= 'dllexport'
1404///
1405bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1406 switch (Lex.getKind()) {
1407 default: Res = GlobalValue::DefaultStorageClass; return false;
1408 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1409 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1410 }
1411 Lex.Lex();
1412 return false;
1413}
1414
Chris Lattnerac161bf2009-01-02 07:01:27 +00001415/// ParseOptionalCallingConv
1416/// ::= /*empty*/
1417/// ::= 'ccc'
1418/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001419/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420/// ::= 'coldcc'
1421/// ::= 'x86_stdcallcc'
1422/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001423/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001424/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001425/// ::= 'arm_apcscc'
1426/// ::= 'arm_aapcscc'
1427/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001428/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001429/// ::= 'ptx_kernel'
1430/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001431/// ::= 'spir_func'
1432/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001433/// ::= 'x86_64_sysvcc'
1434/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001435/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001436/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001437/// ::= 'preserve_mostcc'
1438/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001439/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001440/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001441///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001442bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001443 switch (Lex.getKind()) {
1444 default: CC = CallingConv::C; return false;
1445 case lltok::kw_ccc: CC = CallingConv::C; break;
1446 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1447 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1448 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1449 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001450 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001451 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001452 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1453 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1454 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001455 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001456 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1457 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001458 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1459 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001460 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001461 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1462 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001463 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001464 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001465 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1466 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001467 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001468 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001469 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001470 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001471 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001472 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001473
Chris Lattnerac161bf2009-01-02 07:01:27 +00001474 Lex.Lex();
1475 return false;
1476}
1477
Chris Lattner5c427632009-12-30 05:31:19 +00001478/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001479/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001480bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1481 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001482 do {
1483 if (Lex.getKind() != lltok::MetadataVar)
1484 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001485
Chris Lattner596760d2009-12-29 21:25:40 +00001486 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001487 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001488 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001489
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001490 MDNode *N;
1491 if (ParseMDNode(N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001492 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001493
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001494 Inst->setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001495 if (MDK == LLVMContext::MD_tbaa)
1496 InstsWithTBAATag.push_back(Inst);
1497
Chris Lattner596760d2009-12-29 21:25:40 +00001498 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001499 } while (EatIfPresent(lltok::comma));
1500 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001501}
1502
Chris Lattnerac161bf2009-01-02 07:01:27 +00001503/// ParseOptionalAlignment
1504/// ::= /* empty */
1505/// ::= 'align' 4
1506bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1507 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001508 if (!EatIfPresent(lltok::kw_align))
1509 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001510 LocTy AlignLoc = Lex.getLoc();
1511 if (ParseUInt32(Alignment)) return true;
1512 if (!isPowerOf2_32(Alignment))
1513 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001514 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001515 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001516 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001517}
1518
Hal Finkelb0407ba2014-07-18 15:51:28 +00001519/// ParseOptionalDereferenceableBytes
1520/// ::= /* empty */
1521/// ::= 'dereferenceable' '(' 4 ')'
1522bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1523 Bytes = 0;
1524 if (!EatIfPresent(lltok::kw_dereferenceable))
1525 return false;
1526 LocTy ParenLoc = Lex.getLoc();
1527 if (!EatIfPresent(lltok::lparen))
1528 return Error(ParenLoc, "expected '('");
1529 LocTy DerefLoc = Lex.getLoc();
1530 if (ParseUInt64(Bytes)) return true;
1531 ParenLoc = Lex.getLoc();
1532 if (!EatIfPresent(lltok::rparen))
1533 return Error(ParenLoc, "expected ')'");
1534 if (!Bytes)
1535 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1536 return false;
1537}
1538
Chris Lattnerb2f39502009-12-30 05:44:30 +00001539/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001540/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001541/// ::= ',' align 4
1542///
1543/// This returns with AteExtraComma set to true if it ate an excess comma at the
1544/// end.
1545bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1546 bool &AteExtraComma) {
1547 AteExtraComma = false;
1548 while (EatIfPresent(lltok::comma)) {
1549 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001550 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001551 AteExtraComma = true;
1552 return false;
1553 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001554
Chris Lattner95b0ff42010-04-23 00:50:50 +00001555 if (Lex.getKind() != lltok::kw_align)
1556 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001557
Chris Lattner95b0ff42010-04-23 00:50:50 +00001558 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001559 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001560
Devang Patelea8a4b92009-09-17 23:04:48 +00001561 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562}
1563
Eli Friedmanfee02c62011-07-25 23:16:38 +00001564/// ParseScopeAndOrdering
1565/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1566/// else: ::=
1567///
1568/// This sets Scope and Ordering to the parsed values.
1569bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1570 AtomicOrdering &Ordering) {
1571 if (!isAtomic)
1572 return false;
1573
1574 Scope = CrossThread;
1575 if (EatIfPresent(lltok::kw_singlethread))
1576 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001577
1578 return ParseOrdering(Ordering);
1579}
1580
1581/// ParseOrdering
1582/// ::= AtomicOrdering
1583///
1584/// This sets Ordering to the parsed value.
1585bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001586 switch (Lex.getKind()) {
1587 default: return TokError("Expected ordering on atomic instruction");
1588 case lltok::kw_unordered: Ordering = Unordered; break;
1589 case lltok::kw_monotonic: Ordering = Monotonic; break;
1590 case lltok::kw_acquire: Ordering = Acquire; break;
1591 case lltok::kw_release: Ordering = Release; break;
1592 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1593 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1594 }
1595 Lex.Lex();
1596 return false;
1597}
1598
Charles Davisbe5557e2010-02-12 00:31:15 +00001599/// ParseOptionalStackAlignment
1600/// ::= /* empty */
1601/// ::= 'alignstack' '(' 4 ')'
1602bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1603 Alignment = 0;
1604 if (!EatIfPresent(lltok::kw_alignstack))
1605 return false;
1606 LocTy ParenLoc = Lex.getLoc();
1607 if (!EatIfPresent(lltok::lparen))
1608 return Error(ParenLoc, "expected '('");
1609 LocTy AlignLoc = Lex.getLoc();
1610 if (ParseUInt32(Alignment)) return true;
1611 ParenLoc = Lex.getLoc();
1612 if (!EatIfPresent(lltok::rparen))
1613 return Error(ParenLoc, "expected ')'");
1614 if (!isPowerOf2_32(Alignment))
1615 return Error(AlignLoc, "stack alignment is not a power of two");
1616 return false;
1617}
Devang Patelea8a4b92009-09-17 23:04:48 +00001618
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001619/// ParseIndexList - This parses the index list for an insert/extractvalue
1620/// instruction. This sets AteExtraComma in the case where we eat an extra
1621/// comma at the end of the line and find that it is followed by metadata.
1622/// Clients that don't allow metadata can call the version of this function that
1623/// only takes one argument.
1624///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001625/// ParseIndexList
1626/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001627///
1628bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1629 bool &AteExtraComma) {
1630 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001631
Chris Lattnerac161bf2009-01-02 07:01:27 +00001632 if (Lex.getKind() != lltok::comma)
1633 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001634
Chris Lattner3822f632009-01-02 08:05:26 +00001635 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001636 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001637 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001638 AteExtraComma = true;
1639 return false;
1640 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001641 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001642 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643 Indices.push_back(Idx);
1644 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001645
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646 return false;
1647}
1648
1649//===----------------------------------------------------------------------===//
1650// Type Parsing.
1651//===----------------------------------------------------------------------===//
1652
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001653/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001654bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001655 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001656 switch (Lex.getKind()) {
1657 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001658 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001659 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001660 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001661 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001662 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001664 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001665 // Type ::= StructType
1666 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001667 return true;
1668 break;
1669 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001670 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001671 Lex.Lex(); // eat the lsquare.
1672 if (ParseArrayVectorType(Result, false))
1673 return true;
1674 break;
1675 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001676 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001677 Lex.Lex();
1678 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001680 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001681 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682 } else if (ParseArrayVectorType(Result, true))
1683 return true;
1684 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001685 case lltok::LocalVar: {
1686 // Type ::= %foo
1687 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001688
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001689 // If the type hasn't been defined yet, create a forward definition and
1690 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001691 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001692 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001693 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001694 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001695 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001696 Lex.Lex();
1697 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001699
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001700 case lltok::LocalVarID: {
1701 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001702 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001703
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001704 // If the type hasn't been defined yet, create a forward definition and
1705 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001706 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001707 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001708 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001709 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001710 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001711 Lex.Lex();
1712 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713 }
1714 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001715
1716 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001717 while (1) {
1718 switch (Lex.getKind()) {
1719 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001720 default:
1721 if (!AllowVoid && Result->isVoidTy())
1722 return Error(TypeLoc, "void type only allowed for function results");
1723 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001725 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001726 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001727 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001728 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001729 if (Result->isVoidTy())
1730 return TokError("pointers to void are invalid - use i8* instead");
1731 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001732 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001733 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001734 Lex.Lex();
1735 break;
1736
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001737 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001739 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001741 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001742 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001744 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001745 unsigned AddrSpace;
1746 if (ParseOptionalAddrSpace(AddrSpace) ||
1747 ParseToken(lltok::star, "expected '*' in address space"))
1748 return true;
1749
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001750 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001751 break;
1752 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001753
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1755 case lltok::lparen:
1756 if (ParseFunctionType(Result))
1757 return true;
1758 break;
1759 }
1760 }
1761}
1762
1763/// ParseParameterList
1764/// ::= '(' ')'
1765/// ::= '(' Arg (',' Arg)* ')'
1766/// Arg
1767/// ::= Type OptionalAttributes Value OptionalAttributes
1768bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001769 PerFunctionState &PFS, bool IsMustTailCall,
1770 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 if (ParseToken(lltok::lparen, "expected '(' in call"))
1772 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001773
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001774 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001775 while (Lex.getKind() != lltok::rparen) {
1776 // If this isn't the first argument, we need a comma.
1777 if (!ArgList.empty() &&
1778 ParseToken(lltok::comma, "expected ',' in argument list"))
1779 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001780
Reid Kleckner83498642014-08-26 00:33:28 +00001781 // Parse an ellipsis if this is a musttail call in a variadic function.
1782 if (Lex.getKind() == lltok::dotdotdot) {
1783 const char *Msg = "unexpected ellipsis in argument list for ";
1784 if (!IsMustTailCall)
1785 return TokError(Twine(Msg) + "non-musttail call");
1786 if (!InVarArgsFunc)
1787 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1788 Lex.Lex(); // Lex the '...', it is purely for readability.
1789 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1790 }
1791
Chris Lattnerac161bf2009-01-02 07:01:27 +00001792 // Parse the argument.
1793 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001794 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001795 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001797 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001798 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001799
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001800 if (ArgTy->isMetadataTy()) {
1801 if (ParseMetadataAsValue(V, PFS))
1802 return true;
1803 } else {
1804 // Otherwise, handle normal operands.
1805 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1806 return true;
1807 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001808 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1809 AttrIndex++,
1810 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 }
1812
Reid Kleckner83498642014-08-26 00:33:28 +00001813 if (IsMustTailCall && InVarArgsFunc)
1814 return TokError("expected '...' at end of argument list for musttail call "
1815 "in varargs function");
1816
Chris Lattnerac161bf2009-01-02 07:01:27 +00001817 Lex.Lex(); // Lex the ')'.
1818 return false;
1819}
1820
1821
1822
Chris Lattner2ed06b42009-01-05 18:34:07 +00001823/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001824/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001825/// ::= '(' ArgTypeListI ')'
1826/// ArgTypeListI
1827/// ::= /*empty*/
1828/// ::= '...'
1829/// ::= ArgTypeList ',' '...'
1830/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001831///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001832bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1833 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001834 isVarArg = false;
1835 assert(Lex.getKind() == lltok::lparen);
1836 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001837
Chris Lattnerac161bf2009-01-02 07:01:27 +00001838 if (Lex.getKind() == lltok::rparen) {
1839 // empty
1840 } else if (Lex.getKind() == lltok::dotdotdot) {
1841 isVarArg = true;
1842 Lex.Lex();
1843 } else {
1844 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001845 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001846 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001847 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001848
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001849 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001850 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001851
Chris Lattnerfdd87902009-10-05 05:54:46 +00001852 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001853 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001854
Chris Lattnerdef19492011-06-17 06:36:20 +00001855 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 Name = Lex.getStrVal();
1857 Lex.Lex();
1858 }
Chris Lattner3822f632009-01-02 08:05:26 +00001859
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001860 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001861 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001862
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001863 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001864 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001865 AttributeSet::get(ArgTy->getContext(),
1866 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001867
Chris Lattner3822f632009-01-02 08:05:26 +00001868 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001869 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001870 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001872 break;
1873 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001874
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 // Otherwise must be an argument type.
1876 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001877 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001878
Chris Lattnerfdd87902009-10-05 05:54:46 +00001879 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001880 return Error(TypeLoc, "argument can not have void type");
1881
Chris Lattnerdef19492011-06-17 06:36:20 +00001882 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001883 Name = Lex.getStrVal();
1884 Lex.Lex();
1885 } else {
1886 Name = "";
1887 }
Chris Lattner3822f632009-01-02 08:05:26 +00001888
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001889 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001890 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001891
Bill Wendlingd079a442012-10-15 04:46:55 +00001892 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001893 AttributeSet::get(ArgTy->getContext(),
1894 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001895 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001896 }
1897 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001898
Chris Lattner3822f632009-01-02 08:05:26 +00001899 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001901
Chris Lattnerac161bf2009-01-02 07:01:27 +00001902/// ParseFunctionType
1903/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001904bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001905 assert(Lex.getKind() == lltok::lparen);
1906
Chris Lattnerce473c72009-01-05 08:04:33 +00001907 if (!FunctionType::isValidReturnType(Result))
1908 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001909
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001912 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001913 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001914
Chris Lattnerac161bf2009-01-02 07:01:27 +00001915 // Reject names on the arguments lists.
1916 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1917 if (!ArgList[i].Name.empty())
1918 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001919 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001920 return Error(ArgList[i].Loc,
1921 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001923
Jay Foadb804a2b2011-07-12 14:06:48 +00001924 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001925 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001927
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001928 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 return false;
1930}
1931
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1933/// other structs.
1934bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1935 SmallVector<Type*, 8> Elts;
1936 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001938 Result = StructType::get(Context, Elts, Packed);
1939 return false;
1940}
1941
1942/// ParseStructDefinition - Parse a struct in a 'type' definition.
1943bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1944 std::pair<Type*, LocTy> &Entry,
1945 Type *&ResultTy) {
1946 // If the type was already defined, diagnose the redefinition.
1947 if (Entry.first && !Entry.second.isValid())
1948 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001950 // If we have opaque, just return without filling in the definition for the
1951 // struct. This counts as a definition as far as the .ll file goes.
1952 if (EatIfPresent(lltok::kw_opaque)) {
1953 // This type is being defined, so clear the location to indicate this.
1954 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001955
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001956 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001957 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001958 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001959 ResultTy = Entry.first;
1960 return false;
1961 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001962
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963 // If the type starts with '<', then it is either a packed struct or a vector.
1964 bool isPacked = EatIfPresent(lltok::less);
1965
1966 // If we don't have a struct, then we have a random type alias, which we
1967 // accept for compatibility with old files. These types are not allowed to be
1968 // forward referenced and not allowed to be recursive.
1969 if (Lex.getKind() != lltok::lbrace) {
1970 if (Entry.first)
1971 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001972
Craig Topper2617dcc2014-04-15 06:32:26 +00001973 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001974 if (isPacked)
1975 return ParseArrayVectorType(ResultTy, true);
1976 return ParseType(ResultTy);
1977 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001978
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001979 // This type is being defined, so clear the location to indicate this.
1980 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001981
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001983 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001984 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001985
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001986 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001987
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001988 SmallVector<Type*, 8> Body;
1989 if (ParseStructBody(Body) ||
1990 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1991 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 STy->setBody(Body, isPacked);
1994 ResultTy = STy;
1995 return false;
1996}
1997
1998
Chris Lattnerac161bf2009-01-02 07:01:27 +00001999/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002000/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002001/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002003/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002004/// ::= '<' '{' Type (',' Type)* '}' '>'
2005bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 assert(Lex.getKind() == lltok::lbrace);
2007 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002008
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009 // Handle the empty struct.
2010 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002012
Chris Lattnerf880ca22009-03-09 04:49:14 +00002013 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002014 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 if (ParseType(Ty)) return true;
2016 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002017
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002018 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002019 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002020
Chris Lattner3822f632009-01-02 08:05:26 +00002021 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002022 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002024
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002026 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002027
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002032}
2033
2034/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2035/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002036/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002037/// ::= '[' APSINTVAL 'x' Types ']'
2038/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002039bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002040 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2041 Lex.getAPSIntVal().getBitWidth() > 64)
2042 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002043
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044 LocTy SizeLoc = Lex.getLoc();
2045 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002046 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002047
Chris Lattner3822f632009-01-02 08:05:26 +00002048 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2049 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050
2051 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002052 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002054
Chris Lattner3822f632009-01-02 08:05:26 +00002055 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2056 "expected end of sequential type"))
2057 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002058
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002060 if (Size == 0)
2061 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 if ((unsigned)Size != Size)
2063 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002064 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002065 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002066 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002068 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 }
2072 return false;
2073}
2074
2075//===----------------------------------------------------------------------===//
2076// Function Semantic Analysis.
2077//===----------------------------------------------------------------------===//
2078
Chris Lattner3432c622009-10-28 03:39:23 +00002079LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2080 int functionNumber)
2081 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002082
2083 // Insert unnamed arguments into the NumberedVals list.
2084 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2085 AI != E; ++AI)
2086 if (!AI->hasName())
2087 NumberedVals.push_back(AI);
2088}
2089
2090LLParser::PerFunctionState::~PerFunctionState() {
2091 // If there were any forward referenced non-basicblock values, delete them.
2092 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2093 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2094 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002095 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002096 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002097 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002098 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2102 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2103 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002104 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002105 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002107 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002108 }
2109}
2110
Chris Lattner3432c622009-10-28 03:39:23 +00002111bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002112 if (!ForwardRefVals.empty())
2113 return P.Error(ForwardRefVals.begin()->second.second,
2114 "use of undefined value '%" + ForwardRefVals.begin()->first +
2115 "'");
2116 if (!ForwardRefValIDs.empty())
2117 return P.Error(ForwardRefValIDs.begin()->second.second,
2118 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002119 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 return false;
2121}
2122
2123
2124/// GetVal - Get a value with the specified name or ID, creating a
2125/// forward reference record if needed. This can return null if the value
2126/// exists but does not have the right type.
2127Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002128 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 // Look this name up in the normal function symbol table.
2130 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002131
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132 // If this is a forward reference for the value, see if we already created a
2133 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002134 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2136 I = ForwardRefVals.find(Name);
2137 if (I != ForwardRefVals.end())
2138 Val = I->second.first;
2139 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002140
Chris Lattnerac161bf2009-01-02 07:01:27 +00002141 // If we have the value in the symbol table or fwd-ref table, return it.
2142 if (Val) {
2143 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002144 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002145 P.Error(Loc, "'%" + Name + "' is not a basic block");
2146 else
2147 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002148 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002149 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002153 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002155 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002157
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 // Otherwise, create a new forward reference for this value and remember it.
2159 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002160 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002161 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 else
2163 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002164
Chris Lattnerac161bf2009-01-02 07:01:27 +00002165 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2166 return FwdVal;
2167}
2168
Chris Lattner229907c2011-07-18 04:54:35 +00002169Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 LocTy Loc) {
2171 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002172 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173
Chris Lattnerac161bf2009-01-02 07:01:27 +00002174 // If this is a forward reference for the value, see if we already created a
2175 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002176 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002177 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2178 I = ForwardRefValIDs.find(ID);
2179 if (I != ForwardRefValIDs.end())
2180 Val = I->second.first;
2181 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002182
Chris Lattnerac161bf2009-01-02 07:01:27 +00002183 // If we have the value in the symbol table or fwd-ref table, return it.
2184 if (Val) {
2185 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002186 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002187 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002188 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002189 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002190 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002191 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002193
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002194 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002196 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002198
Chris Lattnerac161bf2009-01-02 07:01:27 +00002199 // Otherwise, create a new forward reference for this value and remember it.
2200 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002201 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002202 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002203 else
2204 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002205
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2207 return FwdVal;
2208}
2209
2210/// SetInstName - After an instruction is parsed and inserted into its
2211/// basic block, this installs its name.
2212bool LLParser::PerFunctionState::SetInstName(int NameID,
2213 const std::string &NameStr,
2214 LocTy NameLoc, Instruction *Inst) {
2215 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002216 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 if (NameID != -1 || !NameStr.empty())
2218 return P.Error(NameLoc, "instructions returning void cannot have a name");
2219 return false;
2220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002221
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 // If this was a numbered instruction, verify that the instruction is the
2223 // expected value and resolve any forward references.
2224 if (NameStr.empty()) {
2225 // If neither a name nor an ID was specified, just use the next ID.
2226 if (NameID == -1)
2227 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002228
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 if (unsigned(NameID) != NumberedVals.size())
2230 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002231 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002232
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2234 ForwardRefValIDs.find(NameID);
2235 if (FI != ForwardRefValIDs.end()) {
2236 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002237 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002238 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002240 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002241 ForwardRefValIDs.erase(FI);
2242 }
2243
2244 NumberedVals.push_back(Inst);
2245 return false;
2246 }
2247
2248 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2249 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2250 FI = ForwardRefVals.find(NameStr);
2251 if (FI != ForwardRefVals.end()) {
2252 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002254 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002256 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 ForwardRefVals.erase(FI);
2258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 // Set the name on the instruction.
2261 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002262
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002263 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002264 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 NameStr + "'");
2266 return false;
2267}
2268
2269/// GetBB - Get a basic block with the specified name or ID, creating a
2270/// forward reference record if needed.
2271BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2272 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002273 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2274 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275}
2276
2277BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002278 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2279 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280}
2281
2282/// DefineBB - Define the specified basic block, which is either named or
2283/// unnamed. If there is an error, this returns null otherwise it returns
2284/// the block being defined.
2285BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2286 LocTy Loc) {
2287 BasicBlock *BB;
2288 if (Name.empty())
2289 BB = GetBB(NumberedVals.size(), Loc);
2290 else
2291 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002292 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 // Move the block to the end of the function. Forward ref'd blocks are
2295 // inserted wherever they happen to be referenced.
2296 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002297
Chris Lattnerac161bf2009-01-02 07:01:27 +00002298 // Remove the block from forward ref sets.
2299 if (Name.empty()) {
2300 ForwardRefValIDs.erase(NumberedVals.size());
2301 NumberedVals.push_back(BB);
2302 } else {
2303 // BB forward references are already in the function symbol table.
2304 ForwardRefVals.erase(Name);
2305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002306
Chris Lattnerac161bf2009-01-02 07:01:27 +00002307 return BB;
2308}
2309
2310//===----------------------------------------------------------------------===//
2311// Constants.
2312//===----------------------------------------------------------------------===//
2313
2314/// ParseValID - Parse an abstract value that doesn't necessarily have a
2315/// type implied. For example, if we parse "4" we don't know what integer type
2316/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002317/// sanity. PFS is used to convert function-local operands of metadata (since
2318/// metadata operands are not just parsed here but also converted to values).
2319/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002320bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002321 ID.Loc = Lex.getLoc();
2322 switch (Lex.getKind()) {
2323 default: return TokError("expected value token");
2324 case lltok::GlobalID: // @42
2325 ID.UIntVal = Lex.getUIntVal();
2326 ID.Kind = ValID::t_GlobalID;
2327 break;
2328 case lltok::GlobalVar: // @foo
2329 ID.StrVal = Lex.getStrVal();
2330 ID.Kind = ValID::t_GlobalName;
2331 break;
2332 case lltok::LocalVarID: // %42
2333 ID.UIntVal = Lex.getUIntVal();
2334 ID.Kind = ValID::t_LocalID;
2335 break;
2336 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 ID.StrVal = Lex.getStrVal();
2338 ID.Kind = ValID::t_LocalName;
2339 break;
2340 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002341 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 ID.Kind = ValID::t_APSInt;
2343 break;
2344 case lltok::APFloat:
2345 ID.APFloatVal = Lex.getAPFloatVal();
2346 ID.Kind = ValID::t_APFloat;
2347 break;
2348 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002349 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 ID.Kind = ValID::t_Constant;
2351 break;
2352 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002353 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 ID.Kind = ValID::t_Constant;
2355 break;
2356 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2357 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2358 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002359
Chris Lattnerac161bf2009-01-02 07:01:27 +00002360 case lltok::lbrace: {
2361 // ValID ::= '{' ConstVector '}'
2362 Lex.Lex();
2363 SmallVector<Constant*, 16> Elts;
2364 if (ParseGlobalValueVector(Elts) ||
2365 ParseToken(lltok::rbrace, "expected end of struct constant"))
2366 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002367
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002368 ID.ConstantStructElts = new Constant*[Elts.size()];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002369 ID.UIntVal = Elts.size();
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002370 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002371 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 return false;
2373 }
2374 case lltok::less: {
2375 // ValID ::= '<' ConstVector '>' --> Vector.
2376 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2377 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002378 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002379
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380 SmallVector<Constant*, 16> Elts;
2381 LocTy FirstEltLoc = Lex.getLoc();
2382 if (ParseGlobalValueVector(Elts) ||
2383 (isPackedStruct &&
2384 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2385 ParseToken(lltok::greater, "expected end of constant"))
2386 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002387
Chris Lattnerac161bf2009-01-02 07:01:27 +00002388 if (isPackedStruct) {
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002389 ID.ConstantStructElts = new Constant*[Elts.size()];
2390 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002391 ID.UIntVal = Elts.size();
2392 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 return false;
2394 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002395
Chris Lattnerac161bf2009-01-02 07:01:27 +00002396 if (Elts.empty())
2397 return Error(ID.Loc, "constant vector must not be empty");
2398
Duncan Sands9dff9be2010-02-15 16:12:20 +00002399 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002400 !Elts[0]->getType()->isFloatingPointTy() &&
2401 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002403 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002404
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405 // Verify that all the vector elements have the same type.
2406 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2407 if (Elts[i]->getType() != Elts[0]->getType())
2408 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002409 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002410 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002411
Chris Lattner69229312011-02-15 00:14:00 +00002412 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 ID.Kind = ValID::t_Constant;
2414 return false;
2415 }
2416 case lltok::lsquare: { // Array Constant
2417 Lex.Lex();
2418 SmallVector<Constant*, 16> Elts;
2419 LocTy FirstEltLoc = Lex.getLoc();
2420 if (ParseGlobalValueVector(Elts) ||
2421 ParseToken(lltok::rsquare, "expected end of array constant"))
2422 return true;
2423
2424 // Handle empty element.
2425 if (Elts.empty()) {
2426 // Use undef instead of an array because it's inconvenient to determine
2427 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002428 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429 return false;
2430 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002431
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002434 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Owen Anderson4056ca92009-07-29 22:17:13 +00002436 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002437
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002439 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 if (Elts[i]->getType() != Elts[0]->getType())
2441 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002442 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002443 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002445
Jay Foad83be3612011-06-22 09:24:39 +00002446 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 ID.Kind = ValID::t_Constant;
2448 return false;
2449 }
2450 case lltok::kw_c: // c "foo"
2451 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002452 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2453 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002454 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2455 ID.Kind = ValID::t_Constant;
2456 return false;
2457
2458 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002459 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2460 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002461 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462 Lex.Lex();
2463 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002464 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002465 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002466 ParseStringConstant(ID.StrVal) ||
2467 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002468 ParseToken(lltok::StringConstant, "expected constraint string"))
2469 return true;
2470 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002471 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002472 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 ID.Kind = ValID::t_InlineAsm;
2474 return false;
2475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002476
Chris Lattner3432c622009-10-28 03:39:23 +00002477 case lltok::kw_blockaddress: {
2478 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2479 Lex.Lex();
2480
2481 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002482
Chris Lattner3432c622009-10-28 03:39:23 +00002483 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2484 ParseValID(Fn) ||
2485 ParseToken(lltok::comma, "expected comma in block address expression")||
2486 ParseValID(Label) ||
2487 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2488 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002489
Chris Lattner3432c622009-10-28 03:39:23 +00002490 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2491 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002492 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002493 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002494
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002495 // Try to find the function (but skip it if it's forward-referenced).
2496 GlobalValue *GV = nullptr;
2497 if (Fn.Kind == ValID::t_GlobalID) {
2498 if (Fn.UIntVal < NumberedVals.size())
2499 GV = NumberedVals[Fn.UIntVal];
2500 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2501 GV = M->getNamedValue(Fn.StrVal);
2502 }
2503 Function *F = nullptr;
2504 if (GV) {
2505 // Confirm that it's actually a function with a definition.
2506 if (!isa<Function>(GV))
2507 return Error(Fn.Loc, "expected function name in blockaddress");
2508 F = cast<Function>(GV);
2509 if (F->isDeclaration())
2510 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2511 }
2512
2513 if (!F) {
2514 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002515 GlobalValue *&FwdRef =
2516 ForwardRefBlockAddresses.insert(std::make_pair(
2517 std::move(Fn),
2518 std::map<ValID, GlobalValue *>()))
2519 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2520 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002521 if (!FwdRef)
2522 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2523 GlobalValue::InternalLinkage, nullptr, "");
2524 ID.ConstantVal = FwdRef;
2525 ID.Kind = ValID::t_Constant;
2526 return false;
2527 }
2528
2529 // We found the function; now find the basic block. Don't use PFS, since we
2530 // might be inside a constant expression.
2531 BasicBlock *BB;
2532 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2533 if (Label.Kind == ValID::t_LocalID)
2534 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2535 else
2536 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2537 if (!BB)
2538 return Error(Label.Loc, "referenced value is not a basic block");
2539 } else {
2540 if (Label.Kind == ValID::t_LocalID)
2541 return Error(Label.Loc, "cannot take address of numeric label after "
2542 "the function is defined");
2543 BB = dyn_cast_or_null<BasicBlock>(
2544 F->getValueSymbolTable().lookup(Label.StrVal));
2545 if (!BB)
2546 return Error(Label.Loc, "referenced value is not a basic block");
2547 }
2548
2549 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002550 ID.Kind = ValID::t_Constant;
2551 return false;
2552 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002553
Chris Lattnerac161bf2009-01-02 07:01:27 +00002554 case lltok::kw_trunc:
2555 case lltok::kw_zext:
2556 case lltok::kw_sext:
2557 case lltok::kw_fptrunc:
2558 case lltok::kw_fpext:
2559 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002560 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 case lltok::kw_uitofp:
2562 case lltok::kw_sitofp:
2563 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002564 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002568 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 Constant *SrcVal;
2570 Lex.Lex();
2571 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2572 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002573 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 ParseType(DestTy) ||
2575 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2576 return true;
2577 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2578 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002579 getTypeString(SrcVal->getType()) + "' to '" +
2580 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002581 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002582 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002583 ID.Kind = ValID::t_Constant;
2584 return false;
2585 }
2586 case lltok::kw_extractvalue: {
2587 Lex.Lex();
2588 Constant *Val;
2589 SmallVector<unsigned, 4> Indices;
2590 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2591 ParseGlobalTypeAndValue(Val) ||
2592 ParseIndexList(Indices) ||
2593 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2594 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002595
Chris Lattner392be582010-02-12 20:49:41 +00002596 if (!Val->getType()->isAggregateType())
2597 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002598 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002600 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002601 ID.Kind = ValID::t_Constant;
2602 return false;
2603 }
2604 case lltok::kw_insertvalue: {
2605 Lex.Lex();
2606 Constant *Val0, *Val1;
2607 SmallVector<unsigned, 4> Indices;
2608 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2609 ParseGlobalTypeAndValue(Val0) ||
2610 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2611 ParseGlobalTypeAndValue(Val1) ||
2612 ParseIndexList(Indices) ||
2613 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2614 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002615 if (!Val0->getType()->isAggregateType())
2616 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002617 Type *IndexedType =
2618 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2619 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002621 if (IndexedType != Val1->getType())
2622 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2623 getTypeString(Val1->getType()) +
2624 "' instead of '" + getTypeString(IndexedType) +
2625 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002626 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 ID.Kind = ValID::t_Constant;
2628 return false;
2629 }
2630 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002631 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 unsigned PredVal, Opc = Lex.getUIntVal();
2633 Constant *Val0, *Val1;
2634 Lex.Lex();
2635 if (ParseCmpPredicate(PredVal, Opc) ||
2636 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2637 ParseGlobalTypeAndValue(Val0) ||
2638 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2639 ParseGlobalTypeAndValue(Val1) ||
2640 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2641 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002642
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 if (Val0->getType() != Val1->getType())
2644 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002645
Chris Lattnerac161bf2009-01-02 07:01:27 +00002646 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002647
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002649 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002651 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002652 } else {
2653 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002654 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002655 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002657 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 }
2659 ID.Kind = ValID::t_Constant;
2660 return false;
2661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002662
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 // Binary Operators.
2664 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002665 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002667 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002669 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 case lltok::kw_udiv:
2671 case lltok::kw_sdiv:
2672 case lltok::kw_fdiv:
2673 case lltok::kw_urem:
2674 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002675 case lltok::kw_frem:
2676 case lltok::kw_shl:
2677 case lltok::kw_lshr:
2678 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002679 bool NUW = false;
2680 bool NSW = false;
2681 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002682 unsigned Opc = Lex.getUIntVal();
2683 Constant *Val0, *Val1;
2684 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002685 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002686 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2687 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002688 if (EatIfPresent(lltok::kw_nuw))
2689 NUW = true;
2690 if (EatIfPresent(lltok::kw_nsw)) {
2691 NSW = true;
2692 if (EatIfPresent(lltok::kw_nuw))
2693 NUW = true;
2694 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002695 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2696 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002697 if (EatIfPresent(lltok::kw_exact))
2698 Exact = true;
2699 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2701 ParseGlobalTypeAndValue(Val0) ||
2702 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2703 ParseGlobalTypeAndValue(Val1) ||
2704 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2705 return true;
2706 if (Val0->getType() != Val1->getType())
2707 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002708 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002709 if (NUW)
2710 return Error(ModifierLoc, "nuw only applies to integer operations");
2711 if (NSW)
2712 return Error(ModifierLoc, "nsw only applies to integer operations");
2713 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002714 // Check that the type is valid for the operator.
2715 switch (Opc) {
2716 case Instruction::Add:
2717 case Instruction::Sub:
2718 case Instruction::Mul:
2719 case Instruction::UDiv:
2720 case Instruction::SDiv:
2721 case Instruction::URem:
2722 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002723 case Instruction::Shl:
2724 case Instruction::AShr:
2725 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002726 if (!Val0->getType()->isIntOrIntVectorTy())
2727 return Error(ID.Loc, "constexpr requires integer operands");
2728 break;
2729 case Instruction::FAdd:
2730 case Instruction::FSub:
2731 case Instruction::FMul:
2732 case Instruction::FDiv:
2733 case Instruction::FRem:
2734 if (!Val0->getType()->isFPOrFPVectorTy())
2735 return Error(ID.Loc, "constexpr requires fp operands");
2736 break;
2737 default: llvm_unreachable("Unknown binary operator!");
2738 }
Dan Gohman1b849082009-09-07 23:54:19 +00002739 unsigned Flags = 0;
2740 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2741 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002742 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002743 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002744 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002745 ID.Kind = ValID::t_Constant;
2746 return false;
2747 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002748
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002750 case lltok::kw_and:
2751 case lltok::kw_or:
2752 case lltok::kw_xor: {
2753 unsigned Opc = Lex.getUIntVal();
2754 Constant *Val0, *Val1;
2755 Lex.Lex();
2756 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2757 ParseGlobalTypeAndValue(Val0) ||
2758 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2759 ParseGlobalTypeAndValue(Val1) ||
2760 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2761 return true;
2762 if (Val0->getType() != Val1->getType())
2763 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002764 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 return Error(ID.Loc,
2766 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002767 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 ID.Kind = ValID::t_Constant;
2769 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002770 }
2771
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 case lltok::kw_getelementptr:
2773 case lltok::kw_shufflevector:
2774 case lltok::kw_insertelement:
2775 case lltok::kw_extractelement:
2776 case lltok::kw_select: {
2777 unsigned Opc = Lex.getUIntVal();
2778 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002779 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002780 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002782
Dan Gohman1639c392009-07-27 21:53:46 +00002783 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002784 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002785
2786 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2787 return true;
2788
2789 LocTy ExplicitTypeLoc = Lex.getLoc();
2790 if (Opc == Instruction::GetElementPtr) {
2791 if (ParseType(Ty) ||
2792 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2793 return true;
2794 }
2795
2796 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002797 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2798 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002799
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002801 if (Elts.size() == 0 ||
2802 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002803 return Error(ID.Loc, "base of getelementptr must be a pointer");
2804
2805 Type *BaseType = Elts[0]->getType();
2806 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002807 if (Ty != BasePointerType->getElementType())
2808 return Error(
2809 ExplicitTypeLoc,
2810 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811
Jay Foaded8db7d2011-07-21 14:31:17 +00002812 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002813 for (Constant *Val : Indices) {
2814 Type *ValTy = Val->getType();
2815 if (!ValTy->getScalarType()->isIntegerTy())
2816 return Error(ID.Loc, "getelementptr index must be an integer");
2817 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2818 return Error(ID.Loc, "getelementptr index type missmatch");
2819 if (ValTy->isVectorTy()) {
2820 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2821 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2822 if (ValNumEl != PtrNumEl)
2823 return Error(
2824 ID.Loc,
2825 "getelementptr vector index has a wrong number of elements");
2826 }
2827 }
2828
Owen Andersone90f9922015-03-10 06:34:57 +00002829 SmallPtrSet<const Type*, 4> Visited;
2830 if (!Indices.empty() &&
2831 !BasePointerType->getElementType()->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002832 return Error(ID.Loc, "base element of getelementptr must be sized");
2833
David Blaikie4a2e73b2015-04-02 18:55:32 +00002834 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002835 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002836 ID.ConstantVal =
2837 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002838 } else if (Opc == Instruction::Select) {
2839 if (Elts.size() != 3)
2840 return Error(ID.Loc, "expected three operands to select");
2841 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2842 Elts[2]))
2843 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002844 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002845 } else if (Opc == Instruction::ShuffleVector) {
2846 if (Elts.size() != 3)
2847 return Error(ID.Loc, "expected three operands to shufflevector");
2848 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2849 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002850 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002851 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 } else if (Opc == Instruction::ExtractElement) {
2853 if (Elts.size() != 2)
2854 return Error(ID.Loc, "expected two operands to extractelement");
2855 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2856 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002857 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 } else {
2859 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2860 if (Elts.size() != 3)
2861 return Error(ID.Loc, "expected three operands to insertelement");
2862 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2863 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002864 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002865 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002866 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002867
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 ID.Kind = ValID::t_Constant;
2869 return false;
2870 }
2871 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002872
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 Lex.Lex();
2874 return false;
2875}
2876
2877/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002878bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002879 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002880 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002881 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002882 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002883 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002884 if (V && !(C = dyn_cast<Constant>(V)))
2885 return Error(ID.Loc, "global values must be constants");
2886 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887}
2888
Victor Hernandez9d75c962010-01-11 22:31:58 +00002889bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002890 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002891 return ParseType(Ty) ||
2892 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002893}
2894
Rafael Espindola83a362c2015-01-06 22:55:16 +00002895bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002896 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002897
2898 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002899 if (!EatIfPresent(lltok::kw_comdat))
2900 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002901
2902 if (EatIfPresent(lltok::lparen)) {
2903 if (Lex.getKind() != lltok::ComdatVar)
2904 return TokError("expected comdat variable");
2905 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2906 Lex.Lex();
2907 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2908 return true;
2909 } else {
2910 if (GlobalName.empty())
2911 return TokError("comdat cannot be unnamed");
2912 C = getComdat(GlobalName, KwLoc);
2913 }
2914
David Majnemerdad0a642014-06-27 18:19:56 +00002915 return false;
2916}
2917
Victor Hernandez9d75c962010-01-11 22:31:58 +00002918/// ParseGlobalValueVector
2919/// ::= /*empty*/
2920/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002921bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002922 // Empty list.
2923 if (Lex.getKind() == lltok::rbrace ||
2924 Lex.getKind() == lltok::rsquare ||
2925 Lex.getKind() == lltok::greater ||
2926 Lex.getKind() == lltok::rparen)
2927 return false;
2928
2929 Constant *C;
2930 if (ParseGlobalTypeAndValue(C)) return true;
2931 Elts.push_back(C);
2932
2933 while (EatIfPresent(lltok::comma)) {
2934 if (ParseGlobalTypeAndValue(C)) return true;
2935 Elts.push_back(C);
2936 }
2937
2938 return false;
2939}
2940
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002941bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002942 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002943 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002944 return true;
2945
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002946 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002947 return false;
2948}
2949
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002950/// MDNode:
2951/// ::= !{ ... }
2952/// ::= !7
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002953/// ::= !MDLocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002954bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002955 if (Lex.getKind() == lltok::MetadataVar)
2956 return ParseSpecializedMDNode(N);
2957
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002958 return ParseToken(lltok::exclaim, "expected '!' here") ||
2959 ParseMDNodeTail(N);
2960}
2961
2962bool LLParser::ParseMDNodeTail(MDNode *&N) {
2963 // !{ ... }
2964 if (Lex.getKind() == lltok::lbrace)
2965 return ParseMDTuple(N);
2966
2967 // !42
2968 return ParseMDNodeID(N);
2969}
2970
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002971namespace {
2972
2973/// Structure to represent an optional metadata field.
2974template <class FieldTy> struct MDFieldImpl {
2975 typedef MDFieldImpl ImplTy;
2976 FieldTy Val;
2977 bool Seen;
2978
2979 void assign(FieldTy Val) {
2980 Seen = true;
2981 this->Val = std::move(Val);
2982 }
2983
2984 explicit MDFieldImpl(FieldTy Default)
2985 : Val(std::move(Default)), Seen(false) {}
2986};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002987
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002988struct MDUnsignedField : public MDFieldImpl<uint64_t> {
2989 uint64_t Max;
2990
2991 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
2992 : ImplTy(Default), Max(Max) {}
2993};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00002994struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00002995 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00002996};
2997struct ColumnField : public MDUnsignedField {
2998 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
2999};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003000struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003001 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003002 DwarfTagField(dwarf::Tag DefaultTag)
3003 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003004};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003005struct DwarfAttEncodingField : public MDUnsignedField {
3006 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3007};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003008struct DwarfVirtualityField : public MDUnsignedField {
3009 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3010};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003011struct DwarfLangField : public MDUnsignedField {
3012 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3013};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003014
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003015struct DIFlagField : public MDUnsignedField {
3016 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3017};
3018
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003019struct MDSignedField : public MDFieldImpl<int64_t> {
3020 int64_t Min;
3021 int64_t Max;
3022
3023 MDSignedField(int64_t Default = 0)
3024 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3025 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3026 : ImplTy(Default), Min(Min), Max(Max) {}
3027};
3028
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003029struct MDBoolField : public MDFieldImpl<bool> {
3030 MDBoolField(bool Default = false) : ImplTy(Default) {}
3031};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003032struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003033 bool AllowNull;
3034
3035 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003036};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003037struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3038 MDConstant() : ImplTy(nullptr) {}
3039};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003040struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003041 bool AllowEmpty;
3042 MDStringField(bool AllowEmpty = true)
3043 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003044};
3045struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3046 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3047};
3048
3049} // end namespace
3050
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003051namespace llvm {
3052
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003053template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003054bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003055 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003056 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3057 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003058
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003059 auto &U = Lex.getAPSIntVal();
3060 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003061 return TokError("value for '" + Name + "' too large, limit is " +
3062 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003063 Result.assign(U.getZExtValue());
3064 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003065 Lex.Lex();
3066 return false;
3067}
3068
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003069template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003070bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3071 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3072}
3073template <>
3074bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3075 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3076}
3077
3078template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003079bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3080 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003081 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003082
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003083 if (Lex.getKind() != lltok::DwarfTag)
3084 return TokError("expected DWARF tag");
3085
3086 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3087 if (Tag == dwarf::DW_TAG_invalid)
3088 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003089 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003090
3091 Result.assign(Tag);
3092 Lex.Lex();
3093 return false;
3094}
3095
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003096template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003097bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3098 DwarfVirtualityField &Result) {
3099 if (Lex.getKind() == lltok::APSInt)
3100 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3101
3102 if (Lex.getKind() != lltok::DwarfVirtuality)
3103 return TokError("expected DWARF virtuality code");
3104
3105 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3106 if (!Virtuality)
3107 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3108 Lex.getStrVal() + "'");
3109 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3110 Result.assign(Virtuality);
3111 Lex.Lex();
3112 return false;
3113}
3114
3115template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003116bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3117 if (Lex.getKind() == lltok::APSInt)
3118 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3119
3120 if (Lex.getKind() != lltok::DwarfLang)
3121 return TokError("expected DWARF language");
3122
3123 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3124 if (!Lang)
3125 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3126 "'");
3127 assert(Lang <= Result.Max && "Expected valid DWARF language");
3128 Result.assign(Lang);
3129 Lex.Lex();
3130 return false;
3131}
3132
3133template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003134bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003135 DwarfAttEncodingField &Result) {
3136 if (Lex.getKind() == lltok::APSInt)
3137 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3138
3139 if (Lex.getKind() != lltok::DwarfAttEncoding)
3140 return TokError("expected DWARF type attribute encoding");
3141
3142 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3143 if (!Encoding)
3144 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3145 Lex.getStrVal() + "'");
3146 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3147 Result.assign(Encoding);
3148 Lex.Lex();
3149 return false;
3150}
3151
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003152/// DIFlagField
3153/// ::= uint32
3154/// ::= DIFlagVector
3155/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3156template <>
3157bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3158 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3159
3160 // Parser for a single flag.
3161 auto parseFlag = [&](unsigned &Val) {
3162 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3163 return ParseUInt32(Val);
3164
3165 if (Lex.getKind() != lltok::DIFlag)
3166 return TokError("expected debug info flag");
3167
Duncan P. N. Exon Smith5261e4b2015-04-07 01:21:40 +00003168 Val = DebugNode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003169 if (!Val)
3170 return TokError(Twine("invalid debug info flag flag '") +
3171 Lex.getStrVal() + "'");
3172 Lex.Lex();
3173 return false;
3174 };
3175
3176 // Parse the flags and combine them together.
3177 unsigned Combined = 0;
3178 do {
3179 unsigned Val;
3180 if (parseFlag(Val))
3181 return true;
3182 Combined |= Val;
3183 } while (EatIfPresent(lltok::bar));
3184
3185 Result.assign(Combined);
3186 return false;
3187}
3188
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003189template <>
3190bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003191 MDSignedField &Result) {
3192 if (Lex.getKind() != lltok::APSInt)
3193 return TokError("expected signed integer");
3194
3195 auto &S = Lex.getAPSIntVal();
3196 if (S < Result.Min)
3197 return TokError("value for '" + Name + "' too small, limit is " +
3198 Twine(Result.Min));
3199 if (S > Result.Max)
3200 return TokError("value for '" + Name + "' too large, limit is " +
3201 Twine(Result.Max));
3202 Result.assign(S.getExtValue());
3203 assert(Result.Val >= Result.Min && "Expected value in range");
3204 assert(Result.Val <= Result.Max && "Expected value in range");
3205 Lex.Lex();
3206 return false;
3207}
3208
3209template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003210bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3211 switch (Lex.getKind()) {
3212 default:
3213 return TokError("expected 'true' or 'false'");
3214 case lltok::kw_true:
3215 Result.assign(true);
3216 break;
3217 case lltok::kw_false:
3218 Result.assign(false);
3219 break;
3220 }
3221 Lex.Lex();
3222 return false;
3223}
3224
3225template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003226bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003227 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003228 if (!Result.AllowNull)
3229 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003230 Lex.Lex();
3231 Result.assign(nullptr);
3232 return false;
3233 }
3234
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003235 Metadata *MD;
3236 if (ParseMetadata(MD, nullptr))
3237 return true;
3238
3239 Result.assign(MD);
3240 return false;
3241}
3242
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003243template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003244bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3245 Metadata *MD;
3246 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3247 return true;
3248
3249 Result.assign(cast<ConstantAsMetadata>(MD));
3250 return false;
3251}
3252
3253template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003254bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003255 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003256 std::string S;
3257 if (ParseStringConstant(S))
3258 return true;
3259
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003260 if (!Result.AllowEmpty && S.empty())
3261 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3262
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003263 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003264 return false;
3265}
3266
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003267template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003268bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3269 SmallVector<Metadata *, 4> MDs;
3270 if (ParseMDNodeVector(MDs))
3271 return true;
3272
3273 Result.assign(std::move(MDs));
3274 return false;
3275}
3276
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003277} // end namespace llvm
3278
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003279template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003280bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003281 do {
3282 if (Lex.getKind() != lltok::LabelStr)
3283 return TokError("expected field label here");
3284
3285 if (parseField())
3286 return true;
3287 } while (EatIfPresent(lltok::comma));
3288
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003289 return false;
3290}
3291
3292template <class ParserTy>
3293bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3294 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3295 Lex.Lex();
3296
3297 if (ParseToken(lltok::lparen, "expected '(' here"))
3298 return true;
3299 if (Lex.getKind() != lltok::rparen)
3300 if (ParseMDFieldsImplBody(parseField))
3301 return true;
3302
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003303 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003304 return ParseToken(lltok::rparen, "expected ')' here");
3305}
3306
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003307template <class FieldTy>
3308bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3309 if (Result.Seen)
3310 return TokError("field '" + Name + "' cannot be specified more than once");
3311
3312 LocTy Loc = Lex.getLoc();
3313 Lex.Lex();
3314 return ParseMDField(Loc, Name, Result);
3315}
3316
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003317bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3318 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003319
3320#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003321 if (Lex.getStrVal() == #CLASS) \
3322 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003323#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003324
3325 return TokError("expected metadata type");
3326}
3327
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003328#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3329#define NOP_FIELD(NAME, TYPE, INIT)
3330#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3331 if (!NAME.Seen) \
3332 return Error(ClosingLoc, "missing required field '" #NAME "'");
3333#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003334 if (Lex.getStrVal() == #NAME) \
3335 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003336#define PARSE_MD_FIELDS() \
3337 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3338 do { \
3339 LocTy ClosingLoc; \
3340 if (ParseMDFieldsImpl([&]() -> bool { \
3341 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3342 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3343 }, ClosingLoc)) \
3344 return true; \
3345 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3346 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003347#define GET_OR_DISTINCT(CLASS, ARGS) \
3348 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003349
3350/// ParseMDLocationFields:
3351/// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3352bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003353#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003354 OPTIONAL(line, LineField, ); \
3355 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003356 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003357 OPTIONAL(inlinedAt, MDField, );
3358 PARSE_MD_FIELDS();
3359#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003360
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003361 Result = GET_OR_DISTINCT(
3362 MDLocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003363 return false;
3364}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003365
3366/// ParseGenericDebugNode:
3367/// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3368bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3369#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003370 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003371 OPTIONAL(header, MDStringField, ); \
3372 OPTIONAL(operands, MDFieldList, );
3373 PARSE_MD_FIELDS();
3374#undef VISIT_MD_FIELDS
3375
3376 Result = GET_OR_DISTINCT(GenericDebugNode,
3377 (Context, tag.Val, header.Val, operands.Val));
3378 return false;
3379}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003380
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003381/// ParseMDSubrange:
3382/// ::= !MDSubrange(count: 30, lowerBound: 2)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003383bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003384#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003385 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003386 OPTIONAL(lowerBound, MDSignedField, );
3387 PARSE_MD_FIELDS();
3388#undef VISIT_MD_FIELDS
3389
3390 Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3391 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003392}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003393
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003394/// ParseMDEnumerator:
3395/// ::= !MDEnumerator(value: 30, name: "SomeKind")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003396bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003397#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003398 REQUIRED(name, MDStringField, ); \
3399 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003400 PARSE_MD_FIELDS();
3401#undef VISIT_MD_FIELDS
3402
3403 Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3404 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003405}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003406
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003407/// ParseMDBasicType:
3408/// ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003409bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003410#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003411 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003412 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003413 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3414 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003415 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003416 PARSE_MD_FIELDS();
3417#undef VISIT_MD_FIELDS
3418
3419 Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3420 align.Val, encoding.Val));
3421 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003422}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003423
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003424/// ParseMDDerivedType:
3425/// ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3426/// line: 7, scope: !1, baseType: !2, size: 32,
3427/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003428bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003429#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3430 REQUIRED(tag, DwarfTagField, ); \
3431 OPTIONAL(name, MDStringField, ); \
3432 OPTIONAL(file, MDField, ); \
3433 OPTIONAL(line, LineField, ); \
3434 OPTIONAL(scope, MDField, ); \
3435 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003436 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3437 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3438 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003439 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003440 OPTIONAL(extraData, MDField, );
3441 PARSE_MD_FIELDS();
3442#undef VISIT_MD_FIELDS
3443
3444 Result = GET_OR_DISTINCT(MDDerivedType,
3445 (Context, tag.Val, name.Val, file.Val, line.Val,
3446 scope.Val, baseType.Val, size.Val, align.Val,
3447 offset.Val, flags.Val, extraData.Val));
3448 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003449}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003450
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003451bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003452#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3453 REQUIRED(tag, DwarfTagField, ); \
3454 OPTIONAL(name, MDStringField, ); \
3455 OPTIONAL(file, MDField, ); \
3456 OPTIONAL(line, LineField, ); \
3457 OPTIONAL(scope, MDField, ); \
3458 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003459 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3460 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3461 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003462 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003463 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003464 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003465 OPTIONAL(vtableHolder, MDField, ); \
3466 OPTIONAL(templateParams, MDField, ); \
3467 OPTIONAL(identifier, MDStringField, );
3468 PARSE_MD_FIELDS();
3469#undef VISIT_MD_FIELDS
3470
3471 Result = GET_OR_DISTINCT(
3472 MDCompositeType,
3473 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3474 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3475 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3476 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003477}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003478
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003479bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003480#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003481 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003482 REQUIRED(types, MDField, );
3483 PARSE_MD_FIELDS();
3484#undef VISIT_MD_FIELDS
3485
3486 Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3487 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003488}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003489
3490/// ParseMDFileType:
3491/// ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003492bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003493#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3494 REQUIRED(filename, MDStringField, ); \
3495 REQUIRED(directory, MDStringField, );
3496 PARSE_MD_FIELDS();
3497#undef VISIT_MD_FIELDS
3498
3499 Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3500 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003501}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003502
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003503/// ParseMDCompileUnit:
3504/// ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3505/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3506/// splitDebugFilename: "abc.debug", emissionKind: 1,
3507/// enums: !1, retainedTypes: !2, subprograms: !3,
3508/// globals: !4, imports: !5)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003509bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003510#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3511 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003512 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003513 OPTIONAL(producer, MDStringField, ); \
3514 OPTIONAL(isOptimized, MDBoolField, ); \
3515 OPTIONAL(flags, MDStringField, ); \
3516 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3517 OPTIONAL(splitDebugFilename, MDStringField, ); \
3518 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3519 OPTIONAL(enums, MDField, ); \
3520 OPTIONAL(retainedTypes, MDField, ); \
3521 OPTIONAL(subprograms, MDField, ); \
3522 OPTIONAL(globals, MDField, ); \
3523 OPTIONAL(imports, MDField, );
3524 PARSE_MD_FIELDS();
3525#undef VISIT_MD_FIELDS
3526
3527 Result = GET_OR_DISTINCT(MDCompileUnit,
3528 (Context, language.Val, file.Val, producer.Val,
3529 isOptimized.Val, flags.Val, runtimeVersion.Val,
3530 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3531 retainedTypes.Val, subprograms.Val, globals.Val,
3532 imports.Val));
3533 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003534}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003535
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003536/// ParseMDSubprogram:
3537/// ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3538/// file: !1, line: 7, type: !2, isLocal: false,
3539/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003540/// virtuality: DW_VIRTUALTIY_pure_virtual,
3541/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003542/// isOptimized: false, function: void ()* @_Z3foov,
3543/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003544bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003545#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3546 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003547 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003548 OPTIONAL(linkageName, MDStringField, ); \
3549 OPTIONAL(file, MDField, ); \
3550 OPTIONAL(line, LineField, ); \
3551 OPTIONAL(type, MDField, ); \
3552 OPTIONAL(isLocal, MDBoolField, ); \
3553 OPTIONAL(isDefinition, MDBoolField, (true)); \
3554 OPTIONAL(scopeLine, LineField, ); \
3555 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003556 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003557 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003558 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003559 OPTIONAL(isOptimized, MDBoolField, ); \
3560 OPTIONAL(function, MDConstant, ); \
3561 OPTIONAL(templateParams, MDField, ); \
3562 OPTIONAL(declaration, MDField, ); \
3563 OPTIONAL(variables, MDField, );
3564 PARSE_MD_FIELDS();
3565#undef VISIT_MD_FIELDS
3566
3567 Result = GET_OR_DISTINCT(
3568 MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3569 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3570 scopeLine.Val, containingType.Val, virtuality.Val,
3571 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3572 templateParams.Val, declaration.Val, variables.Val));
3573 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003574}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003575
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003576/// ParseMDLexicalBlock:
3577/// ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003578bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003579#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003580 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003581 OPTIONAL(file, MDField, ); \
3582 OPTIONAL(line, LineField, ); \
3583 OPTIONAL(column, ColumnField, );
3584 PARSE_MD_FIELDS();
3585#undef VISIT_MD_FIELDS
3586
3587 Result = GET_OR_DISTINCT(
3588 MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3589 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003590}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003591
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003592/// ParseMDLexicalBlockFile:
3593/// ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003594bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003595#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003596 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003597 OPTIONAL(file, MDField, ); \
3598 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3599 PARSE_MD_FIELDS();
3600#undef VISIT_MD_FIELDS
3601
3602 Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3603 (Context, scope.Val, file.Val, discriminator.Val));
3604 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003605}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003606
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003607/// ParseMDNamespace:
3608/// ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003609bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3611 REQUIRED(scope, MDField, ); \
3612 OPTIONAL(file, MDField, ); \
3613 OPTIONAL(name, MDStringField, ); \
3614 OPTIONAL(line, LineField, );
3615 PARSE_MD_FIELDS();
3616#undef VISIT_MD_FIELDS
3617
3618 Result = GET_OR_DISTINCT(MDNamespace,
3619 (Context, scope.Val, file.Val, name.Val, line.Val));
3620 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003621}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003622
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003623/// ParseMDTemplateTypeParameter:
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003624/// ::= !MDTemplateTypeParameter(name: "Ty", type: !1)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003625bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003626#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003627 OPTIONAL(name, MDStringField, ); \
3628 REQUIRED(type, MDField, );
3629 PARSE_MD_FIELDS();
3630#undef VISIT_MD_FIELDS
3631
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003632 Result =
3633 GET_OR_DISTINCT(MDTemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003634 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003635}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003636
3637/// ParseMDTemplateValueParameter:
3638/// ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003639/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003640bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003641#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003642 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003643 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003644 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003645 REQUIRED(value, MDField, );
3646 PARSE_MD_FIELDS();
3647#undef VISIT_MD_FIELDS
3648
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003649 Result = GET_OR_DISTINCT(MDTemplateValueParameter,
3650 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003651 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003652}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003653
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003654/// ParseMDGlobalVariable:
3655/// ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3656/// file: !1, line: 7, type: !2, isLocal: false,
3657/// isDefinition: true, variable: i32* @foo,
3658/// declaration: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003659bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003660#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003661 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003662 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003663 OPTIONAL(linkageName, MDStringField, ); \
3664 OPTIONAL(file, MDField, ); \
3665 OPTIONAL(line, LineField, ); \
3666 OPTIONAL(type, MDField, ); \
3667 OPTIONAL(isLocal, MDBoolField, ); \
3668 OPTIONAL(isDefinition, MDBoolField, (true)); \
3669 OPTIONAL(variable, MDConstant, ); \
3670 OPTIONAL(declaration, MDField, );
3671 PARSE_MD_FIELDS();
3672#undef VISIT_MD_FIELDS
3673
3674 Result = GET_OR_DISTINCT(MDGlobalVariable,
3675 (Context, scope.Val, name.Val, linkageName.Val,
3676 file.Val, line.Val, type.Val, isLocal.Val,
3677 isDefinition.Val, variable.Val, declaration.Val));
3678 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003679}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003680
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003681/// ParseMDLocalVariable:
3682/// ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003683/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003684bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003685#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3686 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003687 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003688 OPTIONAL(name, MDStringField, ); \
3689 OPTIONAL(file, MDField, ); \
3690 OPTIONAL(line, LineField, ); \
3691 OPTIONAL(type, MDField, ); \
3692 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003693 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003694 PARSE_MD_FIELDS();
3695#undef VISIT_MD_FIELDS
3696
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003697 Result = GET_OR_DISTINCT(MDLocalVariable,
3698 (Context, tag.Val, scope.Val, name.Val, file.Val,
3699 line.Val, type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003700 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003701}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003702
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003703/// ParseMDExpression:
3704/// ::= !MDExpression(0, 7, -1)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003705bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003706 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3707 Lex.Lex();
3708
3709 if (ParseToken(lltok::lparen, "expected '(' here"))
3710 return true;
3711
3712 SmallVector<uint64_t, 8> Elements;
3713 if (Lex.getKind() != lltok::rparen)
3714 do {
3715 if (Lex.getKind() == lltok::DwarfOp) {
3716 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3717 Lex.Lex();
3718 Elements.push_back(Op);
3719 continue;
3720 }
3721 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3722 }
3723
3724 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3725 return TokError("expected unsigned integer");
3726
3727 auto &U = Lex.getAPSIntVal();
3728 if (U.ugt(UINT64_MAX))
3729 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3730 Elements.push_back(U.getZExtValue());
3731 Lex.Lex();
3732 } while (EatIfPresent(lltok::comma));
3733
3734 if (ParseToken(lltok::rparen, "expected ')' here"))
3735 return true;
3736
3737 Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3738 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003739}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003740
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003741/// ParseMDObjCProperty:
3742/// ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3743/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003744bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003745#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003746 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003747 OPTIONAL(file, MDField, ); \
3748 OPTIONAL(line, LineField, ); \
3749 OPTIONAL(setter, MDStringField, ); \
3750 OPTIONAL(getter, MDStringField, ); \
3751 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3752 OPTIONAL(type, MDField, );
3753 PARSE_MD_FIELDS();
3754#undef VISIT_MD_FIELDS
3755
3756 Result = GET_OR_DISTINCT(MDObjCProperty,
3757 (Context, name.Val, file.Val, line.Val, setter.Val,
3758 getter.Val, attributes.Val, type.Val));
3759 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003760}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003761
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003762/// ParseMDImportedEntity:
3763/// ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3764/// line: 7, name: "foo")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003765bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003766#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3767 REQUIRED(tag, DwarfTagField, ); \
3768 REQUIRED(scope, MDField, ); \
3769 OPTIONAL(entity, MDField, ); \
3770 OPTIONAL(line, LineField, ); \
3771 OPTIONAL(name, MDStringField, );
3772 PARSE_MD_FIELDS();
3773#undef VISIT_MD_FIELDS
3774
3775 Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3776 entity.Val, line.Val, name.Val));
3777 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003778}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003779
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003780#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003781#undef NOP_FIELD
3782#undef REQUIRE_FIELD
3783#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003784
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003785/// ParseMetadataAsValue
3786/// ::= metadata i32 %local
3787/// ::= metadata i32 @global
3788/// ::= metadata i32 7
3789/// ::= metadata !0
3790/// ::= metadata !{...}
3791/// ::= metadata !"string"
3792bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3793 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003794 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003795 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003796 return true;
3797
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003798 V = MetadataAsValue::get(Context, MD);
3799 return false;
3800}
3801
3802/// ParseValueAsMetadata
3803/// ::= i32 %local
3804/// ::= i32 @global
3805/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003806bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3807 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003808 Type *Ty;
3809 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003810 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003811 return true;
3812 if (Ty->isMetadataTy())
3813 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3814
3815 Value *V;
3816 if (ParseValue(Ty, V, PFS))
3817 return true;
3818
3819 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003820 return false;
3821}
3822
3823/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003824/// ::= i32 %local
3825/// ::= i32 @global
3826/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003827/// ::= !42
3828/// ::= !{...}
3829/// ::= !"string"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003830/// ::= !MDLocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003831bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003832 if (Lex.getKind() == lltok::MetadataVar) {
3833 MDNode *N;
3834 if (ParseSpecializedMDNode(N))
3835 return true;
3836 MD = N;
3837 return false;
3838 }
3839
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003840 // ValueAsMetadata:
3841 // <type> <value>
3842 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003843 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003844
3845 // '!'.
3846 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3847 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003848
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003849 // MDString:
3850 // ::= '!' STRINGCONSTANT
3851 if (Lex.getKind() == lltok::StringConstant) {
3852 MDString *S;
3853 if (ParseMDString(S))
3854 return true;
3855 MD = S;
3856 return false;
3857 }
3858
Dan Gohman8939ba332010-07-14 18:26:50 +00003859 // MDNode:
3860 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003861 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003862 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003863 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003864 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003865 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003866 return false;
3867}
3868
Victor Hernandez9d75c962010-01-11 22:31:58 +00003869
3870//===----------------------------------------------------------------------===//
3871// Function Parsing.
3872//===----------------------------------------------------------------------===//
3873
Chris Lattner229907c2011-07-18 04:54:35 +00003874bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003875 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003876 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003877 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003878
Chris Lattnerac161bf2009-01-02 07:01:27 +00003879 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003880 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003881 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3882 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003883 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003885 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3886 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003887 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003888 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003889 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003890 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003891 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003892 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3893 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003894 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003895 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003896 return false;
3897 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003898 case ValID::t_GlobalName:
3899 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003900 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003901 case ValID::t_GlobalID:
3902 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003903 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003904 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003905 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003906 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003907 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003908 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003909 return false;
3910 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003911 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003912 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3913 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003914
Dan Gohman518cda42011-12-17 00:04:22 +00003915 // The lexer has no type info, so builds all half, float, and double FP
3916 // constants as double. Fix this here. Long double does not need this.
3917 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003918 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003919 if (Ty->isHalfTy())
3920 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3921 &Ignored);
3922 else if (Ty->isFloatTy())
3923 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3924 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003925 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003926 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003927
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003928 if (V->getType() != Ty)
3929 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003930 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003931
Chris Lattnerac161bf2009-01-02 07:01:27 +00003932 return false;
3933 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003934 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003935 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003936 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003937 return false;
3938 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003939 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003940 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003941 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003942 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003943 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003944 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003945 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003946 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003947 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003948 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003949 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003950 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003951 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003952 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003953 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003954 return false;
3955 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003956 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003957 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003958
Chris Lattnerac161bf2009-01-02 07:01:27 +00003959 V = ID.ConstantVal;
3960 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003961 case ValID::t_ConstantStruct:
3962 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003963 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003964 if (ST->getNumElements() != ID.UIntVal)
3965 return Error(ID.Loc,
3966 "initializer with struct type has wrong # elements");
3967 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3968 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003970 // Verify that the elements are compatible with the structtype.
3971 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3972 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3973 return Error(ID.Loc, "element " + Twine(i) +
3974 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003975
Reid Kleckner2ae03e12015-03-04 18:31:10 +00003976 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3977 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003978 } else
3979 return Error(ID.Loc, "constant expression type mismatch");
3980 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003981 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003982 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003983}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003984
Chris Lattner229907c2011-07-18 04:54:35 +00003985bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003986 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003987 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003988 return ParseValID(ID, PFS) ||
3989 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003990}
3991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003992bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003993 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003994 return ParseType(Ty) ||
3995 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003996}
3997
Chris Lattner3ed871f2009-10-27 19:13:16 +00003998bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3999 PerFunctionState &PFS) {
4000 Value *V;
4001 Loc = Lex.getLoc();
4002 if (ParseTypeAndValue(V, PFS)) return true;
4003 if (!isa<BasicBlock>(V))
4004 return Error(Loc, "expected a basic block");
4005 BB = cast<BasicBlock>(V);
4006 return false;
4007}
4008
4009
Chris Lattnerac161bf2009-01-02 07:01:27 +00004010/// FunctionHeader
4011/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004012/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004013/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00004014bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4015 // Parse the linkage.
4016 LocTy LinkageLoc = Lex.getLoc();
4017 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004018
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004019 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004020 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004021 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004022 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004023 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004024 LocTy RetTypeLoc = Lex.getLoc();
4025 if (ParseOptionalLinkage(Linkage) ||
4026 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004027 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004028 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004029 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004030 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004031 return true;
4032
4033 // Verify that the linkage is ok.
4034 switch ((GlobalValue::LinkageTypes)Linkage) {
4035 case GlobalValue::ExternalLinkage:
4036 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004037 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038 if (isDefine)
4039 return Error(LinkageLoc, "invalid linkage for function definition");
4040 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004041 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004042 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004043 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004044 case GlobalValue::LinkOnceAnyLinkage:
4045 case GlobalValue::LinkOnceODRLinkage:
4046 case GlobalValue::WeakAnyLinkage:
4047 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004048 if (!isDefine)
4049 return Error(LinkageLoc, "invalid linkage for function declaration");
4050 break;
4051 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004052 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 return Error(LinkageLoc, "invalid function linkage type");
4054 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004055
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004056 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4057 return Error(LinkageLoc,
4058 "symbol with local linkage must have default visibility");
4059
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004060 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004061 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004062
Chris Lattnerac161bf2009-01-02 07:01:27 +00004063 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004064
4065 std::string FunctionName;
4066 if (Lex.getKind() == lltok::GlobalVar) {
4067 FunctionName = Lex.getStrVal();
4068 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4069 unsigned NameID = Lex.getUIntVal();
4070
4071 if (NameID != NumberedVals.size())
4072 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004073 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004074 } else {
4075 return TokError("expected function name");
4076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004077
Chris Lattner3822f632009-01-02 08:05:26 +00004078 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004079
Chris Lattner3822f632009-01-02 08:05:26 +00004080 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004081 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004082
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004083 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004084 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004085 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004086 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004087 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004088 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004089 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004090 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004091 bool UnnamedAddr;
4092 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004093 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004094 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004095 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004097 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004098 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4099 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004100 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004101 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004102 (EatIfPresent(lltok::kw_section) &&
4103 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004104 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004105 ParseOptionalAlignment(Alignment) ||
4106 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004107 ParseStringConstant(GC)) ||
4108 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004109 ParseGlobalTypeAndValue(Prefix)) ||
4110 (EatIfPresent(lltok::kw_prologue) &&
4111 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00004112 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004113
Michael Gottesman41748d72013-06-27 00:25:01 +00004114 if (FuncAttrs.contains(Attribute::Builtin))
4115 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004116
Chris Lattnerac161bf2009-01-02 07:01:27 +00004117 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004118 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004119 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004120 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004122
Chris Lattnerac161bf2009-01-02 07:01:27 +00004123 // Okay, if we got here, the function is syntactically valid. Convert types
4124 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004125 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004126 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004127
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004128 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004129 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4130 AttributeSet::ReturnIndex,
4131 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004132
Chris Lattnerac161bf2009-01-02 07:01:27 +00004133 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004134 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004135 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4136 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004137 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4138 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004139 }
4140
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004141 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004142 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4143 AttributeSet::FunctionIndex,
4144 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004145
Bill Wendlinge94d8432012-12-07 23:16:57 +00004146 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004147
Bill Wendling749a43d2012-12-30 13:50:49 +00004148 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004149 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4150
Chris Lattner229907c2011-07-18 04:54:35 +00004151 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004152 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004153 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004154
Craig Topper2617dcc2014-04-15 06:32:26 +00004155 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004156 if (!FunctionName.empty()) {
4157 // If this was a definition of a forward reference, remove the definition
4158 // from the forward reference table and fill in the forward ref.
4159 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4160 ForwardRefVals.find(FunctionName);
4161 if (FRVI != ForwardRefVals.end()) {
4162 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004163 if (!Fn)
4164 return Error(FRVI->second.second, "invalid forward reference to "
4165 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004166 if (Fn->getType() != PFT)
4167 return Error(FRVI->second.second, "invalid forward reference to "
4168 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004169
Chris Lattnerac161bf2009-01-02 07:01:27 +00004170 ForwardRefVals.erase(FRVI);
4171 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004172 // Reject redefinitions.
4173 return Error(NameLoc, "invalid redefinition of function '" +
4174 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004175 } else if (M->getNamedValue(FunctionName)) {
4176 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004177 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004178
Dan Gohman399d6ae2009-08-29 23:37:49 +00004179 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004180 // If this is a definition of a forward referenced function, make sure the
4181 // types agree.
4182 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4183 = ForwardRefValIDs.find(NumberedVals.size());
4184 if (I != ForwardRefValIDs.end()) {
4185 Fn = cast<Function>(I->second.first);
4186 if (Fn->getType() != PFT)
4187 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004188 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004189 ForwardRefValIDs.erase(I);
4190 }
4191 }
4192
Craig Topper2617dcc2014-04-15 06:32:26 +00004193 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004194 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4195 else // Move the forward-reference to the correct spot in the module.
4196 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4197
4198 if (FunctionName.empty())
4199 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004200
Chris Lattnerac161bf2009-01-02 07:01:27 +00004201 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4202 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004203 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004204 Fn->setCallingConv(CC);
4205 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004206 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004207 Fn->setAlignment(Alignment);
4208 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004209 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004211 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004212 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004213 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004214
Chris Lattnerac161bf2009-01-02 07:01:27 +00004215 // Add all of the arguments we parsed to the function.
4216 Function::arg_iterator ArgIt = Fn->arg_begin();
4217 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4218 // If the argument has a name, insert it into the argument symbol table.
4219 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004220
Chris Lattnerac161bf2009-01-02 07:01:27 +00004221 // Set the name, if it conflicted, it will be auto-renamed.
4222 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004223
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004224 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004225 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4226 ArgList[i].Name + "'");
4227 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004228
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004229 if (isDefine)
4230 return false;
4231
Robin Morisset039781e2014-08-29 21:53:01 +00004232 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004233 ValID ID;
4234 if (FunctionName.empty()) {
4235 ID.Kind = ValID::t_GlobalID;
4236 ID.UIntVal = NumberedVals.size() - 1;
4237 } else {
4238 ID.Kind = ValID::t_GlobalName;
4239 ID.StrVal = FunctionName;
4240 }
4241 auto Blocks = ForwardRefBlockAddresses.find(ID);
4242 if (Blocks != ForwardRefBlockAddresses.end())
4243 return Error(Blocks->first.Loc,
4244 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004245 return false;
4246}
4247
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004248bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4249 ValID ID;
4250 if (FunctionNumber == -1) {
4251 ID.Kind = ValID::t_GlobalName;
4252 ID.StrVal = F.getName();
4253 } else {
4254 ID.Kind = ValID::t_GlobalID;
4255 ID.UIntVal = FunctionNumber;
4256 }
4257
4258 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4259 if (Blocks == P.ForwardRefBlockAddresses.end())
4260 return false;
4261
4262 for (const auto &I : Blocks->second) {
4263 const ValID &BBID = I.first;
4264 GlobalValue *GV = I.second;
4265
4266 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4267 "Expected local id or name");
4268 BasicBlock *BB;
4269 if (BBID.Kind == ValID::t_LocalName)
4270 BB = GetBB(BBID.StrVal, BBID.Loc);
4271 else
4272 BB = GetBB(BBID.UIntVal, BBID.Loc);
4273 if (!BB)
4274 return P.Error(BBID.Loc, "referenced value is not a basic block");
4275
4276 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4277 GV->eraseFromParent();
4278 }
4279
4280 P.ForwardRefBlockAddresses.erase(Blocks);
4281 return false;
4282}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004283
4284/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004285/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004286bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004287 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004288 return TokError("expected '{' in function body");
4289 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004290
Chris Lattner3432c622009-10-28 03:39:23 +00004291 int FunctionNumber = -1;
4292 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004293
Chris Lattner3432c622009-10-28 03:39:23 +00004294 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004295
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004296 // Resolve block addresses and allow basic blocks to be forward-declared
4297 // within this function.
4298 if (PFS.resolveForwardRefBlockAddresses())
4299 return true;
4300 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4301
Chris Lattnerbbddd962010-01-09 19:20:07 +00004302 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004303 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004304 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004305
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004306 while (Lex.getKind() != lltok::rbrace &&
4307 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004308 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004309
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004310 while (Lex.getKind() != lltok::rbrace)
4311 if (ParseUseListOrder(&PFS))
4312 return true;
4313
Chris Lattnerac161bf2009-01-02 07:01:27 +00004314 // Eat the }.
4315 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004316
Chris Lattnerac161bf2009-01-02 07:01:27 +00004317 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004318 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004319}
4320
4321/// ParseBasicBlock
4322/// ::= LabelStr? Instruction*
4323bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4324 // If this basic block starts out with a name, remember it.
4325 std::string Name;
4326 LocTy NameLoc = Lex.getLoc();
4327 if (Lex.getKind() == lltok::LabelStr) {
4328 Name = Lex.getStrVal();
4329 Lex.Lex();
4330 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004331
Chris Lattnerac161bf2009-01-02 07:01:27 +00004332 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004333 if (!BB)
4334 return Error(NameLoc,
4335 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004336
Chris Lattnerac161bf2009-01-02 07:01:27 +00004337 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004338
Chris Lattnerac161bf2009-01-02 07:01:27 +00004339 // Parse the instructions in this block until we get a terminator.
4340 Instruction *Inst;
4341 do {
4342 // This instruction may have three possibilities for a name: a) none
4343 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4344 LocTy NameLoc = Lex.getLoc();
4345 int NameID = -1;
4346 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004347
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348 if (Lex.getKind() == lltok::LocalVarID) {
4349 NameID = Lex.getUIntVal();
4350 Lex.Lex();
4351 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4352 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004353 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004354 NameStr = Lex.getStrVal();
4355 Lex.Lex();
4356 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4357 return true;
4358 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004359
Chris Lattner77b89dc2009-12-30 05:23:43 +00004360 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004361 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004362 case InstError: return true;
4363 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004364 BB->getInstList().push_back(Inst);
4365
Chris Lattner77b89dc2009-12-30 05:23:43 +00004366 // With a normal result, we check to see if the instruction is followed by
4367 // a comma and metadata.
4368 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00004369 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004370 return true;
4371 break;
4372 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004373 BB->getInstList().push_back(Inst);
4374
Chris Lattner77b89dc2009-12-30 05:23:43 +00004375 // If the instruction parser ate an extra comma at the end of it, it
4376 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00004377 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004378 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004379 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004380 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004381
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 // Set the name on the instruction.
4383 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4384 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004385
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386 return false;
4387}
4388
4389//===----------------------------------------------------------------------===//
4390// Instruction Parsing.
4391//===----------------------------------------------------------------------===//
4392
4393/// ParseInstruction - Parse one of the many different instructions.
4394///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004395int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4396 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004397 lltok::Kind Token = Lex.getKind();
4398 if (Token == lltok::Eof)
4399 return TokError("found end of file when expecting more instructions");
4400 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004401 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004402 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004403
Chris Lattnerac161bf2009-01-02 07:01:27 +00004404 switch (Token) {
4405 default: return Error(Loc, "expected instruction opcode");
4406 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004407 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4409 case lltok::kw_br: return ParseBr(Inst, PFS);
4410 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004411 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004413 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414 // Binary Operators.
4415 case lltok::kw_add:
4416 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004417 case lltok::kw_mul:
4418 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004419 bool NUW = EatIfPresent(lltok::kw_nuw);
4420 bool NSW = EatIfPresent(lltok::kw_nsw);
4421 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004422
Chris Lattnera676c0f2011-02-07 16:40:21 +00004423 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004424
Chris Lattnera676c0f2011-02-07 16:40:21 +00004425 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4426 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4427 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004428 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004429 case lltok::kw_fadd:
4430 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004431 case lltok::kw_fmul:
4432 case lltok::kw_fdiv:
4433 case lltok::kw_frem: {
4434 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4435 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4436 if (Res != 0)
4437 return Res;
4438 if (FMF.any())
4439 Inst->setFastMathFlags(FMF);
4440 return 0;
4441 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004442
Chris Lattner35315d02011-02-06 21:44:57 +00004443 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004444 case lltok::kw_udiv:
4445 case lltok::kw_lshr:
4446 case lltok::kw_ashr: {
4447 bool Exact = EatIfPresent(lltok::kw_exact);
4448
4449 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4450 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4451 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004452 }
4453
Chris Lattnerac161bf2009-01-02 07:01:27 +00004454 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004455 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004456 case lltok::kw_and:
4457 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004458 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004460 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461 // Casts.
4462 case lltok::kw_trunc:
4463 case lltok::kw_zext:
4464 case lltok::kw_sext:
4465 case lltok::kw_fptrunc:
4466 case lltok::kw_fpext:
4467 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004468 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469 case lltok::kw_uitofp:
4470 case lltok::kw_sitofp:
4471 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004472 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004473 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004474 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004475 // Other.
4476 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004477 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004478 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4479 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4480 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4481 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004482 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004483 // Call.
4484 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4485 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4486 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004488 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004489 case lltok::kw_load: return ParseLoad(Inst, PFS);
4490 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004491 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4492 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004493 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4495 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4496 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4497 }
4498}
4499
4500/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4501bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004502 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004503 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004504 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004505 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4506 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4507 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4508 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4509 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4510 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4511 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4512 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4513 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4514 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4515 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4516 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4517 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4518 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4519 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4520 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4521 }
4522 } else {
4523 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004524 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004525 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4526 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4527 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4528 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4529 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4530 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4531 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4532 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4533 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4534 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4535 }
4536 }
4537 Lex.Lex();
4538 return false;
4539}
4540
4541//===----------------------------------------------------------------------===//
4542// Terminator Instructions.
4543//===----------------------------------------------------------------------===//
4544
4545/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004546/// ::= 'ret' void (',' !dbg, !1)*
4547/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004548bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004549 PerFunctionState &PFS) {
4550 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004551 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004552 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004553
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004554 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004555
Chris Lattnerfdd87902009-10-05 05:54:46 +00004556 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004557 if (!ResType->isVoidTy())
4558 return Error(TypeLoc, "value doesn't match function result type '" +
4559 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004560
Owen Anderson55f1c092009-08-13 21:58:54 +00004561 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004562 return false;
4563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004564
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 Value *RV;
4566 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004567
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004568 if (ResType != RV->getType())
4569 return Error(TypeLoc, "value doesn't match function result type '" +
4570 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004571
Owen Anderson55f1c092009-08-13 21:58:54 +00004572 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004573 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004574}
4575
4576
4577/// ParseBr
4578/// ::= 'br' TypeAndValue
4579/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4580bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4581 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004582 Value *Op0;
4583 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004585
Chris Lattnerac161bf2009-01-02 07:01:27 +00004586 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4587 Inst = BranchInst::Create(BB);
4588 return false;
4589 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004590
Owen Anderson55f1c092009-08-13 21:58:54 +00004591 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004592 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004593
Chris Lattnerac161bf2009-01-02 07:01:27 +00004594 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004595 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004596 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004597 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004598 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004599
Chris Lattner3ed871f2009-10-27 19:13:16 +00004600 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 return false;
4602}
4603
4604/// ParseSwitch
4605/// Instruction
4606/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4607/// JumpTable
4608/// ::= (TypeAndValue ',' TypeAndValue)*
4609bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4610 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004611 Value *Cond;
4612 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004613 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4614 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004615 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004616 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4617 return true;
4618
Duncan Sands19d0b472010-02-16 11:11:14 +00004619 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004620 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004621
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622 // Parse the jump table pairs.
4623 SmallPtrSet<Value*, 32> SeenCases;
4624 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4625 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004626 Value *Constant;
4627 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004628
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4630 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004631 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004633
David Blaikie70573dc2014-11-19 07:49:26 +00004634 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004635 return Error(CondLoc, "duplicate case value in switch");
4636 if (!isa<ConstantInt>(Constant))
4637 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004638
Chris Lattner3ed871f2009-10-27 19:13:16 +00004639 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004640 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004641
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004643
Chris Lattner3ed871f2009-10-27 19:13:16 +00004644 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4646 SI->addCase(Table[i].first, Table[i].second);
4647 Inst = SI;
4648 return false;
4649}
4650
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004651/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004652/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004653/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4654bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004655 LocTy AddrLoc;
4656 Value *Address;
4657 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004658 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4659 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004660 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004661
Duncan Sands19d0b472010-02-16 11:11:14 +00004662 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004663 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004664
Chris Lattner3ed871f2009-10-27 19:13:16 +00004665 // Parse the destination list.
4666 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004667
Chris Lattner3ed871f2009-10-27 19:13:16 +00004668 if (Lex.getKind() != lltok::rsquare) {
4669 BasicBlock *DestBB;
4670 if (ParseTypeAndBasicBlock(DestBB, PFS))
4671 return true;
4672 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004673
Chris Lattner3ed871f2009-10-27 19:13:16 +00004674 while (EatIfPresent(lltok::comma)) {
4675 if (ParseTypeAndBasicBlock(DestBB, PFS))
4676 return true;
4677 DestList.push_back(DestBB);
4678 }
4679 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004680
Chris Lattner3ed871f2009-10-27 19:13:16 +00004681 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4682 return true;
4683
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004684 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004685 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4686 IBI->addDestination(DestList[i]);
4687 Inst = IBI;
4688 return false;
4689}
4690
4691
Chris Lattnerac161bf2009-01-02 07:01:27 +00004692/// ParseInvoke
4693/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4694/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4695bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4696 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004697 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004698 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004699 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004700 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004701 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004702 LocTy RetTypeLoc;
4703 ValID CalleeID;
4704 SmallVector<ParamInfo, 16> ArgList;
4705
Chris Lattner3ed871f2009-10-27 19:13:16 +00004706 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004707 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004708 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004709 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004710 ParseValID(CalleeID) ||
4711 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004712 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4713 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004714 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004715 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004716 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004717 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004719
Chris Lattnerac161bf2009-01-02 07:01:27 +00004720 // If RetType is a non-function pointer type, then this is the short syntax
4721 // for the call, which means that RetType is just the return type. Infer the
4722 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004723 PointerType *PFTy = nullptr;
4724 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004725 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4726 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4727 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004728 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004729 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4730 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004731
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 if (!FunctionType::isValidReturnType(RetType))
4733 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004734
Owen Anderson4056ca92009-07-29 22:17:13 +00004735 Ty = FunctionType::get(RetType, ParamTypes, false);
4736 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004738
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 // Look up the callee.
4740 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004741 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004742
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004743 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004744 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004745 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004746 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4747 AttributeSet::ReturnIndex,
4748 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004749
Chris Lattnerac161bf2009-01-02 07:01:27 +00004750 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004751
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752 // Loop through FunctionType's arguments and ensure they are specified
4753 // correctly. Also, gather any parameter attributes.
4754 FunctionType::param_iterator I = Ty->param_begin();
4755 FunctionType::param_iterator E = Ty->param_end();
4756 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004757 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004758 if (I != E) {
4759 ExpectedTy = *I++;
4760 } else if (!Ty->isVarArg()) {
4761 return Error(ArgList[i].Loc, "too many arguments specified");
4762 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004763
Chris Lattnerac161bf2009-01-02 07:01:27 +00004764 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4765 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004766 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004768 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4769 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004770 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4771 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004773
Chris Lattnerac161bf2009-01-02 07:01:27 +00004774 if (I != E)
4775 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004776
David Majnemer8d22abd2015-02-23 00:01:32 +00004777 if (FnAttrs.hasAttributes()) {
4778 if (FnAttrs.hasAlignmentAttr())
4779 return Error(CallLoc, "invoke instructions may not have an alignment");
4780
Bill Wendlingf5075a42013-01-27 02:24:02 +00004781 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4782 AttributeSet::FunctionIndex,
4783 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004784 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004785
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004786 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004787 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004788
Jay Foad5bd375a2011-07-15 08:37:34 +00004789 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 II->setCallingConv(CC);
4791 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004792 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004793 Inst = II;
4794 return false;
4795}
4796
Bill Wendlingf891bf82011-07-31 06:30:59 +00004797/// ParseResume
4798/// ::= 'resume' TypeAndValue
4799bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4800 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004801 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4802 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803
Bill Wendlingf891bf82011-07-31 06:30:59 +00004804 ResumeInst *RI = ResumeInst::Create(Exn);
4805 Inst = RI;
4806 return false;
4807}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808
4809//===----------------------------------------------------------------------===//
4810// Binary Operators.
4811//===----------------------------------------------------------------------===//
4812
4813/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004814/// ::= ArithmeticOps TypeAndValue ',' Value
4815///
4816/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4817/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004818bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004819 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004820 LocTy Loc; Value *LHS, *RHS;
4821 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4822 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4823 ParseValue(LHS->getType(), RHS, PFS))
4824 return true;
4825
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004826 bool Valid;
4827 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004828 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004829 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004830 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4831 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004832 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004833 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4834 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004835 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004836
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004837 if (!Valid)
4838 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004839
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4841 return false;
4842}
4843
4844/// ParseLogical
4845/// ::= ArithmeticOps TypeAndValue ',' Value {
4846bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4847 unsigned Opc) {
4848 LocTy Loc; Value *LHS, *RHS;
4849 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4850 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4851 ParseValue(LHS->getType(), RHS, PFS))
4852 return true;
4853
Duncan Sands9dff9be2010-02-15 16:12:20 +00004854 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004855 return Error(Loc,"instruction requires integer or integer vector operands");
4856
4857 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4858 return false;
4859}
4860
4861
4862/// ParseCompare
4863/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4864/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004865bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4866 unsigned Opc) {
4867 // Parse the integer/fp comparison predicate.
4868 LocTy Loc;
4869 unsigned Pred;
4870 Value *LHS, *RHS;
4871 if (ParseCmpPredicate(Pred, Opc) ||
4872 ParseTypeAndValue(LHS, Loc, PFS) ||
4873 ParseToken(lltok::comma, "expected ',' after compare value") ||
4874 ParseValue(LHS->getType(), RHS, PFS))
4875 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004876
Chris Lattnerac161bf2009-01-02 07:01:27 +00004877 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004878 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004880 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004881 } else {
4882 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004883 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004884 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004886 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004887 }
4888 return false;
4889}
4890
4891//===----------------------------------------------------------------------===//
4892// Other Instructions.
4893//===----------------------------------------------------------------------===//
4894
4895
4896/// ParseCast
4897/// ::= CastOpc TypeAndValue 'to' Type
4898bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4899 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004900 LocTy Loc;
4901 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004902 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004903 if (ParseTypeAndValue(Op, Loc, PFS) ||
4904 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4905 ParseType(DestTy))
4906 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004907
Chris Lattner89d856e2009-03-01 00:53:13 +00004908 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4909 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004910 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004911 getTypeString(Op->getType()) + "' to '" +
4912 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004913 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004914 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4915 return false;
4916}
4917
4918/// ParseSelect
4919/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4920bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4921 LocTy Loc;
4922 Value *Op0, *Op1, *Op2;
4923 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4924 ParseToken(lltok::comma, "expected ',' after select condition") ||
4925 ParseTypeAndValue(Op1, PFS) ||
4926 ParseToken(lltok::comma, "expected ',' after select value") ||
4927 ParseTypeAndValue(Op2, PFS))
4928 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004929
Chris Lattnerac161bf2009-01-02 07:01:27 +00004930 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4931 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004932
Chris Lattnerac161bf2009-01-02 07:01:27 +00004933 Inst = SelectInst::Create(Op0, Op1, Op2);
4934 return false;
4935}
4936
Chris Lattnerb55ab542009-01-05 08:18:44 +00004937/// ParseVA_Arg
4938/// ::= 'va_arg' TypeAndValue ',' Type
4939bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004940 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004941 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004942 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 if (ParseTypeAndValue(Op, PFS) ||
4944 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004945 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004947
Chris Lattnerb55ab542009-01-05 08:18:44 +00004948 if (!EltTy->isFirstClassType())
4949 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950
4951 Inst = new VAArgInst(Op, EltTy);
4952 return false;
4953}
4954
4955/// ParseExtractElement
4956/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4957bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4958 LocTy Loc;
4959 Value *Op0, *Op1;
4960 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4961 ParseToken(lltok::comma, "expected ',' after extract value") ||
4962 ParseTypeAndValue(Op1, PFS))
4963 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004964
Chris Lattnerac161bf2009-01-02 07:01:27 +00004965 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4966 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004967
Eric Christopherc9742252009-07-25 02:28:41 +00004968 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004969 return false;
4970}
4971
4972/// ParseInsertElement
4973/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4974bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4975 LocTy Loc;
4976 Value *Op0, *Op1, *Op2;
4977 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4978 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4979 ParseTypeAndValue(Op1, PFS) ||
4980 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4981 ParseTypeAndValue(Op2, PFS))
4982 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004983
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004985 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004986
Chris Lattnerac161bf2009-01-02 07:01:27 +00004987 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4988 return false;
4989}
4990
4991/// ParseShuffleVector
4992/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4993bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4994 LocTy Loc;
4995 Value *Op0, *Op1, *Op2;
4996 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4997 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4998 ParseTypeAndValue(Op1, PFS) ||
4999 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5000 ParseTypeAndValue(Op2, PFS))
5001 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005002
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005004 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5007 return false;
5008}
5009
5010/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005011/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005012int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005013 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005016 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005017 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5018 ParseValue(Ty, Op0, PFS) ||
5019 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005020 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5022 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005023
Chris Lattnerf4f03422009-12-30 05:27:33 +00005024 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005025 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5026 while (1) {
5027 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005028
Chris Lattner3822f632009-01-02 08:05:26 +00005029 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005030 break;
5031
Chris Lattnerf4f03422009-12-30 05:27:33 +00005032 if (Lex.getKind() == lltok::MetadataVar) {
5033 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005034 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005035 }
Devang Patel8f842d32009-10-16 18:45:49 +00005036
Chris Lattner3822f632009-01-02 08:05:26 +00005037 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005038 ParseValue(Ty, Op0, PFS) ||
5039 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005040 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005041 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5042 return true;
5043 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005044
Chris Lattnerac161bf2009-01-02 07:01:27 +00005045 if (!Ty->isFirstClassType())
5046 return Error(TypeLoc, "phi node must have first class type");
5047
Jay Foad52131342011-03-30 11:28:46 +00005048 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005049 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5050 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5051 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005052 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005053}
5054
Bill Wendlingfae14752011-08-12 20:24:12 +00005055/// ParseLandingPad
5056/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5057/// Clause
5058/// ::= 'catch' TypeAndValue
5059/// ::= 'filter'
5060/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5061bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005062 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005063 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005064
5065 if (ParseType(Ty, TyLoc) ||
5066 ParseToken(lltok::kw_personality, "expected 'personality'") ||
5067 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5068 return true;
5069
Owen Andersonf8f259d2015-03-09 07:13:42 +00005070 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005071 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5072
5073 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5074 LandingPadInst::ClauseType CT;
5075 if (EatIfPresent(lltok::kw_catch))
5076 CT = LandingPadInst::Catch;
5077 else if (EatIfPresent(lltok::kw_filter))
5078 CT = LandingPadInst::Filter;
5079 else
5080 return TokError("expected 'catch' or 'filter' clause type");
5081
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005082 Value *V;
5083 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005084 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005085 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005086
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005087 // A 'catch' type expects a non-array constant. A filter clause expects an
5088 // array constant.
5089 if (CT == LandingPadInst::Catch) {
5090 if (isa<ArrayType>(V->getType()))
5091 Error(VLoc, "'catch' clause has an invalid type");
5092 } else {
5093 if (!isa<ArrayType>(V->getType()))
5094 Error(VLoc, "'filter' clause has an invalid type");
5095 }
5096
Owen Andersonf8f259d2015-03-09 07:13:42 +00005097 Constant *CV = dyn_cast<Constant>(V);
5098 if (!CV)
5099 return Error(VLoc, "clause argument must be a constant");
5100 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005101 }
5102
Owen Andersonf8f259d2015-03-09 07:13:42 +00005103 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005104 return false;
5105}
5106
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005108/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5109/// ParameterList OptionalAttrs
5110/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5111/// ParameterList OptionalAttrs
5112/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113/// ParameterList OptionalAttrs
5114bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005115 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005116 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005117 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005118 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005119 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005120 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005121 LocTy RetTypeLoc;
5122 ValID CalleeID;
5123 SmallVector<ParamInfo, 16> ArgList;
5124 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005125
Reid Kleckner5772b772014-04-24 20:14:34 +00005126 if ((TCK != CallInst::TCK_None &&
5127 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005128 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005129 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005130 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005131 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005132 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5133 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005134 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005135 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005136 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005137
Chris Lattnerac161bf2009-01-02 07:01:27 +00005138 // If RetType is a non-function pointer type, then this is the short syntax
5139 // for the call, which means that RetType is just the return type. Infer the
5140 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00005141 PointerType *PFTy = nullptr;
5142 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005143 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
5144 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
5145 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005146 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005147 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5148 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005149
Chris Lattnerac161bf2009-01-02 07:01:27 +00005150 if (!FunctionType::isValidReturnType(RetType))
5151 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005152
Owen Anderson4056ca92009-07-29 22:17:13 +00005153 Ty = FunctionType::get(RetType, ParamTypes, false);
5154 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005156
Chris Lattnerac161bf2009-01-02 07:01:27 +00005157 // Look up the callee.
5158 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00005159 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005160
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005161 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005162 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005163 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005164 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5165 AttributeSet::ReturnIndex,
5166 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005167
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005169
Chris Lattnerac161bf2009-01-02 07:01:27 +00005170 // Loop through FunctionType's arguments and ensure they are specified
5171 // correctly. Also, gather any parameter attributes.
5172 FunctionType::param_iterator I = Ty->param_begin();
5173 FunctionType::param_iterator E = Ty->param_end();
5174 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005175 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 if (I != E) {
5177 ExpectedTy = *I++;
5178 } else if (!Ty->isVarArg()) {
5179 return Error(ArgList[i].Loc, "too many arguments specified");
5180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005181
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5183 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005184 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005185 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005186 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5187 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005188 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5189 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005191
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 if (I != E)
5193 return Error(CallLoc, "not enough parameters specified for call");
5194
David Majnemer8d22abd2015-02-23 00:01:32 +00005195 if (FnAttrs.hasAttributes()) {
5196 if (FnAttrs.hasAlignmentAttr())
5197 return Error(CallLoc, "call instructions may not have an alignment");
5198
Bill Wendlingf5075a42013-01-27 02:24:02 +00005199 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5200 AttributeSet::FunctionIndex,
5201 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005202 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005203
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005204 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005205 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Jay Foad5bd375a2011-07-15 08:37:34 +00005207 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005208 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 CI->setCallingConv(CC);
5210 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005211 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005212 Inst = CI;
5213 return false;
5214}
5215
5216//===----------------------------------------------------------------------===//
5217// Memory Instructions.
5218//===----------------------------------------------------------------------===//
5219
5220/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005221/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005222int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005223 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005224 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005225 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005226 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005227
5228 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5229
David Majnemera3b0eb22015-02-16 08:38:03 +00005230 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005231
David Majnemera3b0eb22015-02-16 08:38:03 +00005232 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5233 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005234
Chris Lattnerb2f39502009-12-30 05:44:30 +00005235 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005236 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005237 if (Lex.getKind() == lltok::kw_align) {
5238 if (ParseOptionalAlignment(Alignment)) return true;
5239 } else if (Lex.getKind() == lltok::MetadataVar) {
5240 AteExtraComma = true;
5241 } else {
5242 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5243 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5244 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 }
5246 }
5247
Dan Gohman2140a742010-05-28 01:14:11 +00005248 if (Size && !Size->getType()->isIntegerTy())
5249 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005250
Reid Kleckner436c42e2014-01-17 23:58:17 +00005251 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5252 AI->setUsedWithInAlloca(IsInAlloca);
5253 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005254 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005255}
5256
5257/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005258/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005259/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005260/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005261int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005262 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005263 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005264 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005265 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005266 AtomicOrdering Ordering = NotAtomic;
5267 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005268
5269 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005270 isAtomic = true;
5271 Lex.Lex();
5272 }
5273
Chris Lattnerbc639292011-11-27 06:56:53 +00005274 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005275 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005276 isVolatile = true;
5277 Lex.Lex();
5278 }
5279
David Blaikie15d9a4c2015-04-06 20:59:48 +00005280 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005281 LocTy ExplicitTypeLoc = Lex.getLoc();
5282 if (ParseType(Ty) ||
5283 ParseToken(lltok::comma, "expected comma after load's type") ||
5284 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005285 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005286 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5287 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005288
David Blaikie15d9a4c2015-04-06 20:59:48 +00005289 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005291 if (isAtomic && !Alignment)
5292 return Error(Loc, "atomic load must have explicit non-zero alignment");
5293 if (Ordering == Release || Ordering == AcquireRelease)
5294 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005295
David Blaikiea79ac142015-02-27 21:17:42 +00005296 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5297 return Error(ExplicitTypeLoc,
5298 "explicit pointee type doesn't match operand's pointee type");
5299
David Blaikie15d9a4c2015-04-06 20:59:48 +00005300 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005301 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005302}
5303
5304/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005305
5306/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5307/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005308/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005309int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005310 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005311 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005312 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005313 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005314 AtomicOrdering Ordering = NotAtomic;
5315 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005316
5317 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005318 isAtomic = true;
5319 Lex.Lex();
5320 }
5321
Chris Lattnerbc639292011-11-27 06:56:53 +00005322 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005323 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005324 isVolatile = true;
5325 Lex.Lex();
5326 }
5327
Chris Lattnerac161bf2009-01-02 07:01:27 +00005328 if (ParseTypeAndValue(Val, Loc, PFS) ||
5329 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005330 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005331 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005332 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005333 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005334
Duncan Sands19d0b472010-02-16 11:11:14 +00005335 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005336 return Error(PtrLoc, "store operand must be a pointer");
5337 if (!Val->getType()->isFirstClassType())
5338 return Error(Loc, "store operand must be a first class value");
5339 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5340 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005341 if (isAtomic && !Alignment)
5342 return Error(Loc, "atomic store must have explicit non-zero alignment");
5343 if (Ordering == Acquire || Ordering == AcquireRelease)
5344 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005345
Eli Friedman59b66882011-08-09 23:02:53 +00005346 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005347 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348}
5349
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005350/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005351/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5352/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005353int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005354 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5355 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005356 AtomicOrdering SuccessOrdering = NotAtomic;
5357 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005358 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005359 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005360 bool isWeak = false;
5361
5362 if (EatIfPresent(lltok::kw_weak))
5363 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005364
5365 if (EatIfPresent(lltok::kw_volatile))
5366 isVolatile = true;
5367
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005368 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5369 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5370 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5371 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5372 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005373 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5374 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005375 return true;
5376
Tim Northovere94a5182014-03-11 10:48:52 +00005377 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005378 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005379 if (SuccessOrdering < FailureOrdering)
5380 return TokError("cmpxchg must be at least as ordered on success as failure");
5381 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5382 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005383 if (!Ptr->getType()->isPointerTy())
5384 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5385 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5386 return Error(CmpLoc, "compare value and pointer type do not match");
5387 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5388 return Error(NewLoc, "new value and pointer type do not match");
5389 if (!New->getType()->isIntegerTy())
5390 return Error(NewLoc, "cmpxchg operand must be an integer");
5391 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5392 if (Size < 8 || (Size & (Size - 1)))
5393 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5394 " integer");
5395
Tim Northover420a2162014-06-13 14:24:07 +00005396 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5397 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005398 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005399 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005400 Inst = CXI;
5401 return AteExtraComma ? InstExtraComma : InstNormal;
5402}
5403
5404/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005405/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5406/// 'singlethread'? AtomicOrdering
5407int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005408 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5409 bool AteExtraComma = false;
5410 AtomicOrdering Ordering = NotAtomic;
5411 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005412 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005413 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005414
5415 if (EatIfPresent(lltok::kw_volatile))
5416 isVolatile = true;
5417
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005418 switch (Lex.getKind()) {
5419 default: return TokError("expected binary operation in atomicrmw");
5420 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5421 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5422 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5423 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5424 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5425 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5426 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5427 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5428 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5429 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5430 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5431 }
5432 Lex.Lex(); // Eat the operation.
5433
5434 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5435 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5436 ParseTypeAndValue(Val, ValLoc, PFS) ||
5437 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5438 return true;
5439
5440 if (Ordering == Unordered)
5441 return TokError("atomicrmw cannot be unordered");
5442 if (!Ptr->getType()->isPointerTy())
5443 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5444 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5445 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5446 if (!Val->getType()->isIntegerTy())
5447 return Error(ValLoc, "atomicrmw operand must be an integer");
5448 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5449 if (Size < 8 || (Size & (Size - 1)))
5450 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5451 " integer");
5452
5453 AtomicRMWInst *RMWI =
5454 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5455 RMWI->setVolatile(isVolatile);
5456 Inst = RMWI;
5457 return AteExtraComma ? InstExtraComma : InstNormal;
5458}
5459
Eli Friedmanfee02c62011-07-25 23:16:38 +00005460/// ParseFence
5461/// ::= 'fence' 'singlethread'? AtomicOrdering
5462int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5463 AtomicOrdering Ordering = NotAtomic;
5464 SynchronizationScope Scope = CrossThread;
5465 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5466 return true;
5467
5468 if (Ordering == Unordered)
5469 return TokError("fence cannot be unordered");
5470 if (Ordering == Monotonic)
5471 return TokError("fence cannot be monotonic");
5472
5473 Inst = new FenceInst(Context, Ordering, Scope);
5474 return InstNormal;
5475}
5476
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005478/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005479int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005480 Value *Ptr = nullptr;
5481 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005482 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005483
Dan Gohman16cbbe42009-07-29 15:58:36 +00005484 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005485
David Blaikie79e6c742015-02-27 19:29:02 +00005486 Type *Ty = nullptr;
5487 LocTy ExplicitTypeLoc = Lex.getLoc();
5488 if (ParseType(Ty) ||
5489 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5490 ParseTypeAndValue(Ptr, Loc, PFS))
5491 return true;
5492
Eli Benderskyd9806682013-04-22 17:03:42 +00005493 Type *BaseType = Ptr->getType();
5494 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5495 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005496 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005497
David Blaikie8d757942015-03-09 23:08:44 +00005498 if (Ty != BasePointerType->getElementType())
5499 return Error(ExplicitTypeLoc,
5500 "explicit pointee type doesn't match operand's pointee type");
5501
Chris Lattnerac161bf2009-01-02 07:01:27 +00005502 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005503 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005504 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005505 if (Lex.getKind() == lltok::MetadataVar) {
5506 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005507 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005508 }
Chris Lattner3822f632009-01-02 08:05:26 +00005509 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005510 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005511 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00005512 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5513 return Error(EltLoc, "getelementptr index type missmatch");
5514 if (Val->getType()->isVectorTy()) {
5515 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5516 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5517 if (ValNumEl != PtrNumEl)
5518 return Error(EltLoc,
5519 "getelementptr vector index has a wrong number of elements");
5520 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005521 Indices.push_back(Val);
5522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005523
Owen Andersone90f9922015-03-10 06:34:57 +00005524 SmallPtrSet<const Type*, 4> Visited;
5525 if (!Indices.empty() &&
5526 !BasePointerType->getElementType()->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005527 return Error(Loc, "base element of getelementptr must be sized");
5528
David Blaikied288fb82015-03-30 21:41:43 +00005529 if (!GetElementPtrInst::getIndexedType(
5530 cast<PointerType>(BaseType->getScalarType())->getElementType(),
5531 Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005532 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005533 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005534 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005535 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005536 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005537}
5538
5539/// ParseExtractValue
5540/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005541int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005542 Value *Val; LocTy Loc;
5543 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005544 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005545 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005546 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547 return true;
5548
Chris Lattner392be582010-02-12 20:49:41 +00005549 if (!Val->getType()->isAggregateType())
5550 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005551
Jay Foad57aa6362011-07-13 10:26:04 +00005552 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005554 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005555 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005556}
5557
5558/// ParseInsertValue
5559/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005560int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005561 Value *Val0, *Val1; LocTy Loc0, Loc1;
5562 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005563 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005564 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5565 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5566 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005567 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005568 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005569
Chris Lattner392be582010-02-12 20:49:41 +00005570 if (!Val0->getType()->isAggregateType())
5571 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005572
David Majnemer30074532015-02-11 07:43:58 +00005573 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5574 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005575 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005576 if (IndexedType != Val1->getType())
5577 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5578 getTypeString(Val1->getType()) + "' instead of '" +
5579 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005580 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005581 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582}
Nick Lewycky49f89192009-04-04 07:22:01 +00005583
5584//===----------------------------------------------------------------------===//
5585// Embedded metadata.
5586//===----------------------------------------------------------------------===//
5587
5588/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005589/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005590/// Element
5591/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005592bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005593 if (ParseToken(lltok::lbrace, "expected '{' here"))
5594 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005595
Dan Gohman1e0213a2010-07-13 19:33:27 +00005596 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005597 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005598 return false;
5599
Nick Lewycky49f89192009-04-04 07:22:01 +00005600 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005601 // Null is a special case since it is typeless.
5602 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005603 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005604 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005605 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005606
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005607 Metadata *MD;
5608 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005609 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005610 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005611 } while (EatIfPresent(lltok::comma));
5612
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005613 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005614}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005615
5616//===----------------------------------------------------------------------===//
5617// Use-list order directives.
5618//===----------------------------------------------------------------------===//
5619bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5620 SMLoc Loc) {
5621 if (V->use_empty())
5622 return Error(Loc, "value has no uses");
5623
5624 unsigned NumUses = 0;
5625 SmallDenseMap<const Use *, unsigned, 16> Order;
5626 for (const Use &U : V->uses()) {
5627 if (++NumUses > Indexes.size())
5628 break;
5629 Order[&U] = Indexes[NumUses - 1];
5630 }
5631 if (NumUses < 2)
5632 return Error(Loc, "value only has one use");
5633 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5634 return Error(Loc, "wrong number of indexes, expected " +
5635 Twine(std::distance(V->use_begin(), V->use_end())));
5636
5637 V->sortUseList([&](const Use &L, const Use &R) {
5638 return Order.lookup(&L) < Order.lookup(&R);
5639 });
5640 return false;
5641}
5642
5643/// ParseUseListOrderIndexes
5644/// ::= '{' uint32 (',' uint32)+ '}'
5645bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5646 SMLoc Loc = Lex.getLoc();
5647 if (ParseToken(lltok::lbrace, "expected '{' here"))
5648 return true;
5649 if (Lex.getKind() == lltok::rbrace)
5650 return Lex.Error("expected non-empty list of uselistorder indexes");
5651
5652 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5653 // indexes should be distinct numbers in the range [0, size-1], and should
5654 // not be in order.
5655 unsigned Offset = 0;
5656 unsigned Max = 0;
5657 bool IsOrdered = true;
5658 assert(Indexes.empty() && "Expected empty order vector");
5659 do {
5660 unsigned Index;
5661 if (ParseUInt32(Index))
5662 return true;
5663
5664 // Update consistency checks.
5665 Offset += Index - Indexes.size();
5666 Max = std::max(Max, Index);
5667 IsOrdered &= Index == Indexes.size();
5668
5669 Indexes.push_back(Index);
5670 } while (EatIfPresent(lltok::comma));
5671
5672 if (ParseToken(lltok::rbrace, "expected '}' here"))
5673 return true;
5674
5675 if (Indexes.size() < 2)
5676 return Error(Loc, "expected >= 2 uselistorder indexes");
5677 if (Offset != 0 || Max >= Indexes.size())
5678 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5679 if (IsOrdered)
5680 return Error(Loc, "expected uselistorder indexes to change the order");
5681
5682 return false;
5683}
5684
5685/// ParseUseListOrder
5686/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5687bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5688 SMLoc Loc = Lex.getLoc();
5689 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5690 return true;
5691
5692 Value *V;
5693 SmallVector<unsigned, 16> Indexes;
5694 if (ParseTypeAndValue(V, PFS) ||
5695 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5696 ParseUseListOrderIndexes(Indexes))
5697 return true;
5698
5699 return sortUseListOrder(V, Indexes, Loc);
5700}
5701
5702/// ParseUseListOrderBB
5703/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5704bool LLParser::ParseUseListOrderBB() {
5705 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5706 SMLoc Loc = Lex.getLoc();
5707 Lex.Lex();
5708
5709 ValID Fn, Label;
5710 SmallVector<unsigned, 16> Indexes;
5711 if (ParseValID(Fn) ||
5712 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5713 ParseValID(Label) ||
5714 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5715 ParseUseListOrderIndexes(Indexes))
5716 return true;
5717
5718 // Check the function.
5719 GlobalValue *GV;
5720 if (Fn.Kind == ValID::t_GlobalName)
5721 GV = M->getNamedValue(Fn.StrVal);
5722 else if (Fn.Kind == ValID::t_GlobalID)
5723 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5724 else
5725 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5726 if (!GV)
5727 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5728 auto *F = dyn_cast<Function>(GV);
5729 if (!F)
5730 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5731 if (F->isDeclaration())
5732 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5733
5734 // Check the basic block.
5735 if (Label.Kind == ValID::t_LocalID)
5736 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5737 if (Label.Kind != ValID::t_LocalName)
5738 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5739 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5740 if (!V)
5741 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5742 if (!isa<BasicBlock>(V))
5743 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5744
5745 return sortUseListOrder(V, Indexes, Loc);
5746}