blob: 3c561673bbd9bc6eafa8de361745c4d954327625 [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"
David Blaikie1b770232015-08-01 05:10:40 +000016#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000017#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000018#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000021#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000030#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000032#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000033#include "llvm/Support/raw_ostream.h"
34using namespace llvm;
35
Chris Lattner229907c2011-07-18 04:54:35 +000036static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000037 std::string Result;
38 raw_string_ostream Tmp(Result);
39 Tmp << *T;
40 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000041}
42
Chris Lattner3822f632009-01-02 08:05:26 +000043/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000044bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000045 // Prime the lexer.
46 Lex.Lex();
47
Chris Lattnerad6f3352009-01-04 20:44:11 +000048 return ParseTopLevelEntities() ||
49 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000050}
51
Alex Lorenzd2255952015-07-17 22:07:03 +000052bool LLParser::parseStandaloneConstantValue(Constant *&C) {
53 Lex.Lex();
54
55 Type *Ty = nullptr;
56 if (ParseType(Ty) || parseConstantValue(Ty, C))
57 return true;
58 if (Lex.getKind() != lltok::Eof)
59 return Error(Lex.getLoc(), "expected end of string");
60 return false;
61}
62
Chris Lattnerac161bf2009-01-02 07:01:27 +000063/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64/// module.
65bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000066 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
67 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
68
Bill Wendlingb32b0412013-02-08 06:32:06 +000069 // Handle any function attribute group forward references.
70 for (std::map<Value*, std::vector<unsigned> >::iterator
71 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
72 I != E; ++I) {
73 Value *V = I->first;
74 std::vector<unsigned> &Vec = I->second;
75 AttrBuilder B;
76
77 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
78 VI != VE; ++VI)
79 B.merge(NumberedAttrBuilders[*VI]);
80
81 if (Function *Fn = dyn_cast<Function>(V)) {
82 AttributeSet AS = Fn->getAttributes();
83 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
84 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
85 AS.getFnAttributes());
86
87 FnAttrs.merge(B);
88
89 // If the alignment was parsed as an attribute, move to the alignment
90 // field.
91 if (FnAttrs.hasAlignmentAttr()) {
92 Fn->setAlignment(FnAttrs.getAlignment());
93 FnAttrs.removeAttribute(Attribute::Alignment);
94 }
95
96 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
97 AttributeSet::get(Context,
98 AttributeSet::FunctionIndex,
99 FnAttrs));
100 Fn->setAttributes(AS);
101 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
102 AttributeSet AS = CI->getAttributes();
103 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
104 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
105 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000106 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000107 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
108 AttributeSet::get(Context,
109 AttributeSet::FunctionIndex,
110 FnAttrs));
111 CI->setAttributes(AS);
112 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
113 AttributeSet AS = II->getAttributes();
114 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
115 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
116 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000117 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000118 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
119 AttributeSet::get(Context,
120 AttributeSet::FunctionIndex,
121 FnAttrs));
122 II->setAttributes(AS);
123 } else {
124 llvm_unreachable("invalid object with forward attribute group reference");
125 }
126 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000127
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000128 // If there are entries in ForwardRefBlockAddresses at this point, the
129 // function was never defined.
130 if (!ForwardRefBlockAddresses.empty())
131 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
132 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000133
David Majnemer19b51052015-02-11 07:43:56 +0000134 for (const auto &NT : NumberedTypes)
135 if (NT.second.second.isValid())
136 return Error(NT.second.second,
137 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000138
139 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
140 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
141 if (I->second.second.isValid())
142 return Error(I->second.second,
143 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000144
David Majnemerdad0a642014-06-27 18:19:56 +0000145 if (!ForwardRefComdats.empty())
146 return Error(ForwardRefComdats.begin()->second,
147 "use of undefined comdat '$" +
148 ForwardRefComdats.begin()->first + "'");
149
Chris Lattnerac161bf2009-01-02 07:01:27 +0000150 if (!ForwardRefVals.empty())
151 return Error(ForwardRefVals.begin()->second.second,
152 "use of undefined value '@" + ForwardRefVals.begin()->first +
153 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000154
Chris Lattnerac161bf2009-01-02 07:01:27 +0000155 if (!ForwardRefValIDs.empty())
156 return Error(ForwardRefValIDs.begin()->second.second,
157 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000158 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000159
Devang Pateld2541152009-07-08 19:23:54 +0000160 if (!ForwardRefMDNodes.empty())
161 return Error(ForwardRefMDNodes.begin()->second.second,
162 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000163 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000164
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000165 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000166 for (auto &N : NumberedMetadata) {
167 if (N.second && !N.second->isResolved())
168 N.second->resolveCycles();
169 }
Devang Pateld2541152009-07-08 19:23:54 +0000170
Chris Lattnerac161bf2009-01-02 07:01:27 +0000171 // Look for intrinsic functions and CallInst that need to be upgraded
172 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
173 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000174
Manman Ren8b4306c2013-12-02 21:29:56 +0000175 UpgradeDebugInfo(*M);
176
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000177 if (!Slots)
178 return false;
179 // Initialize the slot mapping.
180 // Because by this point we've parsed and validated everything, we can "steal"
181 // the mapping from LLParser as it doesn't need it anymore.
182 Slots->GlobalValues = std::move(NumberedVals);
183 Slots->MetadataNodes = std::move(NumberedMetadata);
184
Chris Lattnerac161bf2009-01-02 07:01:27 +0000185 return false;
186}
187
188//===----------------------------------------------------------------------===//
189// Top-Level Entities
190//===----------------------------------------------------------------------===//
191
192bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000193 while (1) {
194 switch (Lex.getKind()) {
195 default: return TokError("expected top-level entity");
196 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000197 case lltok::kw_declare: if (ParseDeclare()) return true; break;
198 case lltok::kw_define: if (ParseDefine()) return true; break;
199 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
200 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000201 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000202 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000204 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000205 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000206 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000207 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000208 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000209
210 // The Global variable production with no name can have many different
211 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000212 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000213 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000214 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000215 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000216 case lltok::kw_internal: // OptionalLinkage
217 case lltok::kw_weak: // OptionalLinkage
218 case lltok::kw_weak_odr: // OptionalLinkage
219 case lltok::kw_linkonce: // OptionalLinkage
220 case lltok::kw_linkonce_odr: // OptionalLinkage
221 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000222 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000223 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000224 case lltok::kw_external: // OptionalLinkage
225 case lltok::kw_default: // OptionalVisibility
226 case lltok::kw_hidden: // OptionalVisibility
227 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000228 case lltok::kw_dllimport: // OptionalDLLStorageClass
229 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000230 case lltok::kw_thread_local: // OptionalThreadLocal
231 case lltok::kw_addrspace: // OptionalAddrSpace
232 case lltok::kw_constant: // GlobalType
233 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000234 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000235 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000236 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000237 bool HasLinkage;
238 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000240 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000241 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000242 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000243 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000244 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000245 return true;
246 break;
247 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000248
249 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000250 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
251 case lltok::kw_uselistorder_bb:
252 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000253 }
254 }
255}
256
257
258/// toplevelentity
259/// ::= 'module' 'asm' STRINGCONSTANT
260bool LLParser::ParseModuleAsm() {
261 assert(Lex.getKind() == lltok::kw_module);
262 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000263
264 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000265 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
266 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000267
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000268 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000269 return false;
270}
271
272/// toplevelentity
273/// ::= 'target' 'triple' '=' STRINGCONSTANT
274/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
275bool LLParser::ParseTargetDefinition() {
276 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000277 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000278 switch (Lex.Lex()) {
279 default: return TokError("unknown target property");
280 case lltok::kw_triple:
281 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000282 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
283 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000284 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000285 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000286 return false;
287 case lltok::kw_datalayout:
288 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000289 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
290 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000291 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000292 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000293 return false;
294 }
295}
296
Bill Wendling706d3d62012-11-28 08:41:48 +0000297/// toplevelentity
298/// ::= 'deplibs' '=' '[' ']'
299/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
300/// FIXME: Remove in 4.0. Currently parse, but ignore.
301bool LLParser::ParseDepLibs() {
302 assert(Lex.getKind() == lltok::kw_deplibs);
303 Lex.Lex();
304 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
305 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
306 return true;
307
308 if (EatIfPresent(lltok::rsquare))
309 return false;
310
311 do {
312 std::string Str;
313 if (ParseStringConstant(Str)) return true;
314 } while (EatIfPresent(lltok::comma));
315
316 return ParseToken(lltok::rsquare, "expected ']' at end of list");
317}
318
Dan Gohman466876b2009-08-12 23:32:33 +0000319/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000320/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000321bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000322 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000323 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000324 Lex.Lex(); // eat LocalVarID;
325
326 if (ParseToken(lltok::equal, "expected '=' after name") ||
327 ParseToken(lltok::kw_type, "expected 'type' after '='"))
328 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329
Craig Topper2617dcc2014-04-15 06:32:26 +0000330 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000331 if (ParseStructDefinition(TypeLoc, "",
332 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000333
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000334 if (!isa<StructType>(Result)) {
335 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
336 if (Entry.first)
337 return Error(TypeLoc, "non-struct types may not be recursive");
338 Entry.first = Result;
339 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000340 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000341
Chris Lattnerac161bf2009-01-02 07:01:27 +0000342 return false;
343}
344
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000345
Chris Lattnerac161bf2009-01-02 07:01:27 +0000346/// toplevelentity
347/// ::= LocalVar '=' 'type' type
348bool LLParser::ParseNamedType() {
349 std::string Name = Lex.getStrVal();
350 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000351 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000352
Chris Lattner3822f632009-01-02 08:05:26 +0000353 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000354 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000355 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000356
Craig Topper2617dcc2014-04-15 06:32:26 +0000357 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358 if (ParseStructDefinition(NameLoc, Name,
359 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000360
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000361 if (!isa<StructType>(Result)) {
362 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
363 if (Entry.first)
364 return Error(NameLoc, "non-struct types may not be recursive");
365 Entry.first = Result;
366 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000368
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000369 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370}
371
372
373/// toplevelentity
374/// ::= 'declare' FunctionHeader
375bool LLParser::ParseDeclare() {
376 assert(Lex.getKind() == lltok::kw_declare);
377 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000378
Chris Lattnerac161bf2009-01-02 07:01:27 +0000379 Function *F;
380 return ParseFunctionHeader(F, false);
381}
382
383/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000384/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385bool LLParser::ParseDefine() {
386 assert(Lex.getKind() == lltok::kw_define);
387 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000388
Chris Lattnerac161bf2009-01-02 07:01:27 +0000389 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000390 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000391 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000392 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000393}
394
Chris Lattner3822f632009-01-02 08:05:26 +0000395/// ParseGlobalType
396/// ::= 'constant'
397/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000398bool LLParser::ParseGlobalType(bool &IsConstant) {
399 if (Lex.getKind() == lltok::kw_constant)
400 IsConstant = true;
401 else if (Lex.getKind() == lltok::kw_global)
402 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000403 else {
404 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000405 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000406 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000407 Lex.Lex();
408 return false;
409}
410
Dan Gohman466876b2009-08-12 23:32:33 +0000411/// ParseUnnamedGlobal:
412/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000413/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
414/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000415/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000416/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
417/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000418bool LLParser::ParseUnnamedGlobal() {
419 unsigned VarID = NumberedVals.size();
420 std::string Name;
421 LocTy NameLoc = Lex.getLoc();
422
423 // Handle the GlobalID form.
424 if (Lex.getKind() == lltok::GlobalID) {
425 if (Lex.getUIntVal() != VarID)
426 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000427 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000428 Lex.Lex(); // eat GlobalID;
429
430 if (ParseToken(lltok::equal, "expected '=' after name"))
431 return true;
432 }
433
434 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000435 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000436 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000437 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000438 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000439 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000440 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000441 ParseOptionalThreadLocal(TLM) ||
442 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000443 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000444
Rafael Espindola464fe022014-07-30 22:51:54 +0000445 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000446 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000447 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000448 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000449 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000450}
451
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452/// ParseNamedGlobal:
453/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000454/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
455/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000456bool LLParser::ParseNamedGlobal() {
457 assert(Lex.getKind() == lltok::GlobalVar);
458 LocTy NameLoc = Lex.getLoc();
459 std::string Name = Lex.getStrVal();
460 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000461
Chris Lattnerac161bf2009-01-02 07:01:27 +0000462 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000463 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000464 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000465 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000466 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
467 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000468 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000469 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000470 ParseOptionalThreadLocal(TLM) ||
471 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000473
Rafael Espindola464fe022014-07-30 22:51:54 +0000474 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000475 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000476 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000477
478 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000479 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000480}
481
David Majnemerdad0a642014-06-27 18:19:56 +0000482bool LLParser::parseComdat() {
483 assert(Lex.getKind() == lltok::ComdatVar);
484 std::string Name = Lex.getStrVal();
485 LocTy NameLoc = Lex.getLoc();
486 Lex.Lex();
487
488 if (ParseToken(lltok::equal, "expected '=' here"))
489 return true;
490
491 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
492 return TokError("expected comdat type");
493
494 Comdat::SelectionKind SK;
495 switch (Lex.getKind()) {
496 default:
497 return TokError("unknown selection kind");
498 case lltok::kw_any:
499 SK = Comdat::Any;
500 break;
501 case lltok::kw_exactmatch:
502 SK = Comdat::ExactMatch;
503 break;
504 case lltok::kw_largest:
505 SK = Comdat::Largest;
506 break;
507 case lltok::kw_noduplicates:
508 SK = Comdat::NoDuplicates;
509 break;
510 case lltok::kw_samesize:
511 SK = Comdat::SameSize;
512 break;
513 }
514 Lex.Lex();
515
516 // See if the comdat was forward referenced, if so, use the comdat.
517 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
518 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
519 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
520 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
521
522 Comdat *C;
523 if (I != ComdatSymTab.end())
524 C = &I->second;
525 else
526 C = M->getOrInsertComdat(Name);
527 C->setSelectionKind(SK);
528
529 return false;
530}
531
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000532// MDString:
533// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000534bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000535 std::string Str;
536 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000537 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000538 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000539 return false;
540}
541
542// MDNode:
543// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000544bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000545 // !{ ..., !42, ... }
546 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000547 if (ParseUInt32(MID))
548 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000549
Chris Lattner8eff0152010-04-01 05:14:45 +0000550 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000551 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000552 Result = NumberedMetadata[MID];
553 return false;
554 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000555
Chris Lattner8eff0152010-04-01 05:14:45 +0000556 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000557 auto &FwdRef = ForwardRefMDNodes[MID];
558 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000559
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000560 Result = FwdRef.first.get();
561 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000562 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000563}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000564
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000565/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000566/// !foo = !{ !1, !2 }
567bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000568 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000569 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000570 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000571
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000572 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000573 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000574 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000575 return true;
576
Dan Gohman2637cc12010-07-21 23:38:33 +0000577 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000578 if (Lex.getKind() != lltok::rbrace)
579 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000580 if (ParseToken(lltok::exclaim, "Expected '!' here"))
581 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000582
Craig Topper2617dcc2014-04-15 06:32:26 +0000583 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000584 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000585 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000586 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000587
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000588 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000589}
590
Devang Patel39e64d42009-07-01 19:21:12 +0000591/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000592/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000593bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000594 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000595 Lex.Lex();
596 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000597
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000598 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000599 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000600 ParseToken(lltok::equal, "expected '=' here"))
601 return true;
602
603 // Detect common error, from old metadata syntax.
604 if (Lex.getKind() == lltok::Type)
605 return TokError("unexpected type in metadata definition");
606
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000607 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000608 if (Lex.getKind() == lltok::MetadataVar) {
609 if (ParseSpecializedMDNode(Init, IsDistinct))
610 return true;
611 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
612 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000613 return true;
614
Chris Lattnerfc58af22009-12-30 04:51:58 +0000615 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000616 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000617 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000618 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000619 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000620
Chris Lattnerfc58af22009-12-30 04:51:58 +0000621 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
622 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000623 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000624 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000625 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000626 }
627
Devang Patel39e64d42009-07-01 19:21:12 +0000628 return false;
629}
630
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000631static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
632 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
633 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
634}
635
Chris Lattnerac161bf2009-01-02 07:01:27 +0000636/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000637/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
638/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000639/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000640///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000641/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000642/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000643///
Eric Christopher536f0a92015-05-28 23:07:39 +0000644/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000645///
Rafael Espindola464fe022014-07-30 22:51:54 +0000646bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000647 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000648 GlobalVariable::ThreadLocalMode TLM,
649 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000650 assert(Lex.getKind() == lltok::kw_alias);
651 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000652
Rafael Espindola78527052013-10-06 15:10:43 +0000653 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
654
Rafael Espindolacaa43562013-10-09 16:07:32 +0000655 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000656 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000657
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000658 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000659 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000660 "symbol with local linkage must have default visibility");
661
Rafael Espindola64c1e182014-06-03 02:41:57 +0000662 Constant *Aliasee;
663 LocTy AliaseeLoc = Lex.getLoc();
664 if (Lex.getKind() != lltok::kw_bitcast &&
665 Lex.getKind() != lltok::kw_getelementptr &&
666 Lex.getKind() != lltok::kw_addrspacecast &&
667 Lex.getKind() != lltok::kw_inttoptr) {
668 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000669 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000670 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000671 // The bitcast dest type is not present, it is implied by the dest type.
672 ValID ID;
673 if (ParseValID(ID))
674 return true;
675 if (ID.Kind != ValID::t_Constant)
676 return Error(AliaseeLoc, "invalid aliasee");
677 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000679
Rafael Espindola64c1e182014-06-03 02:41:57 +0000680 Type *AliaseeType = Aliasee->getType();
681 auto *PTy = dyn_cast<PointerType>(AliaseeType);
682 if (!PTy)
683 return Error(AliaseeLoc, "An alias must have pointer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000684
685 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000686 std::unique_ptr<GlobalAlias> GA(
David Blaikief64246b2015-04-29 21:22:39 +0000687 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
688 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000689 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000690 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000691 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000692 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000693
Rafael Espindola54fc2982015-06-17 17:53:31 +0000694 if (Name.empty())
695 NumberedVals.push_back(GA.get());
696
Chris Lattnerac161bf2009-01-02 07:01:27 +0000697 // See if this value already exists in the symbol table. If so, it is either
698 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000699 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700 // See if this was a redefinition. If so, there is no entry in
701 // ForwardRefVals.
702 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
703 I = ForwardRefVals.find(Name);
704 if (I == ForwardRefVals.end())
705 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
706
707 // Otherwise, this was a definition of forward ref. Verify that types
708 // agree.
709 if (Val->getType() != GA->getType())
710 return Error(NameLoc,
711 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000712
Chris Lattnerac161bf2009-01-02 07:01:27 +0000713 // If they agree, just RAUW the old value with the alias and remove the
714 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000715 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000716 Val->eraseFromParent();
717 ForwardRefVals.erase(I);
718 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000719
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000721 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000722 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723
Rafael Espindolaaa273822014-05-09 21:49:17 +0000724 // The module owns this now
725 GA.release();
726
Chris Lattnerac161bf2009-01-02 07:01:27 +0000727 return false;
728}
729
730/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000731/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000732/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000733/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000734/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000735/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000736/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000737///
Eric Christopher536f0a92015-05-28 23:07:39 +0000738/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000739/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000740///
741bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
742 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000743 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000744 GlobalVariable::ThreadLocalMode TLM,
745 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000746 if (!isValidVisibilityForLinkage(Visibility, Linkage))
747 return Error(NameLoc,
748 "symbol with local linkage must have default visibility");
749
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000751 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000752 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000753 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000754
Craig Topper2617dcc2014-04-15 06:32:26 +0000755 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000756 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000757 ParseOptionalToken(lltok::kw_externally_initialized,
758 IsExternallyInitialized,
759 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000760 ParseGlobalType(IsConstant) ||
761 ParseType(Ty, TyLoc))
762 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000763
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 // If the linkage is specified and is external, then no initializer is
765 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000766 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000767 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000768 Linkage != GlobalValue::ExternalLinkage)) {
769 if (ParseGlobalValue(Ty, Init))
770 return true;
771 }
772
David Majnemer49b3d9b2015-02-16 08:41:08 +0000773 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000774 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000775
David Majnemer598bd052014-12-09 05:56:09 +0000776 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000777
778 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000779 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000780 GVal = M->getNamedValue(Name);
781 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000782 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
783 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000784 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000785 } else {
786 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
787 I = ForwardRefValIDs.find(NumberedVals.size());
788 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000789 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000790 ForwardRefValIDs.erase(I);
791 }
792 }
793
David Majnemer598bd052014-12-09 05:56:09 +0000794 GlobalVariable *GV;
795 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000796 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
797 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000798 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000799 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000800 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000801 return Error(TyLoc,
802 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
David Majnemer598bd052014-12-09 05:56:09 +0000804 GV = cast<GlobalVariable>(GVal);
805
Chris Lattnerac161bf2009-01-02 07:01:27 +0000806 // Move the forward-reference to the correct spot in the module.
807 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
808 }
809
810 if (Name.empty())
811 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000812
Chris Lattnerac161bf2009-01-02 07:01:27 +0000813 // Set the parsed properties on the global.
814 if (Init)
815 GV->setInitializer(Init);
816 GV->setConstant(IsConstant);
817 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
818 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000819 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000820 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000821 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000822 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000823
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 // Parse attributes on the global.
825 while (Lex.getKind() == lltok::comma) {
826 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 if (Lex.getKind() == lltok::kw_section) {
829 Lex.Lex();
830 GV->setSection(Lex.getStrVal());
831 if (ParseToken(lltok::StringConstant, "expected global section string"))
832 return true;
833 } else if (Lex.getKind() == lltok::kw_align) {
834 unsigned Alignment;
835 if (ParseOptionalAlignment(Alignment)) return true;
836 GV->setAlignment(Alignment);
837 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000838 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000839 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000840 return true;
841 if (C)
842 GV->setComdat(C);
843 else
844 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 }
846 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000847
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848 return false;
849}
850
Bill Wendling63b88192013-02-06 06:52:58 +0000851/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000852/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000853bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000854 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000855 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000856 Lex.Lex();
857
David Majnemerb39e22b2014-12-09 18:33:57 +0000858 if (Lex.getKind() != lltok::AttrGrpID)
859 return TokError("expected attribute group id");
860
Bill Wendling63b88192013-02-06 06:52:58 +0000861 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000862 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000863 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000864 Lex.Lex();
865
866 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000867 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000868 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000869 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000870 ParseToken(lltok::rbrace, "expected end of attribute group"))
871 return true;
872
Bill Wendlingb32b0412013-02-08 06:32:06 +0000873 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000874 return Error(AttrGrpLoc, "attribute group has no attributes");
875
876 return false;
877}
878
Bill Wendling8b0321d2013-02-08 00:52:31 +0000879/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000880/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000881bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
882 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000883 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000884 bool HaveError = false;
885
886 B.clear();
887
Bill Wendling63b88192013-02-06 06:52:58 +0000888 while (true) {
889 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000890 if (Token == lltok::kw_builtin)
891 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000892 switch (Token) {
893 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000894 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000895 return Error(Lex.getLoc(), "unterminated attribute group");
896 case lltok::rbrace:
897 // Finished.
898 return false;
899
Bill Wendlingb32b0412013-02-08 06:32:06 +0000900 case lltok::AttrGrpID: {
901 // Allow a function to reference an attribute group:
902 //
903 // define void @foo() #1 { ... }
904 if (inAttrGrp)
905 HaveError |=
906 Error(Lex.getLoc(),
907 "cannot have an attribute group reference in an attribute group");
908
909 unsigned AttrGrpNum = Lex.getUIntVal();
910 if (inAttrGrp) break;
911
912 // Save the reference to the attribute group. We'll fill it in later.
913 FwdRefAttrGrps.push_back(AttrGrpNum);
914 break;
915 }
Bill Wendling63b88192013-02-06 06:52:58 +0000916 // Target-dependent attributes:
917 case lltok::StringConstant: {
918 std::string Attr = Lex.getStrVal();
919 Lex.Lex();
920 std::string Val;
921 if (EatIfPresent(lltok::equal) &&
922 ParseStringConstant(Val))
923 return true;
924
925 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000926 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000927 }
928
929 // Target-independent attributes:
930 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000931 // As a hack, we allow function alignment to be initially parsed as an
932 // attribute on a function declaration/definition or added to an attribute
933 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000934 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000935 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000936 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000937 if (ParseToken(lltok::equal, "expected '=' here") ||
938 ParseUInt32(Alignment))
939 return true;
940 } else {
941 if (ParseOptionalAlignment(Alignment))
942 return true;
943 }
Bill Wendling63b88192013-02-06 06:52:58 +0000944 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000945 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000946 }
947 case lltok::kw_alignstack: {
948 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000949 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000950 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000951 if (ParseToken(lltok::equal, "expected '=' here") ||
952 ParseUInt32(Alignment))
953 return true;
954 } else {
955 if (ParseOptionalStackAlignment(Alignment))
956 return true;
957 }
Bill Wendling63b88192013-02-06 06:52:58 +0000958 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000959 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000960 }
Igor Laevsky39d662f2015-07-11 10:30:36 +0000961 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
962 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
963 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
964 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
965 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
966 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
967 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
968 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
969 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
970 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
971 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
972 case lltok::kw_noimplicitfloat:
973 B.addAttribute(Attribute::NoImplicitFloat); break;
974 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
975 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
976 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
977 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
978 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
979 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
980 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
981 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
982 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
983 case lltok::kw_returns_twice:
984 B.addAttribute(Attribute::ReturnsTwice); break;
985 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
986 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
987 case lltok::kw_sspstrong:
988 B.addAttribute(Attribute::StackProtectStrong); break;
989 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
990 case lltok::kw_sanitize_address:
991 B.addAttribute(Attribute::SanitizeAddress); break;
992 case lltok::kw_sanitize_thread:
993 B.addAttribute(Attribute::SanitizeThread); break;
994 case lltok::kw_sanitize_memory:
995 B.addAttribute(Attribute::SanitizeMemory); break;
996 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000997
998 // Error handling.
999 case lltok::kw_inreg:
1000 case lltok::kw_signext:
1001 case lltok::kw_zeroext:
1002 HaveError |=
1003 Error(Lex.getLoc(),
1004 "invalid use of attribute on a function");
1005 break;
1006 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001007 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001008 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001009 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001010 case lltok::kw_nest:
1011 case lltok::kw_noalias:
1012 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001013 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001014 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001015 case lltok::kw_sret:
1016 HaveError |=
1017 Error(Lex.getLoc(),
1018 "invalid use of parameter-only attribute on a function");
1019 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001020 }
1021
1022 Lex.Lex();
1023 }
1024}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001025
1026//===----------------------------------------------------------------------===//
1027// GlobalValue Reference/Resolution Routines.
1028//===----------------------------------------------------------------------===//
1029
1030/// GetGlobalVal - Get a value with the specified name or ID, creating a
1031/// forward reference record if needed. This can return null if the value
1032/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001033GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001034 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001035 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001036 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001037 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001038 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001040
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 // Look this name up in the normal function symbol table.
1042 GlobalValue *Val =
1043 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001044
Chris Lattnerac161bf2009-01-02 07:01:27 +00001045 // If this is a forward reference for the value, see if we already created a
1046 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001047 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001048 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1049 I = ForwardRefVals.find(Name);
1050 if (I != ForwardRefVals.end())
1051 Val = I->second.first;
1052 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001053
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 // If we have the value in the symbol table or fwd-ref table, return it.
1055 if (Val) {
1056 if (Val->getType() == Ty) return Val;
1057 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001058 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001059 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001060 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001061
Chris Lattnerac161bf2009-01-02 07:01:27 +00001062 // Otherwise, create a new forward reference for this value and remember it.
1063 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001064 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001065 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001066 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001067 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001068 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1069 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001070 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001071
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1073 return FwdVal;
1074}
1075
Chris Lattner229907c2011-07-18 04:54:35 +00001076GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1077 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001078 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001079 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001080 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001082
Craig Topper2617dcc2014-04-15 06:32:26 +00001083 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001084
Chris Lattnerac161bf2009-01-02 07:01:27 +00001085 // If this is a forward reference for the value, see if we already created a
1086 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001087 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001088 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1089 I = ForwardRefValIDs.find(ID);
1090 if (I != ForwardRefValIDs.end())
1091 Val = I->second.first;
1092 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001093
Chris Lattnerac161bf2009-01-02 07:01:27 +00001094 // If we have the value in the symbol table or fwd-ref table, return it.
1095 if (Val) {
1096 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001097 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001098 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001099 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001100 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001101
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102 // Otherwise, create a new forward reference for this value and remember it.
1103 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001104 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001105 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001106 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001107 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001108 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001109
Chris Lattnerac161bf2009-01-02 07:01:27 +00001110 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1111 return FwdVal;
1112}
1113
1114
1115//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001116// Comdat Reference/Resolution Routines.
1117//===----------------------------------------------------------------------===//
1118
1119Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1120 // Look this name up in the comdat symbol table.
1121 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1122 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1123 if (I != ComdatSymTab.end())
1124 return &I->second;
1125
1126 // Otherwise, create a new forward reference for this value and remember it.
1127 Comdat *C = M->getOrInsertComdat(Name);
1128 ForwardRefComdats[Name] = Loc;
1129 return C;
1130}
1131
1132
1133//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001134// Helper Routines.
1135//===----------------------------------------------------------------------===//
1136
1137/// ParseToken - If the current token has the specified kind, eat it and return
1138/// success. Otherwise, emit the specified error and return failure.
1139bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1140 if (Lex.getKind() != T)
1141 return TokError(ErrMsg);
1142 Lex.Lex();
1143 return false;
1144}
1145
Chris Lattner3822f632009-01-02 08:05:26 +00001146/// ParseStringConstant
1147/// ::= StringConstant
1148bool LLParser::ParseStringConstant(std::string &Result) {
1149 if (Lex.getKind() != lltok::StringConstant)
1150 return TokError("expected string constant");
1151 Result = Lex.getStrVal();
1152 Lex.Lex();
1153 return false;
1154}
1155
1156/// ParseUInt32
1157/// ::= uint32
1158bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001159 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1160 return TokError("expected integer");
1161 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1162 if (Val64 != unsigned(Val64))
1163 return TokError("expected 32-bit integer (too large)");
1164 Val = Val64;
1165 Lex.Lex();
1166 return false;
1167}
1168
Hal Finkelb0407ba2014-07-18 15:51:28 +00001169/// ParseUInt64
1170/// ::= uint64
1171bool LLParser::ParseUInt64(uint64_t &Val) {
1172 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1173 return TokError("expected integer");
1174 Val = Lex.getAPSIntVal().getLimitedValue();
1175 Lex.Lex();
1176 return false;
1177}
1178
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001179/// ParseTLSModel
1180/// := 'localdynamic'
1181/// := 'initialexec'
1182/// := 'localexec'
1183bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1184 switch (Lex.getKind()) {
1185 default:
1186 return TokError("expected localdynamic, initialexec or localexec");
1187 case lltok::kw_localdynamic:
1188 TLM = GlobalVariable::LocalDynamicTLSModel;
1189 break;
1190 case lltok::kw_initialexec:
1191 TLM = GlobalVariable::InitialExecTLSModel;
1192 break;
1193 case lltok::kw_localexec:
1194 TLM = GlobalVariable::LocalExecTLSModel;
1195 break;
1196 }
1197
1198 Lex.Lex();
1199 return false;
1200}
1201
1202/// ParseOptionalThreadLocal
1203/// := /*empty*/
1204/// := 'thread_local'
1205/// := 'thread_local' '(' tlsmodel ')'
1206bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1207 TLM = GlobalVariable::NotThreadLocal;
1208 if (!EatIfPresent(lltok::kw_thread_local))
1209 return false;
1210
1211 TLM = GlobalVariable::GeneralDynamicTLSModel;
1212 if (Lex.getKind() == lltok::lparen) {
1213 Lex.Lex();
1214 return ParseTLSModel(TLM) ||
1215 ParseToken(lltok::rparen, "expected ')' after thread local model");
1216 }
1217 return false;
1218}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219
1220/// ParseOptionalAddrSpace
1221/// := /*empty*/
1222/// := 'addrspace' '(' uint32 ')'
1223bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1224 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001225 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001228 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001229 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001230}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231
Bill Wendling34c2eb22012-12-04 23:40:58 +00001232/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1233bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1234 bool HaveError = false;
1235
1236 B.clear();
1237
1238 while (1) {
1239 lltok::Kind Token = Lex.getKind();
1240 switch (Token) {
1241 default: // End of attributes.
1242 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001243 case lltok::kw_align: {
1244 unsigned Alignment;
1245 if (ParseOptionalAlignment(Alignment))
1246 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001247 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001248 continue;
1249 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001250 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001251 case lltok::kw_dereferenceable: {
1252 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001253 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001254 return true;
1255 B.addDereferenceableAttr(Bytes);
1256 continue;
1257 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001258 case lltok::kw_dereferenceable_or_null: {
1259 uint64_t Bytes;
1260 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1261 return true;
1262 B.addDereferenceableOrNullAttr(Bytes);
1263 continue;
1264 }
Reid Klecknera534a382013-12-19 02:14:12 +00001265 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001266 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1267 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1268 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1269 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001270 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001271 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1272 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001273 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001274 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1275 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1276 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001277
Stephen Lin7577ed52013-04-20 13:16:13 +00001278 case lltok::kw_alignstack:
1279 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001280 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001281 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001282 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001283 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001284 case lltok::kw_minsize:
1285 case lltok::kw_naked:
1286 case lltok::kw_nobuiltin:
1287 case lltok::kw_noduplicate:
1288 case lltok::kw_noimplicitfloat:
1289 case lltok::kw_noinline:
1290 case lltok::kw_nonlazybind:
1291 case lltok::kw_noredzone:
1292 case lltok::kw_noreturn:
1293 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001294 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001295 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001296 case lltok::kw_returns_twice:
1297 case lltok::kw_sanitize_address:
1298 case lltok::kw_sanitize_memory:
1299 case lltok::kw_sanitize_thread:
1300 case lltok::kw_ssp:
1301 case lltok::kw_sspreq:
1302 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001303 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001304 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001305 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1306 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001307 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001308
Bill Wendling34c2eb22012-12-04 23:40:58 +00001309 Lex.Lex();
1310 }
1311}
1312
1313/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1314bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1315 bool HaveError = false;
1316
1317 B.clear();
1318
1319 while (1) {
1320 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001321 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001322 default: // End of attributes.
1323 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001324 case lltok::kw_dereferenceable: {
1325 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001326 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001327 return true;
1328 B.addDereferenceableAttr(Bytes);
1329 continue;
1330 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001331 case lltok::kw_dereferenceable_or_null: {
1332 uint64_t Bytes;
1333 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1334 return true;
1335 B.addDereferenceableOrNullAttr(Bytes);
1336 continue;
1337 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001338 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1339 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001340 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001341 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1342 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001343
Bill Wendling34c2eb22012-12-04 23:40:58 +00001344 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001345 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001346 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001347 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001348 case lltok::kw_nest:
1349 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001350 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001351 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001352 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001353 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001354
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001355 case lltok::kw_alignstack:
1356 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001357 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001358 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001359 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001360 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001361 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001362 case lltok::kw_minsize:
1363 case lltok::kw_naked:
1364 case lltok::kw_nobuiltin:
1365 case lltok::kw_noduplicate:
1366 case lltok::kw_noimplicitfloat:
1367 case lltok::kw_noinline:
1368 case lltok::kw_nonlazybind:
1369 case lltok::kw_noredzone:
1370 case lltok::kw_noreturn:
1371 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001372 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001373 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001374 case lltok::kw_returns_twice:
1375 case lltok::kw_sanitize_address:
1376 case lltok::kw_sanitize_memory:
1377 case lltok::kw_sanitize_thread:
1378 case lltok::kw_ssp:
1379 case lltok::kw_sspreq:
1380 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001381 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001382 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001383 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001384 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001385
1386 case lltok::kw_readnone:
1387 case lltok::kw_readonly:
1388 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001389 }
1390
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391 Lex.Lex();
1392 }
1393}
1394
1395/// ParseOptionalLinkage
1396/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001397/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001398/// ::= 'internal'
1399/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001400/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001401/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001402/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001403/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001404/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001405/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001406/// ::= 'extern_weak'
1407/// ::= 'external'
1408bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1409 HasLinkage = false;
1410 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001411 default: Res=GlobalValue::ExternalLinkage; return false;
1412 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001413 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1414 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1415 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1416 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1417 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001418 case lltok::kw_available_externally:
1419 Res = GlobalValue::AvailableExternallyLinkage;
1420 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001421 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001422 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001423 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1424 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001425 }
1426 Lex.Lex();
1427 HasLinkage = true;
1428 return false;
1429}
1430
1431/// ParseOptionalVisibility
1432/// ::= /*empty*/
1433/// ::= 'default'
1434/// ::= 'hidden'
1435/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001436///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001437bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1438 switch (Lex.getKind()) {
1439 default: Res = GlobalValue::DefaultVisibility; return false;
1440 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1441 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1442 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1443 }
1444 Lex.Lex();
1445 return false;
1446}
1447
Nico Rieck7157bb72014-01-14 15:22:47 +00001448/// ParseOptionalDLLStorageClass
1449/// ::= /*empty*/
1450/// ::= 'dllimport'
1451/// ::= 'dllexport'
1452///
1453bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1454 switch (Lex.getKind()) {
1455 default: Res = GlobalValue::DefaultStorageClass; return false;
1456 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1457 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1458 }
1459 Lex.Lex();
1460 return false;
1461}
1462
Chris Lattnerac161bf2009-01-02 07:01:27 +00001463/// ParseOptionalCallingConv
1464/// ::= /*empty*/
1465/// ::= 'ccc'
1466/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001467/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001468/// ::= 'coldcc'
1469/// ::= 'x86_stdcallcc'
1470/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001471/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001472/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001473/// ::= 'arm_apcscc'
1474/// ::= 'arm_aapcscc'
1475/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001476/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001477/// ::= 'ptx_kernel'
1478/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001479/// ::= 'spir_func'
1480/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001481/// ::= 'x86_64_sysvcc'
1482/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001483/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001484/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001485/// ::= 'preserve_mostcc'
1486/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001487/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001488/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001489///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001490bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001491 switch (Lex.getKind()) {
1492 default: CC = CallingConv::C; return false;
1493 case lltok::kw_ccc: CC = CallingConv::C; break;
1494 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1495 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1496 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1497 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001498 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001499 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001500 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1501 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1502 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001503 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001504 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1505 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001506 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1507 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001508 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001509 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1510 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001511 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001512 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001513 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1514 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001515 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001516 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001517 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001518 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001519 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001520 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001521
Chris Lattnerac161bf2009-01-02 07:01:27 +00001522 Lex.Lex();
1523 return false;
1524}
1525
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001526/// ParseMetadataAttachment
1527/// ::= !dbg !42
1528bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1529 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1530
1531 std::string Name = Lex.getStrVal();
1532 Kind = M->getMDKindID(Name);
1533 Lex.Lex();
1534
1535 return ParseMDNode(MD);
1536}
1537
Chris Lattner5c427632009-12-30 05:31:19 +00001538/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001539/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001540bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001541 do {
1542 if (Lex.getKind() != lltok::MetadataVar)
1543 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001544
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001545 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001546 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001547 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001548 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001549
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001550 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001551 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001552 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001553
Chris Lattner596760d2009-12-29 21:25:40 +00001554 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001555 } while (EatIfPresent(lltok::comma));
1556 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001557}
1558
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001559/// ParseOptionalFunctionMetadata
1560/// ::= (!dbg !57)*
1561bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1562 while (Lex.getKind() == lltok::MetadataVar) {
1563 unsigned MDK;
1564 MDNode *N;
1565 if (ParseMetadataAttachment(MDK, N))
1566 return true;
1567
1568 F.setMetadata(MDK, N);
1569 }
1570 return false;
1571}
1572
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573/// ParseOptionalAlignment
1574/// ::= /* empty */
1575/// ::= 'align' 4
1576bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1577 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001578 if (!EatIfPresent(lltok::kw_align))
1579 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001580 LocTy AlignLoc = Lex.getLoc();
1581 if (ParseUInt32(Alignment)) return true;
1582 if (!isPowerOf2_32(Alignment))
1583 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001584 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001585 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001586 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001587}
1588
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001589/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001590/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001591/// ::= AttrKind '(' 4 ')'
1592///
1593/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1594bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1595 uint64_t &Bytes) {
1596 assert((AttrKind == lltok::kw_dereferenceable ||
1597 AttrKind == lltok::kw_dereferenceable_or_null) &&
1598 "contract!");
1599
Hal Finkelb0407ba2014-07-18 15:51:28 +00001600 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001601 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001602 return false;
1603 LocTy ParenLoc = Lex.getLoc();
1604 if (!EatIfPresent(lltok::lparen))
1605 return Error(ParenLoc, "expected '('");
1606 LocTy DerefLoc = Lex.getLoc();
1607 if (ParseUInt64(Bytes)) return true;
1608 ParenLoc = Lex.getLoc();
1609 if (!EatIfPresent(lltok::rparen))
1610 return Error(ParenLoc, "expected ')'");
1611 if (!Bytes)
1612 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1613 return false;
1614}
1615
Chris Lattnerb2f39502009-12-30 05:44:30 +00001616/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001617/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001618/// ::= ',' align 4
1619///
1620/// This returns with AteExtraComma set to true if it ate an excess comma at the
1621/// end.
1622bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1623 bool &AteExtraComma) {
1624 AteExtraComma = false;
1625 while (EatIfPresent(lltok::comma)) {
1626 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001627 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001628 AteExtraComma = true;
1629 return false;
1630 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001631
Chris Lattner95b0ff42010-04-23 00:50:50 +00001632 if (Lex.getKind() != lltok::kw_align)
1633 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001634
Chris Lattner95b0ff42010-04-23 00:50:50 +00001635 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001636 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001637
Devang Patelea8a4b92009-09-17 23:04:48 +00001638 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001639}
1640
Eli Friedmanfee02c62011-07-25 23:16:38 +00001641/// ParseScopeAndOrdering
1642/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1643/// else: ::=
1644///
1645/// This sets Scope and Ordering to the parsed values.
1646bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1647 AtomicOrdering &Ordering) {
1648 if (!isAtomic)
1649 return false;
1650
1651 Scope = CrossThread;
1652 if (EatIfPresent(lltok::kw_singlethread))
1653 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001654
1655 return ParseOrdering(Ordering);
1656}
1657
1658/// ParseOrdering
1659/// ::= AtomicOrdering
1660///
1661/// This sets Ordering to the parsed value.
1662bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001663 switch (Lex.getKind()) {
1664 default: return TokError("Expected ordering on atomic instruction");
1665 case lltok::kw_unordered: Ordering = Unordered; break;
1666 case lltok::kw_monotonic: Ordering = Monotonic; break;
1667 case lltok::kw_acquire: Ordering = Acquire; break;
1668 case lltok::kw_release: Ordering = Release; break;
1669 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1670 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1671 }
1672 Lex.Lex();
1673 return false;
1674}
1675
Charles Davisbe5557e2010-02-12 00:31:15 +00001676/// ParseOptionalStackAlignment
1677/// ::= /* empty */
1678/// ::= 'alignstack' '(' 4 ')'
1679bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1680 Alignment = 0;
1681 if (!EatIfPresent(lltok::kw_alignstack))
1682 return false;
1683 LocTy ParenLoc = Lex.getLoc();
1684 if (!EatIfPresent(lltok::lparen))
1685 return Error(ParenLoc, "expected '('");
1686 LocTy AlignLoc = Lex.getLoc();
1687 if (ParseUInt32(Alignment)) return true;
1688 ParenLoc = Lex.getLoc();
1689 if (!EatIfPresent(lltok::rparen))
1690 return Error(ParenLoc, "expected ')'");
1691 if (!isPowerOf2_32(Alignment))
1692 return Error(AlignLoc, "stack alignment is not a power of two");
1693 return false;
1694}
Devang Patelea8a4b92009-09-17 23:04:48 +00001695
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001696/// ParseIndexList - This parses the index list for an insert/extractvalue
1697/// instruction. This sets AteExtraComma in the case where we eat an extra
1698/// comma at the end of the line and find that it is followed by metadata.
1699/// Clients that don't allow metadata can call the version of this function that
1700/// only takes one argument.
1701///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001702/// ParseIndexList
1703/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001704///
1705bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1706 bool &AteExtraComma) {
1707 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001708
Chris Lattnerac161bf2009-01-02 07:01:27 +00001709 if (Lex.getKind() != lltok::comma)
1710 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001711
Chris Lattner3822f632009-01-02 08:05:26 +00001712 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001713 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001714 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001715 AteExtraComma = true;
1716 return false;
1717 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001718 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001719 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001720 Indices.push_back(Idx);
1721 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001722
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723 return false;
1724}
1725
1726//===----------------------------------------------------------------------===//
1727// Type Parsing.
1728//===----------------------------------------------------------------------===//
1729
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001730/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001731bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001733 switch (Lex.getKind()) {
1734 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001735 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001737 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001739 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001741 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 // Type ::= StructType
1743 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001744 return true;
1745 break;
1746 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001748 Lex.Lex(); // eat the lsquare.
1749 if (ParseArrayVectorType(Result, false))
1750 return true;
1751 break;
1752 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001754 Lex.Lex();
1755 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001757 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001758 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001759 } else if (ParseArrayVectorType(Result, true))
1760 return true;
1761 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001762 case lltok::LocalVar: {
1763 // Type ::= %foo
1764 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001765
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001766 // If the type hasn't been defined yet, create a forward definition and
1767 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001768 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001769 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001770 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 Lex.Lex();
1774 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001775 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001776
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001777 case lltok::LocalVarID: {
1778 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001779 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001780
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001781 // If the type hasn't been defined yet, create a forward definition and
1782 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001783 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001784 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001785 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001786 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001787 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001788 Lex.Lex();
1789 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001790 }
1791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001792
1793 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001794 while (1) {
1795 switch (Lex.getKind()) {
1796 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 default:
1798 if (!AllowVoid && Result->isVoidTy())
1799 return Error(TypeLoc, "void type only allowed for function results");
1800 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001802 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001804 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001805 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001806 if (Result->isVoidTy())
1807 return TokError("pointers to void are invalid - use i8* instead");
1808 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001809 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001810 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 Lex.Lex();
1812 break;
1813
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001814 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001815 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001816 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001817 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001818 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001819 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001821 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001822 unsigned AddrSpace;
1823 if (ParseOptionalAddrSpace(AddrSpace) ||
1824 ParseToken(lltok::star, "expected '*' in address space"))
1825 return true;
1826
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001827 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001828 break;
1829 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001830
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1832 case lltok::lparen:
1833 if (ParseFunctionType(Result))
1834 return true;
1835 break;
1836 }
1837 }
1838}
1839
1840/// ParseParameterList
1841/// ::= '(' ')'
1842/// ::= '(' Arg (',' Arg)* ')'
1843/// Arg
1844/// ::= Type OptionalAttributes Value OptionalAttributes
1845bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001846 PerFunctionState &PFS, bool IsMustTailCall,
1847 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001848 if (ParseToken(lltok::lparen, "expected '(' in call"))
1849 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001850
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001851 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001852 while (Lex.getKind() != lltok::rparen) {
1853 // If this isn't the first argument, we need a comma.
1854 if (!ArgList.empty() &&
1855 ParseToken(lltok::comma, "expected ',' in argument list"))
1856 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001857
Reid Kleckner83498642014-08-26 00:33:28 +00001858 // Parse an ellipsis if this is a musttail call in a variadic function.
1859 if (Lex.getKind() == lltok::dotdotdot) {
1860 const char *Msg = "unexpected ellipsis in argument list for ";
1861 if (!IsMustTailCall)
1862 return TokError(Twine(Msg) + "non-musttail call");
1863 if (!InVarArgsFunc)
1864 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1865 Lex.Lex(); // Lex the '...', it is purely for readability.
1866 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1867 }
1868
Chris Lattnerac161bf2009-01-02 07:01:27 +00001869 // Parse the argument.
1870 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001871 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001872 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001873 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001874 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001876
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001877 if (ArgTy->isMetadataTy()) {
1878 if (ParseMetadataAsValue(V, PFS))
1879 return true;
1880 } else {
1881 // Otherwise, handle normal operands.
1882 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1883 return true;
1884 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001885 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1886 AttrIndex++,
1887 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001888 }
1889
Reid Kleckner83498642014-08-26 00:33:28 +00001890 if (IsMustTailCall && InVarArgsFunc)
1891 return TokError("expected '...' at end of argument list for musttail call "
1892 "in varargs function");
1893
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 Lex.Lex(); // Lex the ')'.
1895 return false;
1896}
1897
1898
1899
Chris Lattner2ed06b42009-01-05 18:34:07 +00001900/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001902/// ::= '(' ArgTypeListI ')'
1903/// ArgTypeListI
1904/// ::= /*empty*/
1905/// ::= '...'
1906/// ::= ArgTypeList ',' '...'
1907/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001908///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001909bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1910 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 isVarArg = false;
1912 assert(Lex.getKind() == lltok::lparen);
1913 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001914
Chris Lattnerac161bf2009-01-02 07:01:27 +00001915 if (Lex.getKind() == lltok::rparen) {
1916 // empty
1917 } else if (Lex.getKind() == lltok::dotdotdot) {
1918 isVarArg = true;
1919 Lex.Lex();
1920 } else {
1921 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001922 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001923 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001925
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001927 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001928
Chris Lattnerfdd87902009-10-05 05:54:46 +00001929 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001930 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931
Chris Lattnerdef19492011-06-17 06:36:20 +00001932 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933 Name = Lex.getStrVal();
1934 Lex.Lex();
1935 }
Chris Lattner3822f632009-01-02 08:05:26 +00001936
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001937 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001938 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001939
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001940 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001941 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1942 AttrIndex++, Attrs),
1943 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944
Chris Lattner3822f632009-01-02 08:05:26 +00001945 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001946 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001947 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001948 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001949 break;
1950 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001951
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952 // Otherwise must be an argument type.
1953 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001954 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001955
Chris Lattnerfdd87902009-10-05 05:54:46 +00001956 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001957 return Error(TypeLoc, "argument can not have void type");
1958
Chris Lattnerdef19492011-06-17 06:36:20 +00001959 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001960 Name = Lex.getStrVal();
1961 Lex.Lex();
1962 } else {
1963 Name = "";
1964 }
Chris Lattner3822f632009-01-02 08:05:26 +00001965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001966 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001967 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001968
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001969 ArgList.emplace_back(
1970 TypeLoc, ArgTy,
1971 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1972 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 }
1974 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001975
Chris Lattner3822f632009-01-02 08:05:26 +00001976 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Chris Lattnerac161bf2009-01-02 07:01:27 +00001979/// ParseFunctionType
1980/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001982 assert(Lex.getKind() == lltok::lparen);
1983
Chris Lattnerce473c72009-01-05 08:04:33 +00001984 if (!FunctionType::isValidReturnType(Result))
1985 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001991
Chris Lattnerac161bf2009-01-02 07:01:27 +00001992 // Reject names on the arguments lists.
1993 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1994 if (!ArgList[i].Name.empty())
1995 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001996 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001997 return Error(ArgList[i].Loc,
1998 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001999 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002000
Jay Foadb804a2b2011-07-12 14:06:48 +00002001 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002002 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002004
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 return false;
2007}
2008
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2010/// other structs.
2011bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2012 SmallVector<Type*, 8> Elts;
2013 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002014
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 Result = StructType::get(Context, Elts, Packed);
2016 return false;
2017}
2018
2019/// ParseStructDefinition - Parse a struct in a 'type' definition.
2020bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2021 std::pair<Type*, LocTy> &Entry,
2022 Type *&ResultTy) {
2023 // If the type was already defined, diagnose the redefinition.
2024 if (Entry.first && !Entry.second.isValid())
2025 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002026
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002027 // If we have opaque, just return without filling in the definition for the
2028 // struct. This counts as a definition as far as the .ll file goes.
2029 if (EatIfPresent(lltok::kw_opaque)) {
2030 // This type is being defined, so clear the location to indicate this.
2031 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002033 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002034 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002035 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002036 ResultTy = Entry.first;
2037 return false;
2038 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002039
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002040 // If the type starts with '<', then it is either a packed struct or a vector.
2041 bool isPacked = EatIfPresent(lltok::less);
2042
2043 // If we don't have a struct, then we have a random type alias, which we
2044 // accept for compatibility with old files. These types are not allowed to be
2045 // forward referenced and not allowed to be recursive.
2046 if (Lex.getKind() != lltok::lbrace) {
2047 if (Entry.first)
2048 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002049
Craig Topper2617dcc2014-04-15 06:32:26 +00002050 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (isPacked)
2052 return ParseArrayVectorType(ResultTy, true);
2053 return ParseType(ResultTy);
2054 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002055
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056 // This type is being defined, so clear the location to indicate this.
2057 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002058
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002060 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002061 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002062
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002064
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065 SmallVector<Type*, 8> Body;
2066 if (ParseStructBody(Body) ||
2067 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2068 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002069
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070 STy->setBody(Body, isPacked);
2071 ResultTy = STy;
2072 return false;
2073}
2074
2075
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002079/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081/// ::= '<' '{' Type (',' Type)* '}' '>'
2082bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083 assert(Lex.getKind() == lltok::lbrace);
2084 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002086 // Handle the empty struct.
2087 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089
Chris Lattnerf880ca22009-03-09 04:49:14 +00002090 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002091 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002092 if (ParseType(Ty)) return true;
2093 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002095 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002096 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002097
Chris Lattner3822f632009-01-02 08:05:26 +00002098 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002099 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002100 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002102 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002103 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002104
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002105 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002108 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002109}
2110
2111/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2112/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114/// ::= '[' APSINTVAL 'x' Types ']'
2115/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002116bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2118 Lex.getAPSIntVal().getBitWidth() > 64)
2119 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 LocTy SizeLoc = Lex.getLoc();
2122 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002123 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002124
Chris Lattner3822f632009-01-02 08:05:26 +00002125 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2126 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127
2128 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002129 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002130 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002131
Chris Lattner3822f632009-01-02 08:05:26 +00002132 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2133 "expected end of sequential type"))
2134 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002135
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002137 if (Size == 0)
2138 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 if ((unsigned)Size != Size)
2140 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002141 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002142 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002143 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002145 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002147 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 }
2149 return false;
2150}
2151
2152//===----------------------------------------------------------------------===//
2153// Function Semantic Analysis.
2154//===----------------------------------------------------------------------===//
2155
Chris Lattner3432c622009-10-28 03:39:23 +00002156LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2157 int functionNumber)
2158 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159
2160 // Insert unnamed arguments into the NumberedVals list.
2161 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2162 AI != E; ++AI)
2163 if (!AI->hasName())
2164 NumberedVals.push_back(AI);
2165}
2166
2167LLParser::PerFunctionState::~PerFunctionState() {
2168 // If there were any forward referenced non-basicblock values, delete them.
2169 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2170 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2171 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002172 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002173 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002174 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002175 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002177
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2179 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2180 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002181 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002182 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002183 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002184 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185 }
2186}
2187
Chris Lattner3432c622009-10-28 03:39:23 +00002188bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002189 if (!ForwardRefVals.empty())
2190 return P.Error(ForwardRefVals.begin()->second.second,
2191 "use of undefined value '%" + ForwardRefVals.begin()->first +
2192 "'");
2193 if (!ForwardRefValIDs.empty())
2194 return P.Error(ForwardRefValIDs.begin()->second.second,
2195 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002196 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 return false;
2198}
2199
2200
2201/// GetVal - Get a value with the specified name or ID, creating a
2202/// forward reference record if needed. This can return null if the value
2203/// exists but does not have the right type.
2204Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002205 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 // Look this name up in the normal function symbol table.
2207 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 // If this is a forward reference for the value, see if we already created a
2210 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002211 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2213 I = ForwardRefVals.find(Name);
2214 if (I != ForwardRefVals.end())
2215 Val = I->second.first;
2216 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002217
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218 // If we have the value in the symbol table or fwd-ref table, return it.
2219 if (Val) {
2220 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002221 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 P.Error(Loc, "'%" + Name + "' is not a basic block");
2223 else
2224 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002225 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002226 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002227 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002228
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002230 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002232 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 // Otherwise, create a new forward reference for this value and remember it.
2236 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002237 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002238 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 else
2240 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002241
Chris Lattnerac161bf2009-01-02 07:01:27 +00002242 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2243 return FwdVal;
2244}
2245
Chris Lattner229907c2011-07-18 04:54:35 +00002246Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 LocTy Loc) {
2248 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002249 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 // If this is a forward reference for the value, see if we already created a
2252 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002253 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2255 I = ForwardRefValIDs.find(ID);
2256 if (I != ForwardRefValIDs.end())
2257 Val = I->second.first;
2258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 // If we have the value in the symbol table or fwd-ref table, return it.
2261 if (Val) {
2262 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002263 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002264 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002266 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002267 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002268 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002271 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002273 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002275
Chris Lattnerac161bf2009-01-02 07:01:27 +00002276 // Otherwise, create a new forward reference for this value and remember it.
2277 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002278 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002279 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280 else
2281 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002282
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2284 return FwdVal;
2285}
2286
2287/// SetInstName - After an instruction is parsed and inserted into its
2288/// basic block, this installs its name.
2289bool LLParser::PerFunctionState::SetInstName(int NameID,
2290 const std::string &NameStr,
2291 LocTy NameLoc, Instruction *Inst) {
2292 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002293 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 if (NameID != -1 || !NameStr.empty())
2295 return P.Error(NameLoc, "instructions returning void cannot have a name");
2296 return false;
2297 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 // If this was a numbered instruction, verify that the instruction is the
2300 // expected value and resolve any forward references.
2301 if (NameStr.empty()) {
2302 // If neither a name nor an ID was specified, just use the next ID.
2303 if (NameID == -1)
2304 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002305
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306 if (unsigned(NameID) != NumberedVals.size())
2307 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002308 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002309
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2311 ForwardRefValIDs.find(NameID);
2312 if (FI != ForwardRefValIDs.end()) {
2313 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002315 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002317 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002318 ForwardRefValIDs.erase(FI);
2319 }
2320
2321 NumberedVals.push_back(Inst);
2322 return false;
2323 }
2324
2325 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2326 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2327 FI = ForwardRefVals.find(NameStr);
2328 if (FI != ForwardRefVals.end()) {
2329 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002330 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002331 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002333 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 ForwardRefVals.erase(FI);
2335 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002336
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 // Set the name on the instruction.
2338 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002339
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002340 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002341 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 NameStr + "'");
2343 return false;
2344}
2345
2346/// GetBB - Get a basic block with the specified name or ID, creating a
2347/// forward reference record if needed.
2348BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2349 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002350 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2351 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352}
2353
2354BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002355 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2356 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002357}
2358
2359/// DefineBB - Define the specified basic block, which is either named or
2360/// unnamed. If there is an error, this returns null otherwise it returns
2361/// the block being defined.
2362BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2363 LocTy Loc) {
2364 BasicBlock *BB;
2365 if (Name.empty())
2366 BB = GetBB(NumberedVals.size(), Loc);
2367 else
2368 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002369 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 // Move the block to the end of the function. Forward ref'd blocks are
2372 // inserted wherever they happen to be referenced.
2373 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002374
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 // Remove the block from forward ref sets.
2376 if (Name.empty()) {
2377 ForwardRefValIDs.erase(NumberedVals.size());
2378 NumberedVals.push_back(BB);
2379 } else {
2380 // BB forward references are already in the function symbol table.
2381 ForwardRefVals.erase(Name);
2382 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002383
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384 return BB;
2385}
2386
2387//===----------------------------------------------------------------------===//
2388// Constants.
2389//===----------------------------------------------------------------------===//
2390
2391/// ParseValID - Parse an abstract value that doesn't necessarily have a
2392/// type implied. For example, if we parse "4" we don't know what integer type
2393/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002394/// sanity. PFS is used to convert function-local operands of metadata (since
2395/// metadata operands are not just parsed here but also converted to values).
2396/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002397bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 ID.Loc = Lex.getLoc();
2399 switch (Lex.getKind()) {
2400 default: return TokError("expected value token");
2401 case lltok::GlobalID: // @42
2402 ID.UIntVal = Lex.getUIntVal();
2403 ID.Kind = ValID::t_GlobalID;
2404 break;
2405 case lltok::GlobalVar: // @foo
2406 ID.StrVal = Lex.getStrVal();
2407 ID.Kind = ValID::t_GlobalName;
2408 break;
2409 case lltok::LocalVarID: // %42
2410 ID.UIntVal = Lex.getUIntVal();
2411 ID.Kind = ValID::t_LocalID;
2412 break;
2413 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 ID.StrVal = Lex.getStrVal();
2415 ID.Kind = ValID::t_LocalName;
2416 break;
2417 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 ID.Kind = ValID::t_APSInt;
2420 break;
2421 case lltok::APFloat:
2422 ID.APFloatVal = Lex.getAPFloatVal();
2423 ID.Kind = ValID::t_APFloat;
2424 break;
2425 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002426 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 ID.Kind = ValID::t_Constant;
2428 break;
2429 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002430 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 ID.Kind = ValID::t_Constant;
2432 break;
2433 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2434 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2435 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002436
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 case lltok::lbrace: {
2438 // ValID ::= '{' ConstVector '}'
2439 Lex.Lex();
2440 SmallVector<Constant*, 16> Elts;
2441 if (ParseGlobalValueVector(Elts) ||
2442 ParseToken(lltok::rbrace, "expected end of struct constant"))
2443 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444
David Blaikie1b770232015-08-01 05:10:40 +00002445 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002446 ID.UIntVal = Elts.size();
David Blaikie1b770232015-08-01 05:10:40 +00002447 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2448 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002449 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 return false;
2451 }
2452 case lltok::less: {
2453 // ValID ::= '<' ConstVector '>' --> Vector.
2454 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2455 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002456 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 SmallVector<Constant*, 16> Elts;
2459 LocTy FirstEltLoc = Lex.getLoc();
2460 if (ParseGlobalValueVector(Elts) ||
2461 (isPackedStruct &&
2462 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2463 ParseToken(lltok::greater, "expected end of constant"))
2464 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002465
Chris Lattnerac161bf2009-01-02 07:01:27 +00002466 if (isPackedStruct) {
David Blaikie1b770232015-08-01 05:10:40 +00002467 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2468 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2469 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002470 ID.UIntVal = Elts.size();
2471 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 return false;
2473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 if (Elts.empty())
2476 return Error(ID.Loc, "constant vector must not be empty");
2477
Duncan Sands9dff9be2010-02-15 16:12:20 +00002478 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002479 !Elts[0]->getType()->isFloatingPointTy() &&
2480 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002482 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002483
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484 // Verify that all the vector elements have the same type.
2485 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2486 if (Elts[i]->getType() != Elts[0]->getType())
2487 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002488 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002489 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002490
Chris Lattner69229312011-02-15 00:14:00 +00002491 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 ID.Kind = ValID::t_Constant;
2493 return false;
2494 }
2495 case lltok::lsquare: { // Array Constant
2496 Lex.Lex();
2497 SmallVector<Constant*, 16> Elts;
2498 LocTy FirstEltLoc = Lex.getLoc();
2499 if (ParseGlobalValueVector(Elts) ||
2500 ParseToken(lltok::rsquare, "expected end of array constant"))
2501 return true;
2502
2503 // Handle empty element.
2504 if (Elts.empty()) {
2505 // Use undef instead of an array because it's inconvenient to determine
2506 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002507 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 return false;
2509 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002510
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002512 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002513 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
Owen Anderson4056ca92009-07-29 22:17:13 +00002515 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002516
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002518 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 if (Elts[i]->getType() != Elts[0]->getType())
2520 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002521 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002522 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002524
Jay Foad83be3612011-06-22 09:24:39 +00002525 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 ID.Kind = ValID::t_Constant;
2527 return false;
2528 }
2529 case lltok::kw_c: // c "foo"
2530 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002531 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2532 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2534 ID.Kind = ValID::t_Constant;
2535 return false;
2536
2537 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002538 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2539 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002540 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 Lex.Lex();
2542 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002543 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002544 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002545 ParseStringConstant(ID.StrVal) ||
2546 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547 ParseToken(lltok::StringConstant, "expected constraint string"))
2548 return true;
2549 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002550 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002551 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 ID.Kind = ValID::t_InlineAsm;
2553 return false;
2554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
Chris Lattner3432c622009-10-28 03:39:23 +00002556 case lltok::kw_blockaddress: {
2557 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2558 Lex.Lex();
2559
2560 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002561
Chris Lattner3432c622009-10-28 03:39:23 +00002562 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2563 ParseValID(Fn) ||
2564 ParseToken(lltok::comma, "expected comma in block address expression")||
2565 ParseValID(Label) ||
2566 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2567 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002568
Chris Lattner3432c622009-10-28 03:39:23 +00002569 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2570 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002571 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002572 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002573
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002574 // Try to find the function (but skip it if it's forward-referenced).
2575 GlobalValue *GV = nullptr;
2576 if (Fn.Kind == ValID::t_GlobalID) {
2577 if (Fn.UIntVal < NumberedVals.size())
2578 GV = NumberedVals[Fn.UIntVal];
2579 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2580 GV = M->getNamedValue(Fn.StrVal);
2581 }
2582 Function *F = nullptr;
2583 if (GV) {
2584 // Confirm that it's actually a function with a definition.
2585 if (!isa<Function>(GV))
2586 return Error(Fn.Loc, "expected function name in blockaddress");
2587 F = cast<Function>(GV);
2588 if (F->isDeclaration())
2589 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2590 }
2591
2592 if (!F) {
2593 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002594 GlobalValue *&FwdRef =
2595 ForwardRefBlockAddresses.insert(std::make_pair(
2596 std::move(Fn),
2597 std::map<ValID, GlobalValue *>()))
2598 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2599 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002600 if (!FwdRef)
2601 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2602 GlobalValue::InternalLinkage, nullptr, "");
2603 ID.ConstantVal = FwdRef;
2604 ID.Kind = ValID::t_Constant;
2605 return false;
2606 }
2607
2608 // We found the function; now find the basic block. Don't use PFS, since we
2609 // might be inside a constant expression.
2610 BasicBlock *BB;
2611 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2612 if (Label.Kind == ValID::t_LocalID)
2613 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2614 else
2615 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2616 if (!BB)
2617 return Error(Label.Loc, "referenced value is not a basic block");
2618 } else {
2619 if (Label.Kind == ValID::t_LocalID)
2620 return Error(Label.Loc, "cannot take address of numeric label after "
2621 "the function is defined");
2622 BB = dyn_cast_or_null<BasicBlock>(
2623 F->getValueSymbolTable().lookup(Label.StrVal));
2624 if (!BB)
2625 return Error(Label.Loc, "referenced value is not a basic block");
2626 }
2627
2628 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002629 ID.Kind = ValID::t_Constant;
2630 return false;
2631 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002632
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 case lltok::kw_trunc:
2634 case lltok::kw_zext:
2635 case lltok::kw_sext:
2636 case lltok::kw_fptrunc:
2637 case lltok::kw_fpext:
2638 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002639 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640 case lltok::kw_uitofp:
2641 case lltok::kw_sitofp:
2642 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002645 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002646 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002647 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 Constant *SrcVal;
2649 Lex.Lex();
2650 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2651 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002652 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 ParseType(DestTy) ||
2654 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2655 return true;
2656 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2657 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002658 getTypeString(SrcVal->getType()) + "' to '" +
2659 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002660 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002661 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 ID.Kind = ValID::t_Constant;
2663 return false;
2664 }
2665 case lltok::kw_extractvalue: {
2666 Lex.Lex();
2667 Constant *Val;
2668 SmallVector<unsigned, 4> Indices;
2669 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2670 ParseGlobalTypeAndValue(Val) ||
2671 ParseIndexList(Indices) ||
2672 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2673 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002674
Chris Lattner392be582010-02-12 20:49:41 +00002675 if (!Val->getType()->isAggregateType())
2676 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002677 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002678 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002679 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 ID.Kind = ValID::t_Constant;
2681 return false;
2682 }
2683 case lltok::kw_insertvalue: {
2684 Lex.Lex();
2685 Constant *Val0, *Val1;
2686 SmallVector<unsigned, 4> Indices;
2687 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2688 ParseGlobalTypeAndValue(Val0) ||
2689 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2690 ParseGlobalTypeAndValue(Val1) ||
2691 ParseIndexList(Indices) ||
2692 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2693 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002694 if (!Val0->getType()->isAggregateType())
2695 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002696 Type *IndexedType =
2697 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2698 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002700 if (IndexedType != Val1->getType())
2701 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2702 getTypeString(Val1->getType()) +
2703 "' instead of '" + getTypeString(IndexedType) +
2704 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002705 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 ID.Kind = ValID::t_Constant;
2707 return false;
2708 }
2709 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002710 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 unsigned PredVal, Opc = Lex.getUIntVal();
2712 Constant *Val0, *Val1;
2713 Lex.Lex();
2714 if (ParseCmpPredicate(PredVal, Opc) ||
2715 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2716 ParseGlobalTypeAndValue(Val0) ||
2717 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2718 ParseGlobalTypeAndValue(Val1) ||
2719 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2720 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002721
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 if (Val0->getType() != Val1->getType())
2723 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002724
Chris Lattnerac161bf2009-01-02 07:01:27 +00002725 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002726
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002728 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002729 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002730 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002731 } else {
2732 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002733 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002734 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002735 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002736 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002737 }
2738 ID.Kind = ValID::t_Constant;
2739 return false;
2740 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 // Binary Operators.
2743 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002744 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002745 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002746 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002747 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002748 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 case lltok::kw_udiv:
2750 case lltok::kw_sdiv:
2751 case lltok::kw_fdiv:
2752 case lltok::kw_urem:
2753 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002754 case lltok::kw_frem:
2755 case lltok::kw_shl:
2756 case lltok::kw_lshr:
2757 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002758 bool NUW = false;
2759 bool NSW = false;
2760 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 unsigned Opc = Lex.getUIntVal();
2762 Constant *Val0, *Val1;
2763 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002764 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002765 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2766 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002767 if (EatIfPresent(lltok::kw_nuw))
2768 NUW = true;
2769 if (EatIfPresent(lltok::kw_nsw)) {
2770 NSW = true;
2771 if (EatIfPresent(lltok::kw_nuw))
2772 NUW = true;
2773 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002774 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2775 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002776 if (EatIfPresent(lltok::kw_exact))
2777 Exact = true;
2778 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002779 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2780 ParseGlobalTypeAndValue(Val0) ||
2781 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2782 ParseGlobalTypeAndValue(Val1) ||
2783 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2784 return true;
2785 if (Val0->getType() != Val1->getType())
2786 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002787 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002788 if (NUW)
2789 return Error(ModifierLoc, "nuw only applies to integer operations");
2790 if (NSW)
2791 return Error(ModifierLoc, "nsw only applies to integer operations");
2792 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002793 // Check that the type is valid for the operator.
2794 switch (Opc) {
2795 case Instruction::Add:
2796 case Instruction::Sub:
2797 case Instruction::Mul:
2798 case Instruction::UDiv:
2799 case Instruction::SDiv:
2800 case Instruction::URem:
2801 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002802 case Instruction::Shl:
2803 case Instruction::AShr:
2804 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002805 if (!Val0->getType()->isIntOrIntVectorTy())
2806 return Error(ID.Loc, "constexpr requires integer operands");
2807 break;
2808 case Instruction::FAdd:
2809 case Instruction::FSub:
2810 case Instruction::FMul:
2811 case Instruction::FDiv:
2812 case Instruction::FRem:
2813 if (!Val0->getType()->isFPOrFPVectorTy())
2814 return Error(ID.Loc, "constexpr requires fp operands");
2815 break;
2816 default: llvm_unreachable("Unknown binary operator!");
2817 }
Dan Gohman1b849082009-09-07 23:54:19 +00002818 unsigned Flags = 0;
2819 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2820 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002821 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002822 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002823 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 ID.Kind = ValID::t_Constant;
2825 return false;
2826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002827
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 case lltok::kw_and:
2830 case lltok::kw_or:
2831 case lltok::kw_xor: {
2832 unsigned Opc = Lex.getUIntVal();
2833 Constant *Val0, *Val1;
2834 Lex.Lex();
2835 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2836 ParseGlobalTypeAndValue(Val0) ||
2837 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2838 ParseGlobalTypeAndValue(Val1) ||
2839 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2840 return true;
2841 if (Val0->getType() != Val1->getType())
2842 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002843 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 return Error(ID.Loc,
2845 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002846 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 ID.Kind = ValID::t_Constant;
2848 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002849 }
2850
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 case lltok::kw_getelementptr:
2852 case lltok::kw_shufflevector:
2853 case lltok::kw_insertelement:
2854 case lltok::kw_extractelement:
2855 case lltok::kw_select: {
2856 unsigned Opc = Lex.getUIntVal();
2857 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002858 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002859 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002861
Dan Gohman1639c392009-07-27 21:53:46 +00002862 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002863 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002864
2865 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2866 return true;
2867
2868 LocTy ExplicitTypeLoc = Lex.getLoc();
2869 if (Opc == Instruction::GetElementPtr) {
2870 if (ParseType(Ty) ||
2871 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2872 return true;
2873 }
2874
2875 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2877 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002880 if (Elts.size() == 0 ||
2881 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002882 return Error(ID.Loc, "base of getelementptr must be a pointer");
2883
2884 Type *BaseType = Elts[0]->getType();
2885 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002886 if (Ty != BasePointerType->getElementType())
2887 return Error(
2888 ExplicitTypeLoc,
2889 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002890
Jay Foaded8db7d2011-07-21 14:31:17 +00002891 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002892 for (Constant *Val : Indices) {
2893 Type *ValTy = Val->getType();
2894 if (!ValTy->getScalarType()->isIntegerTy())
2895 return Error(ID.Loc, "getelementptr index must be an integer");
2896 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2897 return Error(ID.Loc, "getelementptr index type missmatch");
2898 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002899 unsigned ValNumEl = ValTy->getVectorNumElements();
2900 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00002901 if (ValNumEl != PtrNumEl)
2902 return Error(
2903 ID.Loc,
2904 "getelementptr vector index has a wrong number of elements");
2905 }
2906 }
2907
Craig Toppere3dcce92015-08-01 22:20:21 +00002908 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00002909 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002910 return Error(ID.Loc, "base element of getelementptr must be sized");
2911
David Blaikie4a2e73b2015-04-02 18:55:32 +00002912 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002913 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002914 ID.ConstantVal =
2915 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002916 } else if (Opc == Instruction::Select) {
2917 if (Elts.size() != 3)
2918 return Error(ID.Loc, "expected three operands to select");
2919 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2920 Elts[2]))
2921 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002922 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002923 } else if (Opc == Instruction::ShuffleVector) {
2924 if (Elts.size() != 3)
2925 return Error(ID.Loc, "expected three operands to shufflevector");
2926 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2927 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002928 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002929 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 } else if (Opc == Instruction::ExtractElement) {
2931 if (Elts.size() != 2)
2932 return Error(ID.Loc, "expected two operands to extractelement");
2933 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2934 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002935 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002936 } else {
2937 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2938 if (Elts.size() != 3)
2939 return Error(ID.Loc, "expected three operands to insertelement");
2940 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2941 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002942 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002943 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002945
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 ID.Kind = ValID::t_Constant;
2947 return false;
2948 }
2949 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002950
Chris Lattnerac161bf2009-01-02 07:01:27 +00002951 Lex.Lex();
2952 return false;
2953}
2954
2955/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002956bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002957 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002958 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002959 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002960 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002961 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002962 if (V && !(C = dyn_cast<Constant>(V)))
2963 return Error(ID.Loc, "global values must be constants");
2964 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002965}
2966
Victor Hernandez9d75c962010-01-11 22:31:58 +00002967bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002968 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002969 return ParseType(Ty) ||
2970 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002971}
2972
Rafael Espindola83a362c2015-01-06 22:55:16 +00002973bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002974 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002975
2976 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002977 if (!EatIfPresent(lltok::kw_comdat))
2978 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002979
2980 if (EatIfPresent(lltok::lparen)) {
2981 if (Lex.getKind() != lltok::ComdatVar)
2982 return TokError("expected comdat variable");
2983 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2984 Lex.Lex();
2985 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2986 return true;
2987 } else {
2988 if (GlobalName.empty())
2989 return TokError("comdat cannot be unnamed");
2990 C = getComdat(GlobalName, KwLoc);
2991 }
2992
David Majnemerdad0a642014-06-27 18:19:56 +00002993 return false;
2994}
2995
Victor Hernandez9d75c962010-01-11 22:31:58 +00002996/// ParseGlobalValueVector
2997/// ::= /*empty*/
2998/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002999bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003000 // Empty list.
3001 if (Lex.getKind() == lltok::rbrace ||
3002 Lex.getKind() == lltok::rsquare ||
3003 Lex.getKind() == lltok::greater ||
3004 Lex.getKind() == lltok::rparen)
3005 return false;
3006
3007 Constant *C;
3008 if (ParseGlobalTypeAndValue(C)) return true;
3009 Elts.push_back(C);
3010
3011 while (EatIfPresent(lltok::comma)) {
3012 if (ParseGlobalTypeAndValue(C)) return true;
3013 Elts.push_back(C);
3014 }
3015
3016 return false;
3017}
3018
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003019bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003020 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003021 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003022 return true;
3023
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003024 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003025 return false;
3026}
3027
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003028/// MDNode:
3029/// ::= !{ ... }
3030/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003031/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003032bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003033 if (Lex.getKind() == lltok::MetadataVar)
3034 return ParseSpecializedMDNode(N);
3035
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003036 return ParseToken(lltok::exclaim, "expected '!' here") ||
3037 ParseMDNodeTail(N);
3038}
3039
3040bool LLParser::ParseMDNodeTail(MDNode *&N) {
3041 // !{ ... }
3042 if (Lex.getKind() == lltok::lbrace)
3043 return ParseMDTuple(N);
3044
3045 // !42
3046 return ParseMDNodeID(N);
3047}
3048
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003049namespace {
3050
3051/// Structure to represent an optional metadata field.
3052template <class FieldTy> struct MDFieldImpl {
3053 typedef MDFieldImpl ImplTy;
3054 FieldTy Val;
3055 bool Seen;
3056
3057 void assign(FieldTy Val) {
3058 Seen = true;
3059 this->Val = std::move(Val);
3060 }
3061
3062 explicit MDFieldImpl(FieldTy Default)
3063 : Val(std::move(Default)), Seen(false) {}
3064};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003065
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003066struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3067 uint64_t Max;
3068
3069 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3070 : ImplTy(Default), Max(Max) {}
3071};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003072struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003073 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003074};
3075struct ColumnField : public MDUnsignedField {
3076 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3077};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003078struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003079 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003080 DwarfTagField(dwarf::Tag DefaultTag)
3081 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003082};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003083struct DwarfAttEncodingField : public MDUnsignedField {
3084 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3085};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003086struct DwarfVirtualityField : public MDUnsignedField {
3087 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3088};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003089struct DwarfLangField : public MDUnsignedField {
3090 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3091};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003092
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003093struct DIFlagField : public MDUnsignedField {
3094 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3095};
3096
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003097struct MDSignedField : public MDFieldImpl<int64_t> {
3098 int64_t Min;
3099 int64_t Max;
3100
3101 MDSignedField(int64_t Default = 0)
3102 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3103 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3104 : ImplTy(Default), Min(Min), Max(Max) {}
3105};
3106
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003107struct MDBoolField : public MDFieldImpl<bool> {
3108 MDBoolField(bool Default = false) : ImplTy(Default) {}
3109};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003110struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003111 bool AllowNull;
3112
3113 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003114};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003115struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3116 MDConstant() : ImplTy(nullptr) {}
3117};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003118struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003119 bool AllowEmpty;
3120 MDStringField(bool AllowEmpty = true)
3121 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003122};
3123struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3124 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3125};
3126
3127} // end namespace
3128
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003129namespace llvm {
3130
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003131template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003132bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003133 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003134 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3135 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003136
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003137 auto &U = Lex.getAPSIntVal();
3138 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003139 return TokError("value for '" + Name + "' too large, limit is " +
3140 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003141 Result.assign(U.getZExtValue());
3142 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003143 Lex.Lex();
3144 return false;
3145}
3146
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003147template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003148bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3149 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3150}
3151template <>
3152bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3153 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3154}
3155
3156template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003157bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3158 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003159 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003160
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003161 if (Lex.getKind() != lltok::DwarfTag)
3162 return TokError("expected DWARF tag");
3163
3164 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3165 if (Tag == dwarf::DW_TAG_invalid)
3166 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003167 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003168
3169 Result.assign(Tag);
3170 Lex.Lex();
3171 return false;
3172}
3173
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003174template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003175bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3176 DwarfVirtualityField &Result) {
3177 if (Lex.getKind() == lltok::APSInt)
3178 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3179
3180 if (Lex.getKind() != lltok::DwarfVirtuality)
3181 return TokError("expected DWARF virtuality code");
3182
3183 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3184 if (!Virtuality)
3185 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3186 Lex.getStrVal() + "'");
3187 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3188 Result.assign(Virtuality);
3189 Lex.Lex();
3190 return false;
3191}
3192
3193template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003194bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3195 if (Lex.getKind() == lltok::APSInt)
3196 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3197
3198 if (Lex.getKind() != lltok::DwarfLang)
3199 return TokError("expected DWARF language");
3200
3201 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3202 if (!Lang)
3203 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3204 "'");
3205 assert(Lang <= Result.Max && "Expected valid DWARF language");
3206 Result.assign(Lang);
3207 Lex.Lex();
3208 return false;
3209}
3210
3211template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003212bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003213 DwarfAttEncodingField &Result) {
3214 if (Lex.getKind() == lltok::APSInt)
3215 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3216
3217 if (Lex.getKind() != lltok::DwarfAttEncoding)
3218 return TokError("expected DWARF type attribute encoding");
3219
3220 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3221 if (!Encoding)
3222 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3223 Lex.getStrVal() + "'");
3224 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3225 Result.assign(Encoding);
3226 Lex.Lex();
3227 return false;
3228}
3229
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003230/// DIFlagField
3231/// ::= uint32
3232/// ::= DIFlagVector
3233/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3234template <>
3235bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3236 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3237
3238 // Parser for a single flag.
3239 auto parseFlag = [&](unsigned &Val) {
3240 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3241 return ParseUInt32(Val);
3242
3243 if (Lex.getKind() != lltok::DIFlag)
3244 return TokError("expected debug info flag");
3245
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003246 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003247 if (!Val)
3248 return TokError(Twine("invalid debug info flag flag '") +
3249 Lex.getStrVal() + "'");
3250 Lex.Lex();
3251 return false;
3252 };
3253
3254 // Parse the flags and combine them together.
3255 unsigned Combined = 0;
3256 do {
3257 unsigned Val;
3258 if (parseFlag(Val))
3259 return true;
3260 Combined |= Val;
3261 } while (EatIfPresent(lltok::bar));
3262
3263 Result.assign(Combined);
3264 return false;
3265}
3266
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003267template <>
3268bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003269 MDSignedField &Result) {
3270 if (Lex.getKind() != lltok::APSInt)
3271 return TokError("expected signed integer");
3272
3273 auto &S = Lex.getAPSIntVal();
3274 if (S < Result.Min)
3275 return TokError("value for '" + Name + "' too small, limit is " +
3276 Twine(Result.Min));
3277 if (S > Result.Max)
3278 return TokError("value for '" + Name + "' too large, limit is " +
3279 Twine(Result.Max));
3280 Result.assign(S.getExtValue());
3281 assert(Result.Val >= Result.Min && "Expected value in range");
3282 assert(Result.Val <= Result.Max && "Expected value in range");
3283 Lex.Lex();
3284 return false;
3285}
3286
3287template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003288bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3289 switch (Lex.getKind()) {
3290 default:
3291 return TokError("expected 'true' or 'false'");
3292 case lltok::kw_true:
3293 Result.assign(true);
3294 break;
3295 case lltok::kw_false:
3296 Result.assign(false);
3297 break;
3298 }
3299 Lex.Lex();
3300 return false;
3301}
3302
3303template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003304bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003305 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003306 if (!Result.AllowNull)
3307 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003308 Lex.Lex();
3309 Result.assign(nullptr);
3310 return false;
3311 }
3312
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003313 Metadata *MD;
3314 if (ParseMetadata(MD, nullptr))
3315 return true;
3316
3317 Result.assign(MD);
3318 return false;
3319}
3320
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003321template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003322bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3323 Metadata *MD;
3324 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3325 return true;
3326
3327 Result.assign(cast<ConstantAsMetadata>(MD));
3328 return false;
3329}
3330
3331template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003332bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003333 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003334 std::string S;
3335 if (ParseStringConstant(S))
3336 return true;
3337
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003338 if (!Result.AllowEmpty && S.empty())
3339 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3340
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003341 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003342 return false;
3343}
3344
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003345template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003346bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3347 SmallVector<Metadata *, 4> MDs;
3348 if (ParseMDNodeVector(MDs))
3349 return true;
3350
3351 Result.assign(std::move(MDs));
3352 return false;
3353}
3354
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003355} // end namespace llvm
3356
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003357template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003358bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003359 do {
3360 if (Lex.getKind() != lltok::LabelStr)
3361 return TokError("expected field label here");
3362
3363 if (parseField())
3364 return true;
3365 } while (EatIfPresent(lltok::comma));
3366
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003367 return false;
3368}
3369
3370template <class ParserTy>
3371bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3372 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3373 Lex.Lex();
3374
3375 if (ParseToken(lltok::lparen, "expected '(' here"))
3376 return true;
3377 if (Lex.getKind() != lltok::rparen)
3378 if (ParseMDFieldsImplBody(parseField))
3379 return true;
3380
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003381 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003382 return ParseToken(lltok::rparen, "expected ')' here");
3383}
3384
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003385template <class FieldTy>
3386bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3387 if (Result.Seen)
3388 return TokError("field '" + Name + "' cannot be specified more than once");
3389
3390 LocTy Loc = Lex.getLoc();
3391 Lex.Lex();
3392 return ParseMDField(Loc, Name, Result);
3393}
3394
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003395bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3396 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003397
3398#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003399 if (Lex.getStrVal() == #CLASS) \
3400 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003401#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003402
3403 return TokError("expected metadata type");
3404}
3405
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003406#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3407#define NOP_FIELD(NAME, TYPE, INIT)
3408#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3409 if (!NAME.Seen) \
3410 return Error(ClosingLoc, "missing required field '" #NAME "'");
3411#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003412 if (Lex.getStrVal() == #NAME) \
3413 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003414#define PARSE_MD_FIELDS() \
3415 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3416 do { \
3417 LocTy ClosingLoc; \
3418 if (ParseMDFieldsImpl([&]() -> bool { \
3419 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3420 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3421 }, ClosingLoc)) \
3422 return true; \
3423 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3424 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003425#define GET_OR_DISTINCT(CLASS, ARGS) \
3426 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003427
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003428/// ParseDILocationFields:
3429/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3430bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003431#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003432 OPTIONAL(line, LineField, ); \
3433 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003434 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003435 OPTIONAL(inlinedAt, MDField, );
3436 PARSE_MD_FIELDS();
3437#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003438
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003439 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003440 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003441 return false;
3442}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003443
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003444/// ParseGenericDINode:
3445/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3446bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003447#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003448 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003449 OPTIONAL(header, MDStringField, ); \
3450 OPTIONAL(operands, MDFieldList, );
3451 PARSE_MD_FIELDS();
3452#undef VISIT_MD_FIELDS
3453
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003454 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003455 (Context, tag.Val, header.Val, operands.Val));
3456 return false;
3457}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003458
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003459/// ParseDISubrange:
3460/// ::= !DISubrange(count: 30, lowerBound: 2)
3461bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003462#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003463 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003464 OPTIONAL(lowerBound, MDSignedField, );
3465 PARSE_MD_FIELDS();
3466#undef VISIT_MD_FIELDS
3467
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003468 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003469 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003470}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003471
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003472/// ParseDIEnumerator:
3473/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3474bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003475#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003476 REQUIRED(name, MDStringField, ); \
3477 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003478 PARSE_MD_FIELDS();
3479#undef VISIT_MD_FIELDS
3480
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003481 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003482 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003483}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003484
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003485/// ParseDIBasicType:
3486/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3487bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003488#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003489 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003490 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003491 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3492 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003493 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003494 PARSE_MD_FIELDS();
3495#undef VISIT_MD_FIELDS
3496
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003497 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003498 align.Val, encoding.Val));
3499 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003500}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003501
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003502/// ParseDIDerivedType:
3503/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003504/// line: 7, scope: !1, baseType: !2, size: 32,
3505/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003506bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003507#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3508 REQUIRED(tag, DwarfTagField, ); \
3509 OPTIONAL(name, MDStringField, ); \
3510 OPTIONAL(file, MDField, ); \
3511 OPTIONAL(line, LineField, ); \
3512 OPTIONAL(scope, MDField, ); \
3513 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003514 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3515 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3516 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003517 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003518 OPTIONAL(extraData, MDField, );
3519 PARSE_MD_FIELDS();
3520#undef VISIT_MD_FIELDS
3521
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003522 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003523 (Context, tag.Val, name.Val, file.Val, line.Val,
3524 scope.Val, baseType.Val, size.Val, align.Val,
3525 offset.Val, flags.Val, extraData.Val));
3526 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003527}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003528
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003529bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003530#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3531 REQUIRED(tag, DwarfTagField, ); \
3532 OPTIONAL(name, MDStringField, ); \
3533 OPTIONAL(file, MDField, ); \
3534 OPTIONAL(line, LineField, ); \
3535 OPTIONAL(scope, MDField, ); \
3536 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003537 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3538 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3539 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003540 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003541 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003542 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003543 OPTIONAL(vtableHolder, MDField, ); \
3544 OPTIONAL(templateParams, MDField, ); \
3545 OPTIONAL(identifier, MDStringField, );
3546 PARSE_MD_FIELDS();
3547#undef VISIT_MD_FIELDS
3548
3549 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003550 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003551 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3552 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3553 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3554 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003555}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003556
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003557bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003558#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003559 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003560 REQUIRED(types, MDField, );
3561 PARSE_MD_FIELDS();
3562#undef VISIT_MD_FIELDS
3563
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003564 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003565 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003566}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003567
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003568/// ParseDIFileType:
3569/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3570bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003571#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3572 REQUIRED(filename, MDStringField, ); \
3573 REQUIRED(directory, MDStringField, );
3574 PARSE_MD_FIELDS();
3575#undef VISIT_MD_FIELDS
3576
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003577 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003578 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003579}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003580
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003581/// ParseDICompileUnit:
3582/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003583/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3584/// splitDebugFilename: "abc.debug", emissionKind: 1,
3585/// enums: !1, retainedTypes: !2, subprograms: !3,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003586/// globals: !4, imports: !5, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003587bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003588#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3589 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003590 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003591 OPTIONAL(producer, MDStringField, ); \
3592 OPTIONAL(isOptimized, MDBoolField, ); \
3593 OPTIONAL(flags, MDStringField, ); \
3594 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3595 OPTIONAL(splitDebugFilename, MDStringField, ); \
3596 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3597 OPTIONAL(enums, MDField, ); \
3598 OPTIONAL(retainedTypes, MDField, ); \
3599 OPTIONAL(subprograms, MDField, ); \
3600 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003601 OPTIONAL(imports, MDField, ); \
3602 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003603 PARSE_MD_FIELDS();
3604#undef VISIT_MD_FIELDS
3605
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003606 Result = GET_OR_DISTINCT(DICompileUnit,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003607 (Context, language.Val, file.Val, producer.Val,
3608 isOptimized.Val, flags.Val, runtimeVersion.Val,
3609 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3610 retainedTypes.Val, subprograms.Val, globals.Val,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003611 imports.Val, dwoId.Val));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003612 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003613}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003614
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003615/// ParseDISubprogram:
3616/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003617/// file: !1, line: 7, type: !2, isLocal: false,
3618/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003619/// virtuality: DW_VIRTUALTIY_pure_virtual,
3620/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003621/// isOptimized: false, function: void ()* @_Z3foov,
3622/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003623bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003624#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3625 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003626 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003627 OPTIONAL(linkageName, MDStringField, ); \
3628 OPTIONAL(file, MDField, ); \
3629 OPTIONAL(line, LineField, ); \
3630 OPTIONAL(type, MDField, ); \
3631 OPTIONAL(isLocal, MDBoolField, ); \
3632 OPTIONAL(isDefinition, MDBoolField, (true)); \
3633 OPTIONAL(scopeLine, LineField, ); \
3634 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003635 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003636 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003637 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003638 OPTIONAL(isOptimized, MDBoolField, ); \
3639 OPTIONAL(function, MDConstant, ); \
3640 OPTIONAL(templateParams, MDField, ); \
3641 OPTIONAL(declaration, MDField, ); \
3642 OPTIONAL(variables, MDField, );
3643 PARSE_MD_FIELDS();
3644#undef VISIT_MD_FIELDS
3645
3646 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003647 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003648 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3649 scopeLine.Val, containingType.Val, virtuality.Val,
3650 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3651 templateParams.Val, declaration.Val, variables.Val));
3652 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003653}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003654
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003655/// ParseDILexicalBlock:
3656/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3657bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003658#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003659 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003660 OPTIONAL(file, MDField, ); \
3661 OPTIONAL(line, LineField, ); \
3662 OPTIONAL(column, ColumnField, );
3663 PARSE_MD_FIELDS();
3664#undef VISIT_MD_FIELDS
3665
3666 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003667 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003668 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003669}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003670
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003671/// ParseDILexicalBlockFile:
3672/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3673bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003674#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003675 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003676 OPTIONAL(file, MDField, ); \
3677 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3678 PARSE_MD_FIELDS();
3679#undef VISIT_MD_FIELDS
3680
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003681 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003682 (Context, scope.Val, file.Val, discriminator.Val));
3683 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003684}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003685
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003686/// ParseDINamespace:
3687/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3688bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003689#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3690 REQUIRED(scope, MDField, ); \
3691 OPTIONAL(file, MDField, ); \
3692 OPTIONAL(name, MDStringField, ); \
3693 OPTIONAL(line, LineField, );
3694 PARSE_MD_FIELDS();
3695#undef VISIT_MD_FIELDS
3696
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003697 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003698 (Context, scope.Val, file.Val, name.Val, line.Val));
3699 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003700}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003701
Adrian Prantlab1243f2015-06-29 23:03:47 +00003702/// ParseDIModule:
3703/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3704/// includePath: "/usr/include", isysroot: "/")
3705bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3706#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3707 REQUIRED(scope, MDField, ); \
3708 REQUIRED(name, MDStringField, ); \
3709 OPTIONAL(configMacros, MDStringField, ); \
3710 OPTIONAL(includePath, MDStringField, ); \
3711 OPTIONAL(isysroot, MDStringField, );
3712 PARSE_MD_FIELDS();
3713#undef VISIT_MD_FIELDS
3714
3715 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3716 configMacros.Val, includePath.Val, isysroot.Val));
3717 return false;
3718}
3719
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003720/// ParseDITemplateTypeParameter:
3721/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3722bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003723#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003724 OPTIONAL(name, MDStringField, ); \
3725 REQUIRED(type, MDField, );
3726 PARSE_MD_FIELDS();
3727#undef VISIT_MD_FIELDS
3728
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003729 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003730 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003731 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003732}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003733
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003734/// ParseDITemplateValueParameter:
3735/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003736/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003737bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003738#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003739 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003740 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003741 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003742 REQUIRED(value, MDField, );
3743 PARSE_MD_FIELDS();
3744#undef VISIT_MD_FIELDS
3745
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003746 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003747 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003748 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003749}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003750
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003751/// ParseDIGlobalVariable:
3752/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003753/// file: !1, line: 7, type: !2, isLocal: false,
3754/// isDefinition: true, variable: i32* @foo,
3755/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003756bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003757#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003758 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003759 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003760 OPTIONAL(linkageName, MDStringField, ); \
3761 OPTIONAL(file, MDField, ); \
3762 OPTIONAL(line, LineField, ); \
3763 OPTIONAL(type, MDField, ); \
3764 OPTIONAL(isLocal, MDBoolField, ); \
3765 OPTIONAL(isDefinition, MDBoolField, (true)); \
3766 OPTIONAL(variable, MDConstant, ); \
3767 OPTIONAL(declaration, MDField, );
3768 PARSE_MD_FIELDS();
3769#undef VISIT_MD_FIELDS
3770
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003771 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003772 (Context, scope.Val, name.Val, linkageName.Val,
3773 file.Val, line.Val, type.Val, isLocal.Val,
3774 isDefinition.Val, variable.Val, declaration.Val));
3775 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003776}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003777
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003778/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003779/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3780/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3781/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003782/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003784#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003785 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003786 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003787 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003788 OPTIONAL(file, MDField, ); \
3789 OPTIONAL(line, LineField, ); \
3790 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003791 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003792 PARSE_MD_FIELDS();
3793#undef VISIT_MD_FIELDS
3794
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003795 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003796 (Context, scope.Val, name.Val, file.Val, line.Val,
3797 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003798 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003799}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003800
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003801/// ParseDIExpression:
3802/// ::= !DIExpression(0, 7, -1)
3803bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003804 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3805 Lex.Lex();
3806
3807 if (ParseToken(lltok::lparen, "expected '(' here"))
3808 return true;
3809
3810 SmallVector<uint64_t, 8> Elements;
3811 if (Lex.getKind() != lltok::rparen)
3812 do {
3813 if (Lex.getKind() == lltok::DwarfOp) {
3814 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3815 Lex.Lex();
3816 Elements.push_back(Op);
3817 continue;
3818 }
3819 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3820 }
3821
3822 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3823 return TokError("expected unsigned integer");
3824
3825 auto &U = Lex.getAPSIntVal();
3826 if (U.ugt(UINT64_MAX))
3827 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3828 Elements.push_back(U.getZExtValue());
3829 Lex.Lex();
3830 } while (EatIfPresent(lltok::comma));
3831
3832 if (ParseToken(lltok::rparen, "expected ')' here"))
3833 return true;
3834
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003835 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003836 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003837}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003838
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003839/// ParseDIObjCProperty:
3840/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003841/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003842bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003843#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003844 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003845 OPTIONAL(file, MDField, ); \
3846 OPTIONAL(line, LineField, ); \
3847 OPTIONAL(setter, MDStringField, ); \
3848 OPTIONAL(getter, MDStringField, ); \
3849 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3850 OPTIONAL(type, MDField, );
3851 PARSE_MD_FIELDS();
3852#undef VISIT_MD_FIELDS
3853
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003854 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003855 (Context, name.Val, file.Val, line.Val, setter.Val,
3856 getter.Val, attributes.Val, type.Val));
3857 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003858}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003859
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003860/// ParseDIImportedEntity:
3861/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003862/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003863bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003864#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3865 REQUIRED(tag, DwarfTagField, ); \
3866 REQUIRED(scope, MDField, ); \
3867 OPTIONAL(entity, MDField, ); \
3868 OPTIONAL(line, LineField, ); \
3869 OPTIONAL(name, MDStringField, );
3870 PARSE_MD_FIELDS();
3871#undef VISIT_MD_FIELDS
3872
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003873 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003874 entity.Val, line.Val, name.Val));
3875 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003876}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003877
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003878#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003879#undef NOP_FIELD
3880#undef REQUIRE_FIELD
3881#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003882
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003883/// ParseMetadataAsValue
3884/// ::= metadata i32 %local
3885/// ::= metadata i32 @global
3886/// ::= metadata i32 7
3887/// ::= metadata !0
3888/// ::= metadata !{...}
3889/// ::= metadata !"string"
3890bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3891 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003892 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003893 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003894 return true;
3895
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003896 V = MetadataAsValue::get(Context, MD);
3897 return false;
3898}
3899
3900/// ParseValueAsMetadata
3901/// ::= i32 %local
3902/// ::= i32 @global
3903/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003904bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3905 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003906 Type *Ty;
3907 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003908 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003909 return true;
3910 if (Ty->isMetadataTy())
3911 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3912
3913 Value *V;
3914 if (ParseValue(Ty, V, PFS))
3915 return true;
3916
3917 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003918 return false;
3919}
3920
3921/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003922/// ::= i32 %local
3923/// ::= i32 @global
3924/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003925/// ::= !42
3926/// ::= !{...}
3927/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003928/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003929bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003930 if (Lex.getKind() == lltok::MetadataVar) {
3931 MDNode *N;
3932 if (ParseSpecializedMDNode(N))
3933 return true;
3934 MD = N;
3935 return false;
3936 }
3937
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003938 // ValueAsMetadata:
3939 // <type> <value>
3940 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003941 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003942
3943 // '!'.
3944 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3945 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003946
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003947 // MDString:
3948 // ::= '!' STRINGCONSTANT
3949 if (Lex.getKind() == lltok::StringConstant) {
3950 MDString *S;
3951 if (ParseMDString(S))
3952 return true;
3953 MD = S;
3954 return false;
3955 }
3956
Dan Gohman8939ba332010-07-14 18:26:50 +00003957 // MDNode:
3958 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003959 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003960 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003961 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003962 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003963 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003964 return false;
3965}
3966
Victor Hernandez9d75c962010-01-11 22:31:58 +00003967
3968//===----------------------------------------------------------------------===//
3969// Function Parsing.
3970//===----------------------------------------------------------------------===//
3971
Chris Lattner229907c2011-07-18 04:54:35 +00003972bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003973 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003974 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003975 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003976
Chris Lattnerac161bf2009-01-02 07:01:27 +00003977 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003979 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3980 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003981 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003982 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003983 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3984 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003985 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003986 case ValID::t_InlineAsm: {
David Blaikie41ba2b42015-07-27 23:32:19 +00003987 assert(ID.FTy);
3988 if (!InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00003989 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00003990 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
3991 (ID.UIntVal >> 1) & 1,
3992 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003993 return false;
3994 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003995 case ValID::t_GlobalName:
3996 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003997 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003998 case ValID::t_GlobalID:
3999 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004000 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004001 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004002 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004003 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004004 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004005 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 return false;
4007 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004008 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004009 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4010 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004011
Dan Gohman518cda42011-12-17 00:04:22 +00004012 // The lexer has no type info, so builds all half, float, and double FP
4013 // constants as double. Fix this here. Long double does not need this.
4014 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004015 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004016 if (Ty->isHalfTy())
4017 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4018 &Ignored);
4019 else if (Ty->isFloatTy())
4020 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4021 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004022 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004023 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004024
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004025 if (V->getType() != Ty)
4026 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004027 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004028
Chris Lattnerac161bf2009-01-02 07:01:27 +00004029 return false;
4030 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004031 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004032 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004033 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004034 return false;
4035 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004036 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004037 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004038 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004039 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004040 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004041 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004042 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004043 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004044 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004045 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004046 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004047 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004048 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004049 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004050 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004051 return false;
4052 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004053 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004054 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004055
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056 V = ID.ConstantVal;
4057 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004058 case ValID::t_ConstantStruct:
4059 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004060 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004061 if (ST->getNumElements() != ID.UIntVal)
4062 return Error(ID.Loc,
4063 "initializer with struct type has wrong # elements");
4064 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4065 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004066
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004067 // Verify that the elements are compatible with the structtype.
4068 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4069 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4070 return Error(ID.Loc, "element " + Twine(i) +
4071 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004072
David Blaikie1b770232015-08-01 05:10:40 +00004073 V = ConstantStruct::get(
4074 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004075 } else
4076 return Error(ID.Loc, "constant expression type mismatch");
4077 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004078 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004079 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004081
Alex Lorenzd2255952015-07-17 22:07:03 +00004082bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4083 C = nullptr;
4084 ValID ID;
4085 auto Loc = Lex.getLoc();
4086 if (ParseValID(ID, /*PFS=*/nullptr))
4087 return true;
4088 switch (ID.Kind) {
4089 case ValID::t_APSInt:
4090 case ValID::t_APFloat:
4091 case ValID::t_Constant:
4092 case ValID::t_ConstantStruct:
4093 case ValID::t_PackedConstantStruct: {
4094 Value *V;
4095 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4096 return true;
4097 assert(isa<Constant>(V) && "Expected a constant value");
4098 C = cast<Constant>(V);
4099 return false;
4100 }
4101 default:
4102 return Error(Loc, "expected a constant value");
4103 }
4104}
4105
Chris Lattner229907c2011-07-18 04:54:35 +00004106bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004107 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004108 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004109 return ParseValID(ID, PFS) ||
4110 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004111}
4112
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004113bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004114 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004115 return ParseType(Ty) ||
4116 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004117}
4118
Chris Lattner3ed871f2009-10-27 19:13:16 +00004119bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4120 PerFunctionState &PFS) {
4121 Value *V;
4122 Loc = Lex.getLoc();
4123 if (ParseTypeAndValue(V, PFS)) return true;
4124 if (!isa<BasicBlock>(V))
4125 return Error(Loc, "expected a basic block");
4126 BB = cast<BasicBlock>(V);
4127 return false;
4128}
4129
4130
Chris Lattnerac161bf2009-01-02 07:01:27 +00004131/// FunctionHeader
4132/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004133/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004134/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004135bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4136 // Parse the linkage.
4137 LocTy LinkageLoc = Lex.getLoc();
4138 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004139
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004140 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004141 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004142 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004143 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004144 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004145 LocTy RetTypeLoc = Lex.getLoc();
4146 if (ParseOptionalLinkage(Linkage) ||
4147 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004148 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004149 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004150 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004151 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004152 return true;
4153
4154 // Verify that the linkage is ok.
4155 switch ((GlobalValue::LinkageTypes)Linkage) {
4156 case GlobalValue::ExternalLinkage:
4157 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004158 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004159 if (isDefine)
4160 return Error(LinkageLoc, "invalid linkage for function definition");
4161 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004162 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004163 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004164 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004165 case GlobalValue::LinkOnceAnyLinkage:
4166 case GlobalValue::LinkOnceODRLinkage:
4167 case GlobalValue::WeakAnyLinkage:
4168 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004169 if (!isDefine)
4170 return Error(LinkageLoc, "invalid linkage for function declaration");
4171 break;
4172 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004173 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004174 return Error(LinkageLoc, "invalid function linkage type");
4175 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004176
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004177 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4178 return Error(LinkageLoc,
4179 "symbol with local linkage must have default visibility");
4180
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004181 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004182 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004183
Chris Lattnerac161bf2009-01-02 07:01:27 +00004184 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004185
4186 std::string FunctionName;
4187 if (Lex.getKind() == lltok::GlobalVar) {
4188 FunctionName = Lex.getStrVal();
4189 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4190 unsigned NameID = Lex.getUIntVal();
4191
4192 if (NameID != NumberedVals.size())
4193 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004194 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004195 } else {
4196 return TokError("expected function name");
4197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004198
Chris Lattner3822f632009-01-02 08:05:26 +00004199 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004200
Chris Lattner3822f632009-01-02 08:05:26 +00004201 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004202 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004203
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004204 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004205 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004206 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004207 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004208 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004209 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004211 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004212 bool UnnamedAddr;
4213 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004214 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004215 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004216 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004217 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004218
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004219 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004220 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4221 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004222 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004223 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004224 (EatIfPresent(lltok::kw_section) &&
4225 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004226 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004227 ParseOptionalAlignment(Alignment) ||
4228 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004229 ParseStringConstant(GC)) ||
4230 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004231 ParseGlobalTypeAndValue(Prefix)) ||
4232 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004233 ParseGlobalTypeAndValue(Prologue)) ||
4234 (EatIfPresent(lltok::kw_personality) &&
4235 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004236 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004237
Michael Gottesman41748d72013-06-27 00:25:01 +00004238 if (FuncAttrs.contains(Attribute::Builtin))
4239 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004240
Chris Lattnerac161bf2009-01-02 07:01:27 +00004241 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004242 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004243 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004244 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004245 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004246
Chris Lattnerac161bf2009-01-02 07:01:27 +00004247 // Okay, if we got here, the function is syntactically valid. Convert types
4248 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004249 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004250 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004251
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004252 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004253 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4254 AttributeSet::ReturnIndex,
4255 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004256
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004258 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004259 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4260 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004261 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4262 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004263 }
4264
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004265 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004266 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4267 AttributeSet::FunctionIndex,
4268 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004269
Bill Wendlinge94d8432012-12-07 23:16:57 +00004270 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004271
Bill Wendling749a43d2012-12-30 13:50:49 +00004272 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004273 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4274
Chris Lattner229907c2011-07-18 04:54:35 +00004275 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004276 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004277 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004278
Craig Topper2617dcc2014-04-15 06:32:26 +00004279 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004280 if (!FunctionName.empty()) {
4281 // If this was a definition of a forward reference, remove the definition
4282 // from the forward reference table and fill in the forward ref.
4283 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4284 ForwardRefVals.find(FunctionName);
4285 if (FRVI != ForwardRefVals.end()) {
4286 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004287 if (!Fn)
4288 return Error(FRVI->second.second, "invalid forward reference to "
4289 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004290 if (Fn->getType() != PFT)
4291 return Error(FRVI->second.second, "invalid forward reference to "
4292 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004293
Chris Lattnerac161bf2009-01-02 07:01:27 +00004294 ForwardRefVals.erase(FRVI);
4295 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004296 // Reject redefinitions.
4297 return Error(NameLoc, "invalid redefinition of function '" +
4298 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004299 } else if (M->getNamedValue(FunctionName)) {
4300 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004302
Dan Gohman399d6ae2009-08-29 23:37:49 +00004303 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304 // If this is a definition of a forward referenced function, make sure the
4305 // types agree.
4306 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4307 = ForwardRefValIDs.find(NumberedVals.size());
4308 if (I != ForwardRefValIDs.end()) {
4309 Fn = cast<Function>(I->second.first);
4310 if (Fn->getType() != PFT)
4311 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004312 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004313 ForwardRefValIDs.erase(I);
4314 }
4315 }
4316
Craig Topper2617dcc2014-04-15 06:32:26 +00004317 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004318 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4319 else // Move the forward-reference to the correct spot in the module.
4320 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4321
4322 if (FunctionName.empty())
4323 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004324
Chris Lattnerac161bf2009-01-02 07:01:27 +00004325 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4326 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004327 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328 Fn->setCallingConv(CC);
4329 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004330 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004331 Fn->setAlignment(Alignment);
4332 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004333 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004334 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004336 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004337 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004338 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004339
Chris Lattnerac161bf2009-01-02 07:01:27 +00004340 // Add all of the arguments we parsed to the function.
4341 Function::arg_iterator ArgIt = Fn->arg_begin();
4342 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4343 // If the argument has a name, insert it into the argument symbol table.
4344 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004345
Chris Lattnerac161bf2009-01-02 07:01:27 +00004346 // Set the name, if it conflicted, it will be auto-renamed.
4347 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004348
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004349 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4351 ArgList[i].Name + "'");
4352 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004353
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004354 if (isDefine)
4355 return false;
4356
Robin Morisset039781e2014-08-29 21:53:01 +00004357 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004358 ValID ID;
4359 if (FunctionName.empty()) {
4360 ID.Kind = ValID::t_GlobalID;
4361 ID.UIntVal = NumberedVals.size() - 1;
4362 } else {
4363 ID.Kind = ValID::t_GlobalName;
4364 ID.StrVal = FunctionName;
4365 }
4366 auto Blocks = ForwardRefBlockAddresses.find(ID);
4367 if (Blocks != ForwardRefBlockAddresses.end())
4368 return Error(Blocks->first.Loc,
4369 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004370 return false;
4371}
4372
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004373bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4374 ValID ID;
4375 if (FunctionNumber == -1) {
4376 ID.Kind = ValID::t_GlobalName;
4377 ID.StrVal = F.getName();
4378 } else {
4379 ID.Kind = ValID::t_GlobalID;
4380 ID.UIntVal = FunctionNumber;
4381 }
4382
4383 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4384 if (Blocks == P.ForwardRefBlockAddresses.end())
4385 return false;
4386
4387 for (const auto &I : Blocks->second) {
4388 const ValID &BBID = I.first;
4389 GlobalValue *GV = I.second;
4390
4391 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4392 "Expected local id or name");
4393 BasicBlock *BB;
4394 if (BBID.Kind == ValID::t_LocalName)
4395 BB = GetBB(BBID.StrVal, BBID.Loc);
4396 else
4397 BB = GetBB(BBID.UIntVal, BBID.Loc);
4398 if (!BB)
4399 return P.Error(BBID.Loc, "referenced value is not a basic block");
4400
4401 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4402 GV->eraseFromParent();
4403 }
4404
4405 P.ForwardRefBlockAddresses.erase(Blocks);
4406 return false;
4407}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408
4409/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004410/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004411bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004412 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004413 return TokError("expected '{' in function body");
4414 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004415
Chris Lattner3432c622009-10-28 03:39:23 +00004416 int FunctionNumber = -1;
4417 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004418
Chris Lattner3432c622009-10-28 03:39:23 +00004419 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004420
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004421 // Resolve block addresses and allow basic blocks to be forward-declared
4422 // within this function.
4423 if (PFS.resolveForwardRefBlockAddresses())
4424 return true;
4425 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4426
Chris Lattnerbbddd962010-01-09 19:20:07 +00004427 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004428 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004429 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004430
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004431 while (Lex.getKind() != lltok::rbrace &&
4432 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004433 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004434
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004435 while (Lex.getKind() != lltok::rbrace)
4436 if (ParseUseListOrder(&PFS))
4437 return true;
4438
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 // Eat the }.
4440 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004441
Chris Lattnerac161bf2009-01-02 07:01:27 +00004442 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004443 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004444}
4445
4446/// ParseBasicBlock
4447/// ::= LabelStr? Instruction*
4448bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4449 // If this basic block starts out with a name, remember it.
4450 std::string Name;
4451 LocTy NameLoc = Lex.getLoc();
4452 if (Lex.getKind() == lltok::LabelStr) {
4453 Name = Lex.getStrVal();
4454 Lex.Lex();
4455 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004456
Chris Lattnerac161bf2009-01-02 07:01:27 +00004457 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004458 if (!BB)
4459 return Error(NameLoc,
4460 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004461
Chris Lattnerac161bf2009-01-02 07:01:27 +00004462 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004463
Chris Lattnerac161bf2009-01-02 07:01:27 +00004464 // Parse the instructions in this block until we get a terminator.
4465 Instruction *Inst;
4466 do {
4467 // This instruction may have three possibilities for a name: a) none
4468 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4469 LocTy NameLoc = Lex.getLoc();
4470 int NameID = -1;
4471 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004472
Chris Lattnerac161bf2009-01-02 07:01:27 +00004473 if (Lex.getKind() == lltok::LocalVarID) {
4474 NameID = Lex.getUIntVal();
4475 Lex.Lex();
4476 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4477 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004478 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004479 NameStr = Lex.getStrVal();
4480 Lex.Lex();
4481 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4482 return true;
4483 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004484
Chris Lattner77b89dc2009-12-30 05:23:43 +00004485 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004486 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004487 case InstError: return true;
4488 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004489 BB->getInstList().push_back(Inst);
4490
Chris Lattner77b89dc2009-12-30 05:23:43 +00004491 // With a normal result, we check to see if the instruction is followed by
4492 // a comma and metadata.
4493 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004494 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004495 return true;
4496 break;
4497 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004498 BB->getInstList().push_back(Inst);
4499
Chris Lattner77b89dc2009-12-30 05:23:43 +00004500 // If the instruction parser ate an extra comma at the end of it, it
4501 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004502 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004503 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004504 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004505 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004506
Chris Lattnerac161bf2009-01-02 07:01:27 +00004507 // Set the name on the instruction.
4508 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4509 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004510
Chris Lattnerac161bf2009-01-02 07:01:27 +00004511 return false;
4512}
4513
4514//===----------------------------------------------------------------------===//
4515// Instruction Parsing.
4516//===----------------------------------------------------------------------===//
4517
4518/// ParseInstruction - Parse one of the many different instructions.
4519///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004520int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4521 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004522 lltok::Kind Token = Lex.getKind();
4523 if (Token == lltok::Eof)
4524 return TokError("found end of file when expecting more instructions");
4525 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004526 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004527 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004528
Chris Lattnerac161bf2009-01-02 07:01:27 +00004529 switch (Token) {
4530 default: return Error(Loc, "expected instruction opcode");
4531 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004532 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4534 case lltok::kw_br: return ParseBr(Inst, PFS);
4535 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004536 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004538 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004539 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4540 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4541 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4542 case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4543 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4544 case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 // Binary Operators.
4546 case lltok::kw_add:
4547 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004548 case lltok::kw_mul:
4549 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004550 bool NUW = EatIfPresent(lltok::kw_nuw);
4551 bool NSW = EatIfPresent(lltok::kw_nsw);
4552 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004553
Chris Lattnera676c0f2011-02-07 16:40:21 +00004554 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004555
Chris Lattnera676c0f2011-02-07 16:40:21 +00004556 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4557 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4558 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004559 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004560 case lltok::kw_fadd:
4561 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004562 case lltok::kw_fmul:
4563 case lltok::kw_fdiv:
4564 case lltok::kw_frem: {
4565 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4566 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4567 if (Res != 0)
4568 return Res;
4569 if (FMF.any())
4570 Inst->setFastMathFlags(FMF);
4571 return 0;
4572 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004573
Chris Lattner35315d02011-02-06 21:44:57 +00004574 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004575 case lltok::kw_udiv:
4576 case lltok::kw_lshr:
4577 case lltok::kw_ashr: {
4578 bool Exact = EatIfPresent(lltok::kw_exact);
4579
4580 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4581 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4582 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004583 }
4584
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004586 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004587 case lltok::kw_and:
4588 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004589 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004590 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4591 case lltok::kw_fcmp: {
4592 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4593 int Res = ParseCompare(Inst, PFS, KeywordVal);
4594 if (Res != 0)
4595 return Res;
4596 if (FMF.any())
4597 Inst->setFastMathFlags(FMF);
4598 return 0;
4599 }
4600
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 // Casts.
4602 case lltok::kw_trunc:
4603 case lltok::kw_zext:
4604 case lltok::kw_sext:
4605 case lltok::kw_fptrunc:
4606 case lltok::kw_fpext:
4607 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004608 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609 case lltok::kw_uitofp:
4610 case lltok::kw_sitofp:
4611 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004612 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004613 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004614 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615 // Other.
4616 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004617 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004618 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4619 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4620 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4621 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004622 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004623 // Call.
4624 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4625 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4626 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004628 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004629 case lltok::kw_load: return ParseLoad(Inst, PFS);
4630 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004631 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4632 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004633 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4635 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4636 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4637 }
4638}
4639
4640/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4641bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004642 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004644 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4646 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4647 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4648 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4649 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4650 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4651 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4652 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4653 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4654 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4655 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4656 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4657 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4658 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4659 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4660 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4661 }
4662 } else {
4663 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004664 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4666 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4667 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4668 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4669 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4670 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4671 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4672 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4673 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4674 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4675 }
4676 }
4677 Lex.Lex();
4678 return false;
4679}
4680
4681//===----------------------------------------------------------------------===//
4682// Terminator Instructions.
4683//===----------------------------------------------------------------------===//
4684
4685/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004686/// ::= 'ret' void (',' !dbg, !1)*
4687/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004688bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004689 PerFunctionState &PFS) {
4690 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004691 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004692 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004693
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004694 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004695
Chris Lattnerfdd87902009-10-05 05:54:46 +00004696 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004697 if (!ResType->isVoidTy())
4698 return Error(TypeLoc, "value doesn't match function result type '" +
4699 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004700
Owen Anderson55f1c092009-08-13 21:58:54 +00004701 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004702 return false;
4703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004704
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705 Value *RV;
4706 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004707
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004708 if (ResType != RV->getType())
4709 return Error(TypeLoc, "value doesn't match function result type '" +
4710 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004711
Owen Anderson55f1c092009-08-13 21:58:54 +00004712 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004713 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004714}
4715
4716
4717/// ParseBr
4718/// ::= 'br' TypeAndValue
4719/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4720bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4721 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004722 Value *Op0;
4723 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004724 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004725
Chris Lattnerac161bf2009-01-02 07:01:27 +00004726 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4727 Inst = BranchInst::Create(BB);
4728 return false;
4729 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004730
Owen Anderson55f1c092009-08-13 21:58:54 +00004731 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004733
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004735 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004736 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004737 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004738 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004739
Chris Lattner3ed871f2009-10-27 19:13:16 +00004740 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 return false;
4742}
4743
4744/// ParseSwitch
4745/// Instruction
4746/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4747/// JumpTable
4748/// ::= (TypeAndValue ',' TypeAndValue)*
4749bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4750 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004751 Value *Cond;
4752 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004753 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4754 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004755 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4757 return true;
4758
Duncan Sands19d0b472010-02-16 11:11:14 +00004759 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 // Parse the jump table pairs.
4763 SmallPtrSet<Value*, 32> SeenCases;
4764 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4765 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004766 Value *Constant;
4767 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004768
Chris Lattnerac161bf2009-01-02 07:01:27 +00004769 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4770 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004771 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004773
David Blaikie70573dc2014-11-19 07:49:26 +00004774 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004775 return Error(CondLoc, "duplicate case value in switch");
4776 if (!isa<ConstantInt>(Constant))
4777 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004778
Chris Lattner3ed871f2009-10-27 19:13:16 +00004779 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004781
Chris Lattnerac161bf2009-01-02 07:01:27 +00004782 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004783
Chris Lattner3ed871f2009-10-27 19:13:16 +00004784 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4786 SI->addCase(Table[i].first, Table[i].second);
4787 Inst = SI;
4788 return false;
4789}
4790
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004791/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004792/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004793/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4794bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004795 LocTy AddrLoc;
4796 Value *Address;
4797 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004798 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4799 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004800 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004801
Duncan Sands19d0b472010-02-16 11:11:14 +00004802 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004803 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004804
Chris Lattner3ed871f2009-10-27 19:13:16 +00004805 // Parse the destination list.
4806 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004807
Chris Lattner3ed871f2009-10-27 19:13:16 +00004808 if (Lex.getKind() != lltok::rsquare) {
4809 BasicBlock *DestBB;
4810 if (ParseTypeAndBasicBlock(DestBB, PFS))
4811 return true;
4812 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004813
Chris Lattner3ed871f2009-10-27 19:13:16 +00004814 while (EatIfPresent(lltok::comma)) {
4815 if (ParseTypeAndBasicBlock(DestBB, PFS))
4816 return true;
4817 DestList.push_back(DestBB);
4818 }
4819 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004820
Chris Lattner3ed871f2009-10-27 19:13:16 +00004821 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4822 return true;
4823
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004824 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004825 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4826 IBI->addDestination(DestList[i]);
4827 Inst = IBI;
4828 return false;
4829}
4830
4831
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832/// ParseInvoke
4833/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4834/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4835bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4836 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004837 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004838 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004839 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004840 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004841 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 LocTy RetTypeLoc;
4843 ValID CalleeID;
4844 SmallVector<ParamInfo, 16> ArgList;
4845
Chris Lattner3ed871f2009-10-27 19:13:16 +00004846 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004847 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004848 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004849 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004850 ParseValID(CalleeID) ||
4851 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004852 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4853 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004854 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004855 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004856 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004857 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004858 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004859
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 // If RetType is a non-function pointer type, then this is the short syntax
4861 // for the call, which means that RetType is just the return type. Infer the
4862 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004863 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4864 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004865 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004866 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4868 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004869
Chris Lattnerac161bf2009-01-02 07:01:27 +00004870 if (!FunctionType::isValidReturnType(RetType))
4871 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004872
Owen Anderson4056ca92009-07-29 22:17:13 +00004873 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004874 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004875
David Blaikie41ba2b42015-07-27 23:32:19 +00004876 CalleeID.FTy = Ty;
4877
Chris Lattnerac161bf2009-01-02 07:01:27 +00004878 // Look up the callee.
4879 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004880 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4881 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004882
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004883 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004884 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004885 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004886 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4887 AttributeSet::ReturnIndex,
4888 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004889
Chris Lattnerac161bf2009-01-02 07:01:27 +00004890 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004891
Chris Lattnerac161bf2009-01-02 07:01:27 +00004892 // Loop through FunctionType's arguments and ensure they are specified
4893 // correctly. Also, gather any parameter attributes.
4894 FunctionType::param_iterator I = Ty->param_begin();
4895 FunctionType::param_iterator E = Ty->param_end();
4896 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004897 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004898 if (I != E) {
4899 ExpectedTy = *I++;
4900 } else if (!Ty->isVarArg()) {
4901 return Error(ArgList[i].Loc, "too many arguments specified");
4902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004903
Chris Lattnerac161bf2009-01-02 07:01:27 +00004904 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4905 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004906 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004907 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004908 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4909 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004910 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4911 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004912 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004913
Chris Lattnerac161bf2009-01-02 07:01:27 +00004914 if (I != E)
4915 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004916
David Majnemer8d22abd2015-02-23 00:01:32 +00004917 if (FnAttrs.hasAttributes()) {
4918 if (FnAttrs.hasAlignmentAttr())
4919 return Error(CallLoc, "invoke instructions may not have an alignment");
4920
Bill Wendlingf5075a42013-01-27 02:24:02 +00004921 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4922 AttributeSet::FunctionIndex,
4923 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004924 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004925
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004926 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004927 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004928
David Blaikie3e807092015-05-13 18:35:26 +00004929 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004930 II->setCallingConv(CC);
4931 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004932 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004933 Inst = II;
4934 return false;
4935}
4936
Bill Wendlingf891bf82011-07-31 06:30:59 +00004937/// ParseResume
4938/// ::= 'resume' TypeAndValue
4939bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4940 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004941 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4942 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943
Bill Wendlingf891bf82011-07-31 06:30:59 +00004944 ResumeInst *RI = ResumeInst::Create(Exn);
4945 Inst = RI;
4946 return false;
4947}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948
David Majnemer654e1302015-07-31 17:58:14 +00004949bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
4950 PerFunctionState &PFS) {
4951 if (ParseToken(lltok::lsquare, "expected '[' in cleanuppad"))
4952 return true;
4953
4954 while (Lex.getKind() != lltok::rsquare) {
4955 // If this isn't the first argument, we need a comma.
4956 if (!Args.empty() &&
4957 ParseToken(lltok::comma, "expected ',' in argument list"))
4958 return true;
4959
4960 // Parse the argument.
4961 LocTy ArgLoc;
4962 Type *ArgTy = nullptr;
4963 if (ParseType(ArgTy, ArgLoc))
4964 return true;
4965
4966 Value *V;
4967 if (ArgTy->isMetadataTy()) {
4968 if (ParseMetadataAsValue(V, PFS))
4969 return true;
4970 } else {
4971 if (ParseValue(ArgTy, V, PFS))
4972 return true;
4973 }
4974 Args.push_back(V);
4975 }
4976
4977 Lex.Lex(); // Lex the ']'.
4978 return false;
4979}
4980
4981/// ParseCleanupRet
4982/// ::= 'cleanupret' ('void' | TypeAndValue) unwind ('to' 'caller' | TypeAndValue)
4983bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
4984 Type *RetTy = nullptr;
4985 Value *RetVal = nullptr;
4986 if (ParseType(RetTy, /*AllowVoid=*/true))
4987 return true;
4988
4989 if (!RetTy->isVoidTy())
4990 if (ParseValue(RetTy, RetVal, PFS))
4991 return true;
4992
4993 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
4994 return true;
4995
4996 BasicBlock *UnwindBB = nullptr;
4997 if (Lex.getKind() == lltok::kw_to) {
4998 Lex.Lex();
4999 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5000 return true;
5001 } else {
5002 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5003 return true;
5004 }
5005 }
5006
5007 Inst = CleanupReturnInst::Create(Context, RetVal, UnwindBB);
5008 return false;
5009}
5010
5011/// ParseCatchRet
5012/// ::= 'catchret' TypeAndValue
5013bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5014 BasicBlock *BB;
5015 if (ParseTypeAndBasicBlock(BB, PFS))
5016 return true;
5017
5018 Inst = CatchReturnInst::Create(BB);
5019 return false;
5020}
5021
5022/// ParseCatchPad
5023/// ::= 'catchpad' Type ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5024bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5025 Type *RetType = nullptr;
5026
5027 SmallVector<Value *, 8> Args;
5028 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5029 return true;
5030
5031 BasicBlock *NormalBB, *UnwindBB;
5032 if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5033 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5034 ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5035 ParseTypeAndBasicBlock(UnwindBB, PFS))
5036 return true;
5037
5038 Inst = CatchPadInst::Create(RetType, NormalBB, UnwindBB, Args);
5039 return false;
5040}
5041
5042/// ParseTerminatePad
5043/// ::= 'terminatepad' ParamList 'to' TypeAndValue
5044bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5045 SmallVector<Value *, 8> Args;
5046 if (ParseExceptionArgs(Args, PFS))
5047 return true;
5048
5049 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5050 return true;
5051
5052 BasicBlock *UnwindBB = nullptr;
5053 if (Lex.getKind() == lltok::kw_to) {
5054 Lex.Lex();
5055 if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5056 return true;
5057 } else {
5058 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5059 return true;
5060 }
5061 }
5062
5063 Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5064 return false;
5065}
5066
5067/// ParseCleanupPad
5068/// ::= 'cleanuppad' ParamList
5069bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5070 Type *RetType = nullptr;
5071
5072 SmallVector<Value *, 8> Args;
5073 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5074 return true;
5075
5076 Inst = CleanupPadInst::Create(RetType, Args);
5077 return false;
5078}
5079
5080/// ParseCatchEndPad
5081/// ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5082bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5083 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5084 return true;
5085
5086 BasicBlock *UnwindBB = nullptr;
5087 if (Lex.getKind() == lltok::kw_to) {
5088 Lex.Lex();
5089 if (Lex.getKind() == lltok::kw_caller) {
5090 Lex.Lex();
5091 } else {
5092 return true;
5093 }
5094 } else {
5095 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5096 return true;
5097 }
5098 }
5099
5100 Inst = CatchEndPadInst::Create(Context, UnwindBB);
5101 return false;
5102}
5103
Chris Lattnerac161bf2009-01-02 07:01:27 +00005104//===----------------------------------------------------------------------===//
5105// Binary Operators.
5106//===----------------------------------------------------------------------===//
5107
5108/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005109/// ::= ArithmeticOps TypeAndValue ',' Value
5110///
5111/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5112/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005114 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005115 LocTy Loc; Value *LHS, *RHS;
5116 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5117 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5118 ParseValue(LHS->getType(), RHS, PFS))
5119 return true;
5120
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005121 bool Valid;
5122 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005123 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005124 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005125 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5126 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005127 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005128 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5129 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005130 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005132 if (!Valid)
5133 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005134
Chris Lattnerac161bf2009-01-02 07:01:27 +00005135 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5136 return false;
5137}
5138
5139/// ParseLogical
5140/// ::= ArithmeticOps TypeAndValue ',' Value {
5141bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5142 unsigned Opc) {
5143 LocTy Loc; Value *LHS, *RHS;
5144 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5145 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5146 ParseValue(LHS->getType(), RHS, PFS))
5147 return true;
5148
Duncan Sands9dff9be2010-02-15 16:12:20 +00005149 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005150 return Error(Loc,"instruction requires integer or integer vector operands");
5151
5152 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5153 return false;
5154}
5155
5156
5157/// ParseCompare
5158/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5159/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5161 unsigned Opc) {
5162 // Parse the integer/fp comparison predicate.
5163 LocTy Loc;
5164 unsigned Pred;
5165 Value *LHS, *RHS;
5166 if (ParseCmpPredicate(Pred, Opc) ||
5167 ParseTypeAndValue(LHS, Loc, PFS) ||
5168 ParseToken(lltok::comma, "expected ',' after compare value") ||
5169 ParseValue(LHS->getType(), RHS, PFS))
5170 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005171
Chris Lattnerac161bf2009-01-02 07:01:27 +00005172 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005173 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005174 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005175 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005176 } else {
5177 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005178 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005179 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005180 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005181 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 }
5183 return false;
5184}
5185
5186//===----------------------------------------------------------------------===//
5187// Other Instructions.
5188//===----------------------------------------------------------------------===//
5189
5190
5191/// ParseCast
5192/// ::= CastOpc TypeAndValue 'to' Type
5193bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5194 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005195 LocTy Loc;
5196 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005197 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005198 if (ParseTypeAndValue(Op, Loc, PFS) ||
5199 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5200 ParseType(DestTy))
5201 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005202
Chris Lattner89d856e2009-03-01 00:53:13 +00005203 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5204 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005205 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005206 getTypeString(Op->getType()) + "' to '" +
5207 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005208 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5210 return false;
5211}
5212
5213/// ParseSelect
5214/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5215bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5216 LocTy Loc;
5217 Value *Op0, *Op1, *Op2;
5218 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5219 ParseToken(lltok::comma, "expected ',' after select condition") ||
5220 ParseTypeAndValue(Op1, PFS) ||
5221 ParseToken(lltok::comma, "expected ',' after select value") ||
5222 ParseTypeAndValue(Op2, PFS))
5223 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005224
Chris Lattnerac161bf2009-01-02 07:01:27 +00005225 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5226 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005227
Chris Lattnerac161bf2009-01-02 07:01:27 +00005228 Inst = SelectInst::Create(Op0, Op1, Op2);
5229 return false;
5230}
5231
Chris Lattnerb55ab542009-01-05 08:18:44 +00005232/// ParseVA_Arg
5233/// ::= 'va_arg' TypeAndValue ',' Type
5234bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005235 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005236 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005237 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 if (ParseTypeAndValue(Op, PFS) ||
5239 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005240 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005242
Chris Lattnerb55ab542009-01-05 08:18:44 +00005243 if (!EltTy->isFirstClassType())
5244 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245
5246 Inst = new VAArgInst(Op, EltTy);
5247 return false;
5248}
5249
5250/// ParseExtractElement
5251/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5252bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5253 LocTy Loc;
5254 Value *Op0, *Op1;
5255 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5256 ParseToken(lltok::comma, "expected ',' after extract value") ||
5257 ParseTypeAndValue(Op1, PFS))
5258 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5261 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005262
Eric Christopherc9742252009-07-25 02:28:41 +00005263 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 return false;
5265}
5266
5267/// ParseInsertElement
5268/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5269bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5270 LocTy Loc;
5271 Value *Op0, *Op1, *Op2;
5272 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5273 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5274 ParseTypeAndValue(Op1, PFS) ||
5275 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5276 ParseTypeAndValue(Op2, PFS))
5277 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005278
Chris Lattnerac161bf2009-01-02 07:01:27 +00005279 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005280 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005281
Chris Lattnerac161bf2009-01-02 07:01:27 +00005282 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5283 return false;
5284}
5285
5286/// ParseShuffleVector
5287/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5288bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5289 LocTy Loc;
5290 Value *Op0, *Op1, *Op2;
5291 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5292 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5293 ParseTypeAndValue(Op1, PFS) ||
5294 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5295 ParseTypeAndValue(Op2, PFS))
5296 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005297
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005299 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005300
Chris Lattnerac161bf2009-01-02 07:01:27 +00005301 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5302 return false;
5303}
5304
5305/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005306/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005307int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005308 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005309 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005310
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005311 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005312 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5313 ParseValue(Ty, Op0, PFS) ||
5314 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005315 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5317 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005318
Chris Lattnerf4f03422009-12-30 05:27:33 +00005319 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005320 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5321 while (1) {
5322 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005323
Chris Lattner3822f632009-01-02 08:05:26 +00005324 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005325 break;
5326
Chris Lattnerf4f03422009-12-30 05:27:33 +00005327 if (Lex.getKind() == lltok::MetadataVar) {
5328 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005329 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005330 }
Devang Patel8f842d32009-10-16 18:45:49 +00005331
Chris Lattner3822f632009-01-02 08:05:26 +00005332 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005333 ParseValue(Ty, Op0, PFS) ||
5334 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005335 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005336 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5337 return true;
5338 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005339
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340 if (!Ty->isFirstClassType())
5341 return Error(TypeLoc, "phi node must have first class type");
5342
Jay Foad52131342011-03-30 11:28:46 +00005343 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005344 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5345 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5346 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005347 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348}
5349
Bill Wendlingfae14752011-08-12 20:24:12 +00005350/// ParseLandingPad
5351/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5352/// Clause
5353/// ::= 'catch' TypeAndValue
5354/// ::= 'filter'
5355/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5356bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005357 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005358
David Majnemer7fddecc2015-06-17 20:52:32 +00005359 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005360 return true;
5361
David Majnemer7fddecc2015-06-17 20:52:32 +00005362 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005363 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5364
5365 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5366 LandingPadInst::ClauseType CT;
5367 if (EatIfPresent(lltok::kw_catch))
5368 CT = LandingPadInst::Catch;
5369 else if (EatIfPresent(lltok::kw_filter))
5370 CT = LandingPadInst::Filter;
5371 else
5372 return TokError("expected 'catch' or 'filter' clause type");
5373
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005374 Value *V;
5375 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005376 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005377 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005378
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005379 // A 'catch' type expects a non-array constant. A filter clause expects an
5380 // array constant.
5381 if (CT == LandingPadInst::Catch) {
5382 if (isa<ArrayType>(V->getType()))
5383 Error(VLoc, "'catch' clause has an invalid type");
5384 } else {
5385 if (!isa<ArrayType>(V->getType()))
5386 Error(VLoc, "'filter' clause has an invalid type");
5387 }
5388
Owen Andersonf8f259d2015-03-09 07:13:42 +00005389 Constant *CV = dyn_cast<Constant>(V);
5390 if (!CV)
5391 return Error(VLoc, "clause argument must be a constant");
5392 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005393 }
5394
Owen Andersonf8f259d2015-03-09 07:13:42 +00005395 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005396 return false;
5397}
5398
Chris Lattnerac161bf2009-01-02 07:01:27 +00005399/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005400/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5401/// ParameterList OptionalAttrs
5402/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5403/// ParameterList OptionalAttrs
5404/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005405/// ParameterList OptionalAttrs
5406bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005407 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005408 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005409 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005410 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005411 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005412 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005413 LocTy RetTypeLoc;
5414 ValID CalleeID;
5415 SmallVector<ParamInfo, 16> ArgList;
5416 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005417
Reid Kleckner5772b772014-04-24 20:14:34 +00005418 if ((TCK != CallInst::TCK_None &&
5419 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005421 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005422 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005423 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005424 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5425 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005426 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005427 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005428 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005429
Chris Lattnerac161bf2009-01-02 07:01:27 +00005430 // If RetType is a non-function pointer type, then this is the short syntax
5431 // for the call, which means that RetType is just the return type. Infer the
5432 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005433 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5434 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005435 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005436 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005437 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5438 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005439
Chris Lattnerac161bf2009-01-02 07:01:27 +00005440 if (!FunctionType::isValidReturnType(RetType))
5441 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005442
Owen Anderson4056ca92009-07-29 22:17:13 +00005443 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005444 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005445
David Blaikie41ba2b42015-07-27 23:32:19 +00005446 CalleeID.FTy = Ty;
5447
Chris Lattnerac161bf2009-01-02 07:01:27 +00005448 // Look up the callee.
5449 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005450 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5451 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005452
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005453 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005454 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005455 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005456 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5457 AttributeSet::ReturnIndex,
5458 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005459
Chris Lattnerac161bf2009-01-02 07:01:27 +00005460 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005461
Chris Lattnerac161bf2009-01-02 07:01:27 +00005462 // Loop through FunctionType's arguments and ensure they are specified
5463 // correctly. Also, gather any parameter attributes.
5464 FunctionType::param_iterator I = Ty->param_begin();
5465 FunctionType::param_iterator E = Ty->param_end();
5466 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005467 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005468 if (I != E) {
5469 ExpectedTy = *I++;
5470 } else if (!Ty->isVarArg()) {
5471 return Error(ArgList[i].Loc, "too many arguments specified");
5472 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005473
Chris Lattnerac161bf2009-01-02 07:01:27 +00005474 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5475 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005476 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005478 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5479 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005480 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5481 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005482 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005483
Chris Lattnerac161bf2009-01-02 07:01:27 +00005484 if (I != E)
5485 return Error(CallLoc, "not enough parameters specified for call");
5486
David Majnemer8d22abd2015-02-23 00:01:32 +00005487 if (FnAttrs.hasAttributes()) {
5488 if (FnAttrs.hasAlignmentAttr())
5489 return Error(CallLoc, "call instructions may not have an alignment");
5490
Bill Wendlingf5075a42013-01-27 02:24:02 +00005491 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5492 AttributeSet::FunctionIndex,
5493 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005494 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005495
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005496 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005497 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005498
David Blaikie348de692015-04-23 21:36:23 +00005499 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005500 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005501 CI->setCallingConv(CC);
5502 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005503 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005504 Inst = CI;
5505 return false;
5506}
5507
5508//===----------------------------------------------------------------------===//
5509// Memory Instructions.
5510//===----------------------------------------------------------------------===//
5511
5512/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005513/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005514int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005515 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005516 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005517 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005518 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005519
5520 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5521
David Majnemera3b0eb22015-02-16 08:38:03 +00005522 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005523
David Majnemera3b0eb22015-02-16 08:38:03 +00005524 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5525 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005526
Chris Lattnerb2f39502009-12-30 05:44:30 +00005527 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005528 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005529 if (Lex.getKind() == lltok::kw_align) {
5530 if (ParseOptionalAlignment(Alignment)) return true;
5531 } else if (Lex.getKind() == lltok::MetadataVar) {
5532 AteExtraComma = true;
5533 } else {
5534 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5535 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5536 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005537 }
5538 }
5539
Dan Gohman2140a742010-05-28 01:14:11 +00005540 if (Size && !Size->getType()->isIntegerTy())
5541 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005542
Reid Kleckner436c42e2014-01-17 23:58:17 +00005543 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5544 AI->setUsedWithInAlloca(IsInAlloca);
5545 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005546 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547}
5548
5549/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005550/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005551/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005552/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005553int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005554 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005555 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005556 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005557 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005558 AtomicOrdering Ordering = NotAtomic;
5559 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005560
5561 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005562 isAtomic = true;
5563 Lex.Lex();
5564 }
5565
Chris Lattnerbc639292011-11-27 06:56:53 +00005566 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005567 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005568 isVolatile = true;
5569 Lex.Lex();
5570 }
5571
David Blaikie15d9a4c2015-04-06 20:59:48 +00005572 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005573 LocTy ExplicitTypeLoc = Lex.getLoc();
5574 if (ParseType(Ty) ||
5575 ParseToken(lltok::comma, "expected comma after load's type") ||
5576 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005577 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005578 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5579 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005580
David Blaikie15d9a4c2015-04-06 20:59:48 +00005581 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005583 if (isAtomic && !Alignment)
5584 return Error(Loc, "atomic load must have explicit non-zero alignment");
5585 if (Ordering == Release || Ordering == AcquireRelease)
5586 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005587
David Blaikiea79ac142015-02-27 21:17:42 +00005588 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5589 return Error(ExplicitTypeLoc,
5590 "explicit pointee type doesn't match operand's pointee type");
5591
David Blaikie15d9a4c2015-04-06 20:59:48 +00005592 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005593 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005594}
5595
5596/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005597
5598/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5599/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005600/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005601int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005602 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005603 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005604 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005605 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005606 AtomicOrdering Ordering = NotAtomic;
5607 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005608
5609 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005610 isAtomic = true;
5611 Lex.Lex();
5612 }
5613
Chris Lattnerbc639292011-11-27 06:56:53 +00005614 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005615 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005616 isVolatile = true;
5617 Lex.Lex();
5618 }
5619
Chris Lattnerac161bf2009-01-02 07:01:27 +00005620 if (ParseTypeAndValue(Val, Loc, PFS) ||
5621 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005622 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005623 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005624 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005625 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005626
Duncan Sands19d0b472010-02-16 11:11:14 +00005627 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005628 return Error(PtrLoc, "store operand must be a pointer");
5629 if (!Val->getType()->isFirstClassType())
5630 return Error(Loc, "store operand must be a first class value");
5631 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5632 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005633 if (isAtomic && !Alignment)
5634 return Error(Loc, "atomic store must have explicit non-zero alignment");
5635 if (Ordering == Acquire || Ordering == AcquireRelease)
5636 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005637
Eli Friedman59b66882011-08-09 23:02:53 +00005638 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005639 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640}
5641
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005642/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005643/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5644/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005645int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005646 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5647 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005648 AtomicOrdering SuccessOrdering = NotAtomic;
5649 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005650 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005651 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005652 bool isWeak = false;
5653
5654 if (EatIfPresent(lltok::kw_weak))
5655 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005656
5657 if (EatIfPresent(lltok::kw_volatile))
5658 isVolatile = true;
5659
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005660 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5661 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5662 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5663 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5664 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005665 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5666 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005667 return true;
5668
Tim Northovere94a5182014-03-11 10:48:52 +00005669 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005670 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005671 if (SuccessOrdering < FailureOrdering)
5672 return TokError("cmpxchg must be at least as ordered on success as failure");
5673 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5674 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005675 if (!Ptr->getType()->isPointerTy())
5676 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5677 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5678 return Error(CmpLoc, "compare value and pointer type do not match");
5679 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5680 return Error(NewLoc, "new value and pointer type do not match");
5681 if (!New->getType()->isIntegerTy())
5682 return Error(NewLoc, "cmpxchg operand must be an integer");
5683 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5684 if (Size < 8 || (Size & (Size - 1)))
5685 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5686 " integer");
5687
Tim Northover420a2162014-06-13 14:24:07 +00005688 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5689 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005690 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005691 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005692 Inst = CXI;
5693 return AteExtraComma ? InstExtraComma : InstNormal;
5694}
5695
5696/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005697/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5698/// 'singlethread'? AtomicOrdering
5699int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005700 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5701 bool AteExtraComma = false;
5702 AtomicOrdering Ordering = NotAtomic;
5703 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005704 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005705 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005706
5707 if (EatIfPresent(lltok::kw_volatile))
5708 isVolatile = true;
5709
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005710 switch (Lex.getKind()) {
5711 default: return TokError("expected binary operation in atomicrmw");
5712 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5713 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5714 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5715 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5716 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5717 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5718 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5719 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5720 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5721 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5722 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5723 }
5724 Lex.Lex(); // Eat the operation.
5725
5726 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5727 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5728 ParseTypeAndValue(Val, ValLoc, PFS) ||
5729 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5730 return true;
5731
5732 if (Ordering == Unordered)
5733 return TokError("atomicrmw cannot be unordered");
5734 if (!Ptr->getType()->isPointerTy())
5735 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5736 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5737 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5738 if (!Val->getType()->isIntegerTy())
5739 return Error(ValLoc, "atomicrmw operand must be an integer");
5740 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5741 if (Size < 8 || (Size & (Size - 1)))
5742 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5743 " integer");
5744
5745 AtomicRMWInst *RMWI =
5746 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5747 RMWI->setVolatile(isVolatile);
5748 Inst = RMWI;
5749 return AteExtraComma ? InstExtraComma : InstNormal;
5750}
5751
Eli Friedmanfee02c62011-07-25 23:16:38 +00005752/// ParseFence
5753/// ::= 'fence' 'singlethread'? AtomicOrdering
5754int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5755 AtomicOrdering Ordering = NotAtomic;
5756 SynchronizationScope Scope = CrossThread;
5757 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5758 return true;
5759
5760 if (Ordering == Unordered)
5761 return TokError("fence cannot be unordered");
5762 if (Ordering == Monotonic)
5763 return TokError("fence cannot be monotonic");
5764
5765 Inst = new FenceInst(Context, Ordering, Scope);
5766 return InstNormal;
5767}
5768
Chris Lattnerac161bf2009-01-02 07:01:27 +00005769/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005770/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005771int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005772 Value *Ptr = nullptr;
5773 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005774 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005775
Dan Gohman16cbbe42009-07-29 15:58:36 +00005776 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005777
David Blaikie79e6c742015-02-27 19:29:02 +00005778 Type *Ty = nullptr;
5779 LocTy ExplicitTypeLoc = Lex.getLoc();
5780 if (ParseType(Ty) ||
5781 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5782 ParseTypeAndValue(Ptr, Loc, PFS))
5783 return true;
5784
Eli Benderskyd9806682013-04-22 17:03:42 +00005785 Type *BaseType = Ptr->getType();
5786 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5787 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005789
David Blaikie8d757942015-03-09 23:08:44 +00005790 if (Ty != BasePointerType->getElementType())
5791 return Error(ExplicitTypeLoc,
5792 "explicit pointee type doesn't match operand's pointee type");
5793
Chris Lattnerac161bf2009-01-02 07:01:27 +00005794 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005795 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005796 // GEP returns a vector of pointers if at least one of parameters is a vector.
5797 // All vector parameters should have the same vector width.
5798 unsigned GEPWidth = BaseType->isVectorTy() ?
5799 BaseType->getVectorNumElements() : 0;
5800
Chris Lattner3822f632009-01-02 08:05:26 +00005801 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005802 if (Lex.getKind() == lltok::MetadataVar) {
5803 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005804 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005805 }
Chris Lattner3822f632009-01-02 08:05:26 +00005806 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005807 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005809
Nadav Rotem3924cb02011-12-05 06:29:09 +00005810 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005811 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5812 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00005813 return Error(EltLoc,
5814 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005815 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005816 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005817 Indices.push_back(Val);
5818 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005819
Craig Toppere3dcce92015-08-01 22:20:21 +00005820 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005821 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005822 return Error(Loc, "base element of getelementptr must be sized");
5823
David Blaikied33bad32015-04-17 22:32:13 +00005824 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005825 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005826 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005827 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005828 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005829 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005830}
5831
5832/// ParseExtractValue
5833/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005834int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005835 Value *Val; LocTy Loc;
5836 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005837 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005838 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005839 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005840 return true;
5841
Chris Lattner392be582010-02-12 20:49:41 +00005842 if (!Val->getType()->isAggregateType())
5843 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844
Jay Foad57aa6362011-07-13 10:26:04 +00005845 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005847 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005848 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005849}
5850
5851/// ParseInsertValue
5852/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005853int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005854 Value *Val0, *Val1; LocTy Loc0, Loc1;
5855 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005856 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005857 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5858 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5859 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005860 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005861 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005862
Chris Lattner392be582010-02-12 20:49:41 +00005863 if (!Val0->getType()->isAggregateType())
5864 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005865
David Majnemer30074532015-02-11 07:43:58 +00005866 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5867 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005868 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005869 if (IndexedType != Val1->getType())
5870 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5871 getTypeString(Val1->getType()) + "' instead of '" +
5872 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005873 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005874 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005875}
Nick Lewycky49f89192009-04-04 07:22:01 +00005876
5877//===----------------------------------------------------------------------===//
5878// Embedded metadata.
5879//===----------------------------------------------------------------------===//
5880
5881/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005882/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005883/// Element
5884/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005885bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005886 if (ParseToken(lltok::lbrace, "expected '{' here"))
5887 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005888
Dan Gohman1e0213a2010-07-13 19:33:27 +00005889 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005890 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005891 return false;
5892
Nick Lewycky49f89192009-04-04 07:22:01 +00005893 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005894 // Null is a special case since it is typeless.
5895 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005896 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005897 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005898 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005899
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005900 Metadata *MD;
5901 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005902 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005903 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005904 } while (EatIfPresent(lltok::comma));
5905
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005906 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005907}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005908
5909//===----------------------------------------------------------------------===//
5910// Use-list order directives.
5911//===----------------------------------------------------------------------===//
5912bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5913 SMLoc Loc) {
5914 if (V->use_empty())
5915 return Error(Loc, "value has no uses");
5916
5917 unsigned NumUses = 0;
5918 SmallDenseMap<const Use *, unsigned, 16> Order;
5919 for (const Use &U : V->uses()) {
5920 if (++NumUses > Indexes.size())
5921 break;
5922 Order[&U] = Indexes[NumUses - 1];
5923 }
5924 if (NumUses < 2)
5925 return Error(Loc, "value only has one use");
5926 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5927 return Error(Loc, "wrong number of indexes, expected " +
5928 Twine(std::distance(V->use_begin(), V->use_end())));
5929
5930 V->sortUseList([&](const Use &L, const Use &R) {
5931 return Order.lookup(&L) < Order.lookup(&R);
5932 });
5933 return false;
5934}
5935
5936/// ParseUseListOrderIndexes
5937/// ::= '{' uint32 (',' uint32)+ '}'
5938bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5939 SMLoc Loc = Lex.getLoc();
5940 if (ParseToken(lltok::lbrace, "expected '{' here"))
5941 return true;
5942 if (Lex.getKind() == lltok::rbrace)
5943 return Lex.Error("expected non-empty list of uselistorder indexes");
5944
5945 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5946 // indexes should be distinct numbers in the range [0, size-1], and should
5947 // not be in order.
5948 unsigned Offset = 0;
5949 unsigned Max = 0;
5950 bool IsOrdered = true;
5951 assert(Indexes.empty() && "Expected empty order vector");
5952 do {
5953 unsigned Index;
5954 if (ParseUInt32(Index))
5955 return true;
5956
5957 // Update consistency checks.
5958 Offset += Index - Indexes.size();
5959 Max = std::max(Max, Index);
5960 IsOrdered &= Index == Indexes.size();
5961
5962 Indexes.push_back(Index);
5963 } while (EatIfPresent(lltok::comma));
5964
5965 if (ParseToken(lltok::rbrace, "expected '}' here"))
5966 return true;
5967
5968 if (Indexes.size() < 2)
5969 return Error(Loc, "expected >= 2 uselistorder indexes");
5970 if (Offset != 0 || Max >= Indexes.size())
5971 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5972 if (IsOrdered)
5973 return Error(Loc, "expected uselistorder indexes to change the order");
5974
5975 return false;
5976}
5977
5978/// ParseUseListOrder
5979/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5980bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5981 SMLoc Loc = Lex.getLoc();
5982 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5983 return true;
5984
5985 Value *V;
5986 SmallVector<unsigned, 16> Indexes;
5987 if (ParseTypeAndValue(V, PFS) ||
5988 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5989 ParseUseListOrderIndexes(Indexes))
5990 return true;
5991
5992 return sortUseListOrder(V, Indexes, Loc);
5993}
5994
5995/// ParseUseListOrderBB
5996/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5997bool LLParser::ParseUseListOrderBB() {
5998 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5999 SMLoc Loc = Lex.getLoc();
6000 Lex.Lex();
6001
6002 ValID Fn, Label;
6003 SmallVector<unsigned, 16> Indexes;
6004 if (ParseValID(Fn) ||
6005 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6006 ParseValID(Label) ||
6007 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6008 ParseUseListOrderIndexes(Indexes))
6009 return true;
6010
6011 // Check the function.
6012 GlobalValue *GV;
6013 if (Fn.Kind == ValID::t_GlobalName)
6014 GV = M->getNamedValue(Fn.StrVal);
6015 else if (Fn.Kind == ValID::t_GlobalID)
6016 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6017 else
6018 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6019 if (!GV)
6020 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6021 auto *F = dyn_cast<Function>(GV);
6022 if (!F)
6023 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6024 if (F->isDeclaration())
6025 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6026
6027 // Check the basic block.
6028 if (Label.Kind == ValID::t_LocalID)
6029 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6030 if (Label.Kind != ValID::t_LocalName)
6031 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6032 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6033 if (!V)
6034 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6035 if (!isa<BasicBlock>(V))
6036 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6037
6038 return sortUseListOrder(V, Indexes, Loc);
6039}