blob: b6a753d97cfd06e2ef0a5f0e71e61f08a11a7689 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000022#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000028#include "llvm/Support/raw_ostream.h"
29using namespace llvm;
30
Chris Lattner229907c2011-07-18 04:54:35 +000031static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000032 std::string Result;
33 raw_string_ostream Tmp(Result);
34 Tmp << *T;
35 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000036}
37
Chris Lattner3822f632009-01-02 08:05:26 +000038/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000039bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000040 // Prime the lexer.
41 Lex.Lex();
42
Chris Lattnerad6f3352009-01-04 20:44:11 +000043 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000045}
46
47/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48/// module.
49bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000050 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
51 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
52
Bill Wendlingb32b0412013-02-08 06:32:06 +000053 // Handle any function attribute group forward references.
54 for (std::map<Value*, std::vector<unsigned> >::iterator
55 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
56 I != E; ++I) {
57 Value *V = I->first;
58 std::vector<unsigned> &Vec = I->second;
59 AttrBuilder B;
60
61 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
62 VI != VE; ++VI)
63 B.merge(NumberedAttrBuilders[*VI]);
64
65 if (Function *Fn = dyn_cast<Function>(V)) {
66 AttributeSet AS = Fn->getAttributes();
67 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
68 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
69 AS.getFnAttributes());
70
71 FnAttrs.merge(B);
72
73 // If the alignment was parsed as an attribute, move to the alignment
74 // field.
75 if (FnAttrs.hasAlignmentAttr()) {
76 Fn->setAlignment(FnAttrs.getAlignment());
77 FnAttrs.removeAttribute(Attribute::Alignment);
78 }
79
80 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
81 AttributeSet::get(Context,
82 AttributeSet::FunctionIndex,
83 FnAttrs));
84 Fn->setAttributes(AS);
85 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
86 AttributeSet AS = CI->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000090 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000091 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
92 AttributeSet::get(Context,
93 AttributeSet::FunctionIndex,
94 FnAttrs));
95 CI->setAttributes(AS);
96 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
97 AttributeSet AS = II->getAttributes();
98 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000101 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000102 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
103 AttributeSet::get(Context,
104 AttributeSet::FunctionIndex,
105 FnAttrs));
106 II->setAttributes(AS);
107 } else {
108 llvm_unreachable("invalid object with forward attribute group reference");
109 }
110 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000111
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000112 // If there are entries in ForwardRefBlockAddresses at this point, the
113 // function was never defined.
114 if (!ForwardRefBlockAddresses.empty())
115 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
116 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000118 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
119 if (NumberedTypes[i].second.isValid())
120 return Error(NumberedTypes[i].second,
121 "use of undefined type '%" + Twine(i) + "'");
122
123 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
124 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
125 if (I->second.second.isValid())
126 return Error(I->second.second,
127 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000128
David Majnemerdad0a642014-06-27 18:19:56 +0000129 if (!ForwardRefComdats.empty())
130 return Error(ForwardRefComdats.begin()->second,
131 "use of undefined comdat '$" +
132 ForwardRefComdats.begin()->first + "'");
133
Chris Lattnerac161bf2009-01-02 07:01:27 +0000134 if (!ForwardRefVals.empty())
135 return Error(ForwardRefVals.begin()->second.second,
136 "use of undefined value '@" + ForwardRefVals.begin()->first +
137 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000138
Chris Lattnerac161bf2009-01-02 07:01:27 +0000139 if (!ForwardRefValIDs.empty())
140 return Error(ForwardRefValIDs.begin()->second.second,
141 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000142 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000143
Devang Pateld2541152009-07-08 19:23:54 +0000144 if (!ForwardRefMDNodes.empty())
145 return Error(ForwardRefMDNodes.begin()->second.second,
146 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000147 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000148
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000149 // Resolve metadata cycles.
150 for (auto &N : NumberedMetadata)
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000151 if (auto *U = cast_or_null<UniquableMDNode>(N))
152 U->resolveCycles();
Devang Pateld2541152009-07-08 19:23:54 +0000153
Chris Lattnerac161bf2009-01-02 07:01:27 +0000154 // Look for intrinsic functions and CallInst that need to be upgraded
155 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
156 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000157
Manman Ren8b4306c2013-12-02 21:29:56 +0000158 UpgradeDebugInfo(*M);
159
Chris Lattnerac161bf2009-01-02 07:01:27 +0000160 return false;
161}
162
163//===----------------------------------------------------------------------===//
164// Top-Level Entities
165//===----------------------------------------------------------------------===//
166
167bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000168 while (1) {
169 switch (Lex.getKind()) {
170 default: return TokError("expected top-level entity");
171 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000172 case lltok::kw_declare: if (ParseDeclare()) return true; break;
173 case lltok::kw_define: if (ParseDefine()) return true; break;
174 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
175 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000176 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000177 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000178 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000179 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000180 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000181 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000183 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
188 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000189 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000190 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000191 case lltok::kw_internal: // OptionalLinkage
192 case lltok::kw_weak: // OptionalLinkage
193 case lltok::kw_weak_odr: // OptionalLinkage
194 case lltok::kw_linkonce: // OptionalLinkage
195 case lltok::kw_linkonce_odr: // OptionalLinkage
196 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000197 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000198 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000199 case lltok::kw_external: // OptionalLinkage
200 case lltok::kw_default: // OptionalVisibility
201 case lltok::kw_hidden: // OptionalVisibility
202 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000203 case lltok::kw_dllimport: // OptionalDLLStorageClass
204 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000205 case lltok::kw_thread_local: // OptionalThreadLocal
206 case lltok::kw_addrspace: // OptionalAddrSpace
207 case lltok::kw_constant: // GlobalType
208 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000209 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000210 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000211 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000212 bool HasLinkage;
213 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000214 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000215 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000216 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000217 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000218 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000219 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000220 return true;
221 break;
222 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000223
224 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000225 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
226 case lltok::kw_uselistorder_bb:
227 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000228 }
229 }
230}
231
232
233/// toplevelentity
234/// ::= 'module' 'asm' STRINGCONSTANT
235bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
237 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000238
239 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000242
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000243 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000244 return false;
245}
246
247/// toplevelentity
248/// ::= 'target' 'triple' '=' STRINGCONSTANT
249/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000252 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000253 switch (Lex.Lex()) {
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
256 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000260 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 return false;
262 case lltok::kw_datalayout:
263 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000264 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
265 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000267 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 return false;
269 }
270}
271
Bill Wendling706d3d62012-11-28 08:41:48 +0000272/// toplevelentity
273/// ::= 'deplibs' '=' '[' ']'
274/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
275/// FIXME: Remove in 4.0. Currently parse, but ignore.
276bool LLParser::ParseDepLibs() {
277 assert(Lex.getKind() == lltok::kw_deplibs);
278 Lex.Lex();
279 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
280 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
281 return true;
282
283 if (EatIfPresent(lltok::rsquare))
284 return false;
285
286 do {
287 std::string Str;
288 if (ParseStringConstant(Str)) return true;
289 } while (EatIfPresent(lltok::comma));
290
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
292}
293
Dan Gohman466876b2009-08-12 23:32:33 +0000294/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000295/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000296bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000297 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000298 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000299 Lex.Lex(); // eat LocalVarID;
300
301 if (ParseToken(lltok::equal, "expected '=' after name") ||
302 ParseToken(lltok::kw_type, "expected 'type' after '='"))
303 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000305 if (TypeID >= NumberedTypes.size())
306 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000307
Craig Topper2617dcc2014-04-15 06:32:26 +0000308 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000309 if (ParseStructDefinition(TypeLoc, "",
310 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000312 if (!isa<StructType>(Result)) {
313 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
314 if (Entry.first)
315 return Error(TypeLoc, "non-struct types may not be recursive");
316 Entry.first = Result;
317 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000319
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return false;
321}
322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000323
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324/// toplevelentity
325/// ::= LocalVar '=' 'type' type
326bool LLParser::ParseNamedType() {
327 std::string Name = Lex.getStrVal();
328 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000329 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000330
Chris Lattner3822f632009-01-02 08:05:26 +0000331 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000332 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000333 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000334
Craig Topper2617dcc2014-04-15 06:32:26 +0000335 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000336 if (ParseStructDefinition(NameLoc, Name,
337 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000339 if (!isa<StructType>(Result)) {
340 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
341 if (Entry.first)
342 return Error(NameLoc, "non-struct types may not be recursive");
343 Entry.first = Result;
344 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000347 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000348}
349
350
351/// toplevelentity
352/// ::= 'declare' FunctionHeader
353bool LLParser::ParseDeclare() {
354 assert(Lex.getKind() == lltok::kw_declare);
355 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000356
Chris Lattnerac161bf2009-01-02 07:01:27 +0000357 Function *F;
358 return ParseFunctionHeader(F, false);
359}
360
361/// toplevelentity
362/// ::= 'define' FunctionHeader '{' ...
363bool LLParser::ParseDefine() {
364 assert(Lex.getKind() == lltok::kw_define);
365 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000368 return ParseFunctionHeader(F, true) ||
369 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370}
371
Chris Lattner3822f632009-01-02 08:05:26 +0000372/// ParseGlobalType
373/// ::= 'constant'
374/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000375bool LLParser::ParseGlobalType(bool &IsConstant) {
376 if (Lex.getKind() == lltok::kw_constant)
377 IsConstant = true;
378 else if (Lex.getKind() == lltok::kw_global)
379 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000380 else {
381 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000382 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000383 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 Lex.Lex();
385 return false;
386}
387
Dan Gohman466876b2009-08-12 23:32:33 +0000388/// ParseUnnamedGlobal:
389/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000390/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
391/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000392/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000393/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
394/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000395bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
397 std::string Name;
398 LocTy NameLoc = Lex.getLoc();
399
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000404 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000405 Lex.Lex(); // eat GlobalID;
406
407 if (ParseToken(lltok::equal, "expected '=' after name"))
408 return true;
409 }
410
411 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000412 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000413 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000414 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000415 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000416 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000417 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000418 ParseOptionalThreadLocal(TLM) ||
419 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000420 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000421
Rafael Espindola464fe022014-07-30 22:51:54 +0000422 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000423 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000424 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000425 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000426 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000427}
428
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429/// ParseNamedGlobal:
430/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000431/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
432/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000433bool LLParser::ParseNamedGlobal() {
434 assert(Lex.getKind() == lltok::GlobalVar);
435 LocTy NameLoc = Lex.getLoc();
436 std::string Name = Lex.getStrVal();
437 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000438
Chris Lattnerac161bf2009-01-02 07:01:27 +0000439 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000440 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000441 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000442 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
444 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000445 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000446 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000447 ParseOptionalThreadLocal(TLM) ||
448 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000450
Rafael Espindola464fe022014-07-30 22:51:54 +0000451 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000452 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000453 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000454
455 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000456 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000457}
458
David Majnemerdad0a642014-06-27 18:19:56 +0000459bool LLParser::parseComdat() {
460 assert(Lex.getKind() == lltok::ComdatVar);
461 std::string Name = Lex.getStrVal();
462 LocTy NameLoc = Lex.getLoc();
463 Lex.Lex();
464
465 if (ParseToken(lltok::equal, "expected '=' here"))
466 return true;
467
468 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
469 return TokError("expected comdat type");
470
471 Comdat::SelectionKind SK;
472 switch (Lex.getKind()) {
473 default:
474 return TokError("unknown selection kind");
475 case lltok::kw_any:
476 SK = Comdat::Any;
477 break;
478 case lltok::kw_exactmatch:
479 SK = Comdat::ExactMatch;
480 break;
481 case lltok::kw_largest:
482 SK = Comdat::Largest;
483 break;
484 case lltok::kw_noduplicates:
485 SK = Comdat::NoDuplicates;
486 break;
487 case lltok::kw_samesize:
488 SK = Comdat::SameSize;
489 break;
490 }
491 Lex.Lex();
492
493 // See if the comdat was forward referenced, if so, use the comdat.
494 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
495 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
496 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
497 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
498
499 Comdat *C;
500 if (I != ComdatSymTab.end())
501 C = &I->second;
502 else
503 C = M->getOrInsertComdat(Name);
504 C->setSelectionKind(SK);
505
506 return false;
507}
508
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000509// MDString:
510// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000511bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000512 std::string Str;
513 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000514 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000515 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000516 return false;
517}
518
519// MDNode:
520// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000521//
522/// This version of ParseMDNodeID returns the slot number and null in the case
523/// of a forward reference.
524bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
525 // !{ ..., !42, ... }
526 if (ParseUInt32(SlotNo)) return true;
527
528 // Check existing MDNode.
Craig Topper2617dcc2014-04-15 06:32:26 +0000529 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +0000530 Result = NumberedMetadata[SlotNo];
531 else
Craig Topper2617dcc2014-04-15 06:32:26 +0000532 Result = nullptr;
Chris Lattner8eff0152010-04-01 05:14:45 +0000533 return false;
534}
535
Chris Lattner6dac02a2009-12-30 04:15:23 +0000536bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000537 // !{ ..., !42, ... }
538 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000539 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000540
Chris Lattner8eff0152010-04-01 05:14:45 +0000541 // If not a forward reference, just return it now.
542 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543
Chris Lattner8eff0152010-04-01 05:14:45 +0000544 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000545 MDNodeFwdDecl *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000546 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000547
Chris Lattnerfc58af22009-12-30 04:51:58 +0000548 if (NumberedMetadata.size() <= MID)
549 NumberedMetadata.resize(MID+1);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000550 NumberedMetadata[MID].reset(FwdNode);
Chris Lattner1797fc72009-12-29 21:53:55 +0000551 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000552 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000553}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000554
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000555/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000556/// !foo = !{ !1, !2 }
557bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000558 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000559 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000560 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000561
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000562 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000563 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000564 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000565 return true;
566
Dan Gohman2637cc12010-07-21 23:38:33 +0000567 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000568 if (Lex.getKind() != lltok::rbrace)
569 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000570 if (ParseToken(lltok::exclaim, "Expected '!' here"))
571 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000572
Craig Topper2617dcc2014-04-15 06:32:26 +0000573 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000574 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000575 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000576 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000577
578 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
579 return true;
580
Devang Patelbe626972009-07-29 00:34:02 +0000581 return false;
582}
583
Devang Patel39e64d42009-07-01 19:21:12 +0000584/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000585/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000586bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000587 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000588 Lex.Lex();
589 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000590
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000591 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000592 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000593 ParseToken(lltok::equal, "expected '=' here"))
594 return true;
595
596 // Detect common error, from old metadata syntax.
597 if (Lex.getKind() == lltok::Type)
598 return TokError("unexpected type in metadata definition");
599
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000600 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000601 if (ParseToken(lltok::exclaim, "Expected '!' here") ||
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000602 ParseMDNode(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000603 return true;
604
Chris Lattnerfc58af22009-12-30 04:51:58 +0000605 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000606 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000607 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000608 auto *Temp = FI->second.first;
Dan Gohman16a5d982010-08-20 22:02:26 +0000609 Temp->replaceAllUsesWith(Init);
610 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000611 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000612
Chris Lattnerfc58af22009-12-30 04:51:58 +0000613 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
614 } else {
615 if (MetadataID >= NumberedMetadata.size())
616 NumberedMetadata.resize(MetadataID+1);
617
Craig Topper2617dcc2014-04-15 06:32:26 +0000618 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000619 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000620 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000621 }
622
Devang Patel39e64d42009-07-01 19:21:12 +0000623 return false;
624}
625
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000626static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
627 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
628 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
629}
630
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000632/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
633/// OptionalDLLStorageClass OptionalThreadLocal
634/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000635///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000636/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000637/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000638///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000639/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000640///
Rafael Espindola464fe022014-07-30 22:51:54 +0000641bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000642 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000643 GlobalVariable::ThreadLocalMode TLM,
644 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000645 assert(Lex.getKind() == lltok::kw_alias);
646 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000647
Rafael Espindola78527052013-10-06 15:10:43 +0000648 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
649
Rafael Espindolacaa43562013-10-09 16:07:32 +0000650 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000651 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000652
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000653 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000654 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000655 "symbol with local linkage must have default visibility");
656
Rafael Espindola64c1e182014-06-03 02:41:57 +0000657 Constant *Aliasee;
658 LocTy AliaseeLoc = Lex.getLoc();
659 if (Lex.getKind() != lltok::kw_bitcast &&
660 Lex.getKind() != lltok::kw_getelementptr &&
661 Lex.getKind() != lltok::kw_addrspacecast &&
662 Lex.getKind() != lltok::kw_inttoptr) {
663 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000664 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000665 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000666 // The bitcast dest type is not present, it is implied by the dest type.
667 ValID ID;
668 if (ParseValID(ID))
669 return true;
670 if (ID.Kind != ValID::t_Constant)
671 return Error(AliaseeLoc, "invalid aliasee");
672 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000673 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000674
Rafael Espindola64c1e182014-06-03 02:41:57 +0000675 Type *AliaseeType = Aliasee->getType();
676 auto *PTy = dyn_cast<PointerType>(AliaseeType);
677 if (!PTy)
678 return Error(AliaseeLoc, "An alias must have pointer type");
679 Type *Ty = PTy->getElementType();
680 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000681
682 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000683 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000684 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
685 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000686 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000687 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000688 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000689 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000690
Chris Lattnerac161bf2009-01-02 07:01:27 +0000691 // See if this value already exists in the symbol table. If so, it is either
692 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000693 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000694 // See if this was a redefinition. If so, there is no entry in
695 // ForwardRefVals.
696 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
697 I = ForwardRefVals.find(Name);
698 if (I == ForwardRefVals.end())
699 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
700
701 // Otherwise, this was a definition of forward ref. Verify that types
702 // agree.
703 if (Val->getType() != GA->getType())
704 return Error(NameLoc,
705 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000706
Chris Lattnerac161bf2009-01-02 07:01:27 +0000707 // If they agree, just RAUW the old value with the alias and remove the
708 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000709 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000710 Val->eraseFromParent();
711 ForwardRefVals.erase(I);
712 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000713
Chris Lattnerac161bf2009-01-02 07:01:27 +0000714 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000715 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000716 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000717
Rafael Espindolaaa273822014-05-09 21:49:17 +0000718 // The module owns this now
719 GA.release();
720
Chris Lattnerac161bf2009-01-02 07:01:27 +0000721 return false;
722}
723
724/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000725/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000726/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000727/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000728/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000729/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000730/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000731///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000732/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000733/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000734///
735bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
736 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000737 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000738 GlobalVariable::ThreadLocalMode TLM,
739 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000740 if (!isValidVisibilityForLinkage(Visibility, Linkage))
741 return Error(NameLoc,
742 "symbol with local linkage must have default visibility");
743
Chris Lattnerac161bf2009-01-02 07:01:27 +0000744 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000745 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000746 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000748
Craig Topper2617dcc2014-04-15 06:32:26 +0000749 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000750 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000751 ParseOptionalToken(lltok::kw_externally_initialized,
752 IsExternallyInitialized,
753 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000754 ParseGlobalType(IsConstant) ||
755 ParseType(Ty, TyLoc))
756 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757
Chris Lattnerac161bf2009-01-02 07:01:27 +0000758 // If the linkage is specified and is external, then no initializer is
759 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000760 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000761 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000762 Linkage != GlobalValue::ExternalLinkage)) {
763 if (ParseGlobalValue(Ty, Init))
764 return true;
765 }
766
Duncan Sands19d0b472010-02-16 11:11:14 +0000767 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000768 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000769
David Majnemer598bd052014-12-09 05:56:09 +0000770 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000771
772 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000773 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000774 GVal = M->getNamedValue(Name);
775 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000776 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
777 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000778 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 } else {
780 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
781 I = ForwardRefValIDs.find(NumberedVals.size());
782 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000783 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000784 ForwardRefValIDs.erase(I);
785 }
786 }
787
David Majnemer598bd052014-12-09 05:56:09 +0000788 GlobalVariable *GV;
789 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000790 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
791 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000792 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000793 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000794 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000795 return Error(TyLoc,
796 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000797
David Majnemer598bd052014-12-09 05:56:09 +0000798 GV = cast<GlobalVariable>(GVal);
799
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 // Move the forward-reference to the correct spot in the module.
801 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
802 }
803
804 if (Name.empty())
805 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattnerac161bf2009-01-02 07:01:27 +0000807 // Set the parsed properties on the global.
808 if (Init)
809 GV->setInitializer(Init);
810 GV->setConstant(IsConstant);
811 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
812 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000813 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000814 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000815 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000816 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000817
Chris Lattnerac161bf2009-01-02 07:01:27 +0000818 // Parse attributes on the global.
819 while (Lex.getKind() == lltok::comma) {
820 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000821
Chris Lattnerac161bf2009-01-02 07:01:27 +0000822 if (Lex.getKind() == lltok::kw_section) {
823 Lex.Lex();
824 GV->setSection(Lex.getStrVal());
825 if (ParseToken(lltok::StringConstant, "expected global section string"))
826 return true;
827 } else if (Lex.getKind() == lltok::kw_align) {
828 unsigned Alignment;
829 if (ParseOptionalAlignment(Alignment)) return true;
830 GV->setAlignment(Alignment);
831 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000832 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000833 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000834 return true;
835 if (C)
836 GV->setComdat(C);
837 else
838 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839 }
840 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000841
Chris Lattnerac161bf2009-01-02 07:01:27 +0000842 return false;
843}
844
Bill Wendling63b88192013-02-06 06:52:58 +0000845/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000846/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000847bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000848 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000849 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000850 Lex.Lex();
851
David Majnemerb39e22b2014-12-09 18:33:57 +0000852 if (Lex.getKind() != lltok::AttrGrpID)
853 return TokError("expected attribute group id");
854
Bill Wendling63b88192013-02-06 06:52:58 +0000855 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000856 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000857 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000858 Lex.Lex();
859
860 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000861 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000862 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000863 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000864 ParseToken(lltok::rbrace, "expected end of attribute group"))
865 return true;
866
Bill Wendlingb32b0412013-02-08 06:32:06 +0000867 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000868 return Error(AttrGrpLoc, "attribute group has no attributes");
869
870 return false;
871}
872
Bill Wendling8b0321d2013-02-08 00:52:31 +0000873/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000874/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000875bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
876 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000877 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000878 bool HaveError = false;
879
880 B.clear();
881
Bill Wendling63b88192013-02-06 06:52:58 +0000882 while (true) {
883 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000884 if (Token == lltok::kw_builtin)
885 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000886 switch (Token) {
887 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000888 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000889 return Error(Lex.getLoc(), "unterminated attribute group");
890 case lltok::rbrace:
891 // Finished.
892 return false;
893
Bill Wendlingb32b0412013-02-08 06:32:06 +0000894 case lltok::AttrGrpID: {
895 // Allow a function to reference an attribute group:
896 //
897 // define void @foo() #1 { ... }
898 if (inAttrGrp)
899 HaveError |=
900 Error(Lex.getLoc(),
901 "cannot have an attribute group reference in an attribute group");
902
903 unsigned AttrGrpNum = Lex.getUIntVal();
904 if (inAttrGrp) break;
905
906 // Save the reference to the attribute group. We'll fill it in later.
907 FwdRefAttrGrps.push_back(AttrGrpNum);
908 break;
909 }
Bill Wendling63b88192013-02-06 06:52:58 +0000910 // Target-dependent attributes:
911 case lltok::StringConstant: {
912 std::string Attr = Lex.getStrVal();
913 Lex.Lex();
914 std::string Val;
915 if (EatIfPresent(lltok::equal) &&
916 ParseStringConstant(Val))
917 return true;
918
919 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000920 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000921 }
922
923 // Target-independent attributes:
924 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000925 // As a hack, we allow function alignment to be initially parsed as an
926 // attribute on a function declaration/definition or added to an attribute
927 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000928 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000929 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000930 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
933 return true;
934 } else {
935 if (ParseOptionalAlignment(Alignment))
936 return true;
937 }
Bill Wendling63b88192013-02-06 06:52:58 +0000938 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000940 }
941 case lltok::kw_alignstack: {
942 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000943 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000944 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000945 if (ParseToken(lltok::equal, "expected '=' here") ||
946 ParseUInt32(Alignment))
947 return true;
948 } else {
949 if (ParseOptionalStackAlignment(Alignment))
950 return true;
951 }
Bill Wendling63b88192013-02-06 06:52:58 +0000952 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000953 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000954 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000955 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000956 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000957 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000958 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000959 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000960 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
961 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
962 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
963 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
964 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
965 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
966 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
967 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
968 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
969 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000970 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000971 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
972 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
973 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
974 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
975 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
976 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
977 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
978 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
979 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
980 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
981 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000982
983 // Error handling.
984 case lltok::kw_inreg:
985 case lltok::kw_signext:
986 case lltok::kw_zeroext:
987 HaveError |=
988 Error(Lex.getLoc(),
989 "invalid use of attribute on a function");
990 break;
991 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000992 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +0000993 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000994 case lltok::kw_nest:
995 case lltok::kw_noalias:
996 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000997 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000998 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000999 case lltok::kw_sret:
1000 HaveError |=
1001 Error(Lex.getLoc(),
1002 "invalid use of parameter-only attribute on a function");
1003 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001004 }
1005
1006 Lex.Lex();
1007 }
1008}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001009
1010//===----------------------------------------------------------------------===//
1011// GlobalValue Reference/Resolution Routines.
1012//===----------------------------------------------------------------------===//
1013
1014/// GetGlobalVal - Get a value with the specified name or ID, creating a
1015/// forward reference record if needed. This can return null if the value
1016/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001017GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001018 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001019 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001020 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001021 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001022 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001023 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001024
Chris Lattnerac161bf2009-01-02 07:01:27 +00001025 // Look this name up in the normal function symbol table.
1026 GlobalValue *Val =
1027 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001028
Chris Lattnerac161bf2009-01-02 07:01:27 +00001029 // If this is a forward reference for the value, see if we already created a
1030 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001031 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001032 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1033 I = ForwardRefVals.find(Name);
1034 if (I != ForwardRefVals.end())
1035 Val = I->second.first;
1036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001037
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 // If we have the value in the symbol table or fwd-ref table, return it.
1039 if (Val) {
1040 if (Val->getType() == Ty) return Val;
1041 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001042 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001043 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001044 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattnerac161bf2009-01-02 07:01:27 +00001046 // Otherwise, create a new forward reference for this value and remember it.
1047 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001048 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001049 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001050 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001051 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1053 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001054 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001055
Chris Lattnerac161bf2009-01-02 07:01:27 +00001056 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1057 return FwdVal;
1058}
1059
Chris Lattner229907c2011-07-18 04:54:35 +00001060GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1061 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001062 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001063 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001064 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001065 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001066
Craig Topper2617dcc2014-04-15 06:32:26 +00001067 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001068
Chris Lattnerac161bf2009-01-02 07:01:27 +00001069 // If this is a forward reference for the value, see if we already created a
1070 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001071 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1073 I = ForwardRefValIDs.find(ID);
1074 if (I != ForwardRefValIDs.end())
1075 Val = I->second.first;
1076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 // If we have the value in the symbol table or fwd-ref table, return it.
1079 if (Val) {
1080 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001081 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001082 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001083 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001085
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 // Otherwise, create a new forward reference for this value and remember it.
1087 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001088 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001089 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001090 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001091 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001092 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001093
Chris Lattnerac161bf2009-01-02 07:01:27 +00001094 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1095 return FwdVal;
1096}
1097
1098
1099//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001100// Comdat Reference/Resolution Routines.
1101//===----------------------------------------------------------------------===//
1102
1103Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1104 // Look this name up in the comdat symbol table.
1105 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1106 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1107 if (I != ComdatSymTab.end())
1108 return &I->second;
1109
1110 // Otherwise, create a new forward reference for this value and remember it.
1111 Comdat *C = M->getOrInsertComdat(Name);
1112 ForwardRefComdats[Name] = Loc;
1113 return C;
1114}
1115
1116
1117//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001118// Helper Routines.
1119//===----------------------------------------------------------------------===//
1120
1121/// ParseToken - If the current token has the specified kind, eat it and return
1122/// success. Otherwise, emit the specified error and return failure.
1123bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1124 if (Lex.getKind() != T)
1125 return TokError(ErrMsg);
1126 Lex.Lex();
1127 return false;
1128}
1129
Chris Lattner3822f632009-01-02 08:05:26 +00001130/// ParseStringConstant
1131/// ::= StringConstant
1132bool LLParser::ParseStringConstant(std::string &Result) {
1133 if (Lex.getKind() != lltok::StringConstant)
1134 return TokError("expected string constant");
1135 Result = Lex.getStrVal();
1136 Lex.Lex();
1137 return false;
1138}
1139
1140/// ParseUInt32
1141/// ::= uint32
1142bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001143 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1144 return TokError("expected integer");
1145 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1146 if (Val64 != unsigned(Val64))
1147 return TokError("expected 32-bit integer (too large)");
1148 Val = Val64;
1149 Lex.Lex();
1150 return false;
1151}
1152
Hal Finkelb0407ba2014-07-18 15:51:28 +00001153/// ParseUInt64
1154/// ::= uint64
1155bool LLParser::ParseUInt64(uint64_t &Val) {
1156 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1157 return TokError("expected integer");
1158 Val = Lex.getAPSIntVal().getLimitedValue();
1159 Lex.Lex();
1160 return false;
1161}
1162
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001163/// ParseTLSModel
1164/// := 'localdynamic'
1165/// := 'initialexec'
1166/// := 'localexec'
1167bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1168 switch (Lex.getKind()) {
1169 default:
1170 return TokError("expected localdynamic, initialexec or localexec");
1171 case lltok::kw_localdynamic:
1172 TLM = GlobalVariable::LocalDynamicTLSModel;
1173 break;
1174 case lltok::kw_initialexec:
1175 TLM = GlobalVariable::InitialExecTLSModel;
1176 break;
1177 case lltok::kw_localexec:
1178 TLM = GlobalVariable::LocalExecTLSModel;
1179 break;
1180 }
1181
1182 Lex.Lex();
1183 return false;
1184}
1185
1186/// ParseOptionalThreadLocal
1187/// := /*empty*/
1188/// := 'thread_local'
1189/// := 'thread_local' '(' tlsmodel ')'
1190bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1191 TLM = GlobalVariable::NotThreadLocal;
1192 if (!EatIfPresent(lltok::kw_thread_local))
1193 return false;
1194
1195 TLM = GlobalVariable::GeneralDynamicTLSModel;
1196 if (Lex.getKind() == lltok::lparen) {
1197 Lex.Lex();
1198 return ParseTLSModel(TLM) ||
1199 ParseToken(lltok::rparen, "expected ')' after thread local model");
1200 }
1201 return false;
1202}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203
1204/// ParseOptionalAddrSpace
1205/// := /*empty*/
1206/// := 'addrspace' '(' uint32 ')'
1207bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1208 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001209 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001211 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001212 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001214}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001215
Bill Wendling34c2eb22012-12-04 23:40:58 +00001216/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1217bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1218 bool HaveError = false;
1219
1220 B.clear();
1221
1222 while (1) {
1223 lltok::Kind Token = Lex.getKind();
1224 switch (Token) {
1225 default: // End of attributes.
1226 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 case lltok::kw_align: {
1228 unsigned Alignment;
1229 if (ParseOptionalAlignment(Alignment))
1230 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001231 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232 continue;
1233 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001234 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001235 case lltok::kw_dereferenceable: {
1236 uint64_t Bytes;
1237 if (ParseOptionalDereferenceableBytes(Bytes))
1238 return true;
1239 B.addDereferenceableAttr(Bytes);
1240 continue;
1241 }
Reid Klecknera534a382013-12-19 02:14:12 +00001242 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001243 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1244 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1245 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1246 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001247 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001248 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1249 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001250 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001251 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1252 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1253 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001254
Stephen Lin7577ed52013-04-20 13:16:13 +00001255 case lltok::kw_alignstack:
1256 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001257 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001258 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001259 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001260 case lltok::kw_minsize:
1261 case lltok::kw_naked:
1262 case lltok::kw_nobuiltin:
1263 case lltok::kw_noduplicate:
1264 case lltok::kw_noimplicitfloat:
1265 case lltok::kw_noinline:
1266 case lltok::kw_nonlazybind:
1267 case lltok::kw_noredzone:
1268 case lltok::kw_noreturn:
1269 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001270 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001271 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001272 case lltok::kw_returns_twice:
1273 case lltok::kw_sanitize_address:
1274 case lltok::kw_sanitize_memory:
1275 case lltok::kw_sanitize_thread:
1276 case lltok::kw_ssp:
1277 case lltok::kw_sspreq:
1278 case lltok::kw_sspstrong:
1279 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001280 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1281 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001282 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001283
Bill Wendling34c2eb22012-12-04 23:40:58 +00001284 Lex.Lex();
1285 }
1286}
1287
1288/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1289bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1290 bool HaveError = false;
1291
1292 B.clear();
1293
1294 while (1) {
1295 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001296 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001297 default: // End of attributes.
1298 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001299 case lltok::kw_dereferenceable: {
1300 uint64_t Bytes;
1301 if (ParseOptionalDereferenceableBytes(Bytes))
1302 return true;
1303 B.addDereferenceableAttr(Bytes);
1304 continue;
1305 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001306 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1307 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001308 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001309 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1310 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001311
Bill Wendling34c2eb22012-12-04 23:40:58 +00001312 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001313 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001314 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001315 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001316 case lltok::kw_nest:
1317 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001318 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001319 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001320 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001321 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001322
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001323 case lltok::kw_alignstack:
1324 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001325 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001326 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001327 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001328 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001329 case lltok::kw_minsize:
1330 case lltok::kw_naked:
1331 case lltok::kw_nobuiltin:
1332 case lltok::kw_noduplicate:
1333 case lltok::kw_noimplicitfloat:
1334 case lltok::kw_noinline:
1335 case lltok::kw_nonlazybind:
1336 case lltok::kw_noredzone:
1337 case lltok::kw_noreturn:
1338 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001339 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001340 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001341 case lltok::kw_returns_twice:
1342 case lltok::kw_sanitize_address:
1343 case lltok::kw_sanitize_memory:
1344 case lltok::kw_sanitize_thread:
1345 case lltok::kw_ssp:
1346 case lltok::kw_sspreq:
1347 case lltok::kw_sspstrong:
1348 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001349 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001350 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001351
1352 case lltok::kw_readnone:
1353 case lltok::kw_readonly:
1354 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001355 }
1356
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357 Lex.Lex();
1358 }
1359}
1360
1361/// ParseOptionalLinkage
1362/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001363/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364/// ::= 'internal'
1365/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001366/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001367/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001368/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001369/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001370/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001371/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372/// ::= 'extern_weak'
1373/// ::= 'external'
1374bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1375 HasLinkage = false;
1376 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001377 default: Res=GlobalValue::ExternalLinkage; return false;
1378 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001379 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1380 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1381 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1382 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1383 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001384 case lltok::kw_available_externally:
1385 Res = GlobalValue::AvailableExternallyLinkage;
1386 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001387 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001388 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001389 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1390 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391 }
1392 Lex.Lex();
1393 HasLinkage = true;
1394 return false;
1395}
1396
1397/// ParseOptionalVisibility
1398/// ::= /*empty*/
1399/// ::= 'default'
1400/// ::= 'hidden'
1401/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001402///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001403bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1404 switch (Lex.getKind()) {
1405 default: Res = GlobalValue::DefaultVisibility; return false;
1406 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1407 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1408 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1409 }
1410 Lex.Lex();
1411 return false;
1412}
1413
Nico Rieck7157bb72014-01-14 15:22:47 +00001414/// ParseOptionalDLLStorageClass
1415/// ::= /*empty*/
1416/// ::= 'dllimport'
1417/// ::= 'dllexport'
1418///
1419bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1420 switch (Lex.getKind()) {
1421 default: Res = GlobalValue::DefaultStorageClass; return false;
1422 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1423 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1424 }
1425 Lex.Lex();
1426 return false;
1427}
1428
Chris Lattnerac161bf2009-01-02 07:01:27 +00001429/// ParseOptionalCallingConv
1430/// ::= /*empty*/
1431/// ::= 'ccc'
1432/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001433/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001434/// ::= 'coldcc'
1435/// ::= 'x86_stdcallcc'
1436/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001437/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001438/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001439/// ::= 'arm_apcscc'
1440/// ::= 'arm_aapcscc'
1441/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001442/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001443/// ::= 'ptx_kernel'
1444/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001445/// ::= 'spir_func'
1446/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001447/// ::= 'x86_64_sysvcc'
1448/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001449/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001450/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001451/// ::= 'preserve_mostcc'
1452/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001453/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001454/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001455///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001456bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001457 switch (Lex.getKind()) {
1458 default: CC = CallingConv::C; return false;
1459 case lltok::kw_ccc: CC = CallingConv::C; break;
1460 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1461 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1462 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1463 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001464 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001465 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001466 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1467 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1468 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001469 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001470 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1471 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001472 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1473 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001474 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001475 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1476 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001477 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001478 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001479 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1480 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001481 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001482 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001483 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001484 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001485 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001486 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001487
Chris Lattnerac161bf2009-01-02 07:01:27 +00001488 Lex.Lex();
1489 return false;
1490}
1491
Chris Lattner5c427632009-12-30 05:31:19 +00001492/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001493/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001494bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1495 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001496 do {
1497 if (Lex.getKind() != lltok::MetadataVar)
1498 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001499
Chris Lattner596760d2009-12-29 21:25:40 +00001500 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001501 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001502 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001503
Dan Gohmanc828c542010-08-24 02:24:03 +00001504 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001505 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001506
Duncan P. N. Exon Smithab617d52015-01-12 21:13:09 +00001507 // This code is similar to that of ParseMetadata. However, only MDNodes
1508 // are supported here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001509 if (Lex.getKind() == lltok::lbrace) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001510 MDNode *N;
1511 if (ParseMDNode(N))
Dan Gohmanc828c542010-08-24 02:24:03 +00001512 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001513 Inst->setMetadata(MDK, N);
Chris Lattner8eff0152010-04-01 05:14:45 +00001514 } else {
Duncan P. N. Exon Smithab617d52015-01-12 21:13:09 +00001515 MDNode *Node;
1516 if (ParseMDNodeID(Node))
Dan Gohmanc828c542010-08-24 02:24:03 +00001517 return true;
Duncan P. N. Exon Smithab617d52015-01-12 21:13:09 +00001518 // If we got the node, add it to the instruction.
1519 Inst->setMetadata(MDK, Node);
Chris Lattner8eff0152010-04-01 05:14:45 +00001520 }
Chris Lattner596760d2009-12-29 21:25:40 +00001521
Manman Ren209b17c2013-09-28 00:22:27 +00001522 if (MDK == LLVMContext::MD_tbaa)
1523 InstsWithTBAATag.push_back(Inst);
1524
Chris Lattner596760d2009-12-29 21:25:40 +00001525 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001526 } while (EatIfPresent(lltok::comma));
1527 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001528}
1529
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530/// ParseOptionalAlignment
1531/// ::= /* empty */
1532/// ::= 'align' 4
1533bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1534 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001535 if (!EatIfPresent(lltok::kw_align))
1536 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001537 LocTy AlignLoc = Lex.getLoc();
1538 if (ParseUInt32(Alignment)) return true;
1539 if (!isPowerOf2_32(Alignment))
1540 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001541 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001542 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001543 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001544}
1545
Hal Finkelb0407ba2014-07-18 15:51:28 +00001546/// ParseOptionalDereferenceableBytes
1547/// ::= /* empty */
1548/// ::= 'dereferenceable' '(' 4 ')'
1549bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1550 Bytes = 0;
1551 if (!EatIfPresent(lltok::kw_dereferenceable))
1552 return false;
1553 LocTy ParenLoc = Lex.getLoc();
1554 if (!EatIfPresent(lltok::lparen))
1555 return Error(ParenLoc, "expected '('");
1556 LocTy DerefLoc = Lex.getLoc();
1557 if (ParseUInt64(Bytes)) return true;
1558 ParenLoc = Lex.getLoc();
1559 if (!EatIfPresent(lltok::rparen))
1560 return Error(ParenLoc, "expected ')'");
1561 if (!Bytes)
1562 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1563 return false;
1564}
1565
Chris Lattnerb2f39502009-12-30 05:44:30 +00001566/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001567/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001568/// ::= ',' align 4
1569///
1570/// This returns with AteExtraComma set to true if it ate an excess comma at the
1571/// end.
1572bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1573 bool &AteExtraComma) {
1574 AteExtraComma = false;
1575 while (EatIfPresent(lltok::comma)) {
1576 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001577 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001578 AteExtraComma = true;
1579 return false;
1580 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001581
Chris Lattner95b0ff42010-04-23 00:50:50 +00001582 if (Lex.getKind() != lltok::kw_align)
1583 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001584
Chris Lattner95b0ff42010-04-23 00:50:50 +00001585 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001586 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001587
Devang Patelea8a4b92009-09-17 23:04:48 +00001588 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001589}
1590
Eli Friedmanfee02c62011-07-25 23:16:38 +00001591/// ParseScopeAndOrdering
1592/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1593/// else: ::=
1594///
1595/// This sets Scope and Ordering to the parsed values.
1596bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1597 AtomicOrdering &Ordering) {
1598 if (!isAtomic)
1599 return false;
1600
1601 Scope = CrossThread;
1602 if (EatIfPresent(lltok::kw_singlethread))
1603 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001604
1605 return ParseOrdering(Ordering);
1606}
1607
1608/// ParseOrdering
1609/// ::= AtomicOrdering
1610///
1611/// This sets Ordering to the parsed value.
1612bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001613 switch (Lex.getKind()) {
1614 default: return TokError("Expected ordering on atomic instruction");
1615 case lltok::kw_unordered: Ordering = Unordered; break;
1616 case lltok::kw_monotonic: Ordering = Monotonic; break;
1617 case lltok::kw_acquire: Ordering = Acquire; break;
1618 case lltok::kw_release: Ordering = Release; break;
1619 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1620 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1621 }
1622 Lex.Lex();
1623 return false;
1624}
1625
Charles Davisbe5557e2010-02-12 00:31:15 +00001626/// ParseOptionalStackAlignment
1627/// ::= /* empty */
1628/// ::= 'alignstack' '(' 4 ')'
1629bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1630 Alignment = 0;
1631 if (!EatIfPresent(lltok::kw_alignstack))
1632 return false;
1633 LocTy ParenLoc = Lex.getLoc();
1634 if (!EatIfPresent(lltok::lparen))
1635 return Error(ParenLoc, "expected '('");
1636 LocTy AlignLoc = Lex.getLoc();
1637 if (ParseUInt32(Alignment)) return true;
1638 ParenLoc = Lex.getLoc();
1639 if (!EatIfPresent(lltok::rparen))
1640 return Error(ParenLoc, "expected ')'");
1641 if (!isPowerOf2_32(Alignment))
1642 return Error(AlignLoc, "stack alignment is not a power of two");
1643 return false;
1644}
Devang Patelea8a4b92009-09-17 23:04:48 +00001645
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001646/// ParseIndexList - This parses the index list for an insert/extractvalue
1647/// instruction. This sets AteExtraComma in the case where we eat an extra
1648/// comma at the end of the line and find that it is followed by metadata.
1649/// Clients that don't allow metadata can call the version of this function that
1650/// only takes one argument.
1651///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001652/// ParseIndexList
1653/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001654///
1655bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1656 bool &AteExtraComma) {
1657 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001658
Chris Lattnerac161bf2009-01-02 07:01:27 +00001659 if (Lex.getKind() != lltok::comma)
1660 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001661
Chris Lattner3822f632009-01-02 08:05:26 +00001662 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001663 if (Lex.getKind() == lltok::MetadataVar) {
1664 AteExtraComma = true;
1665 return false;
1666 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001667 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001668 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001669 Indices.push_back(Idx);
1670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001671
Chris Lattnerac161bf2009-01-02 07:01:27 +00001672 return false;
1673}
1674
1675//===----------------------------------------------------------------------===//
1676// Type Parsing.
1677//===----------------------------------------------------------------------===//
1678
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001680bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001681 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682 switch (Lex.getKind()) {
1683 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001684 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001686 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001687 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001688 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001689 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001690 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001691 // Type ::= StructType
1692 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001693 return true;
1694 break;
1695 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001696 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001697 Lex.Lex(); // eat the lsquare.
1698 if (ParseArrayVectorType(Result, false))
1699 return true;
1700 break;
1701 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001702 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001703 Lex.Lex();
1704 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001705 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001706 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001707 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001708 } else if (ParseArrayVectorType(Result, true))
1709 return true;
1710 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711 case lltok::LocalVar: {
1712 // Type ::= %foo
1713 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001714
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 // If the type hasn't been defined yet, create a forward definition and
1716 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001717 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001718 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001719 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001720 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001721 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 Lex.Lex();
1723 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001725
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001726 case lltok::LocalVarID: {
1727 // Type ::= %4
1728 if (Lex.getUIntVal() >= NumberedTypes.size())
1729 NumberedTypes.resize(Lex.getUIntVal()+1);
1730 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001731
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 // If the type hasn't been defined yet, create a forward definition and
1733 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001734 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001735 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001736 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001738 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 Lex.Lex();
1740 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001741 }
1742 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001743
1744 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001745 while (1) {
1746 switch (Lex.getKind()) {
1747 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001748 default:
1749 if (!AllowVoid && Result->isVoidTy())
1750 return Error(TypeLoc, "void type only allowed for function results");
1751 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001755 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001757 if (Result->isVoidTy())
1758 return TokError("pointers to void are invalid - use i8* instead");
1759 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001760 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001762 Lex.Lex();
1763 break;
1764
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001765 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001766 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001767 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001768 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001769 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001770 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001771 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001772 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 unsigned AddrSpace;
1774 if (ParseOptionalAddrSpace(AddrSpace) ||
1775 ParseToken(lltok::star, "expected '*' in address space"))
1776 return true;
1777
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001778 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779 break;
1780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001781
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1783 case lltok::lparen:
1784 if (ParseFunctionType(Result))
1785 return true;
1786 break;
1787 }
1788 }
1789}
1790
1791/// ParseParameterList
1792/// ::= '(' ')'
1793/// ::= '(' Arg (',' Arg)* ')'
1794/// Arg
1795/// ::= Type OptionalAttributes Value OptionalAttributes
1796bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001797 PerFunctionState &PFS, bool IsMustTailCall,
1798 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001799 if (ParseToken(lltok::lparen, "expected '(' in call"))
1800 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001801
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001802 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 while (Lex.getKind() != lltok::rparen) {
1804 // If this isn't the first argument, we need a comma.
1805 if (!ArgList.empty() &&
1806 ParseToken(lltok::comma, "expected ',' in argument list"))
1807 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001808
Reid Kleckner83498642014-08-26 00:33:28 +00001809 // Parse an ellipsis if this is a musttail call in a variadic function.
1810 if (Lex.getKind() == lltok::dotdotdot) {
1811 const char *Msg = "unexpected ellipsis in argument list for ";
1812 if (!IsMustTailCall)
1813 return TokError(Twine(Msg) + "non-musttail call");
1814 if (!InVarArgsFunc)
1815 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1816 Lex.Lex(); // Lex the '...', it is purely for readability.
1817 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1818 }
1819
Chris Lattnerac161bf2009-01-02 07:01:27 +00001820 // Parse the argument.
1821 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001822 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001823 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001824 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001825 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001826 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001827
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001828 if (ArgTy->isMetadataTy()) {
1829 if (ParseMetadataAsValue(V, PFS))
1830 return true;
1831 } else {
1832 // Otherwise, handle normal operands.
1833 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1834 return true;
1835 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001836 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1837 AttrIndex++,
1838 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839 }
1840
Reid Kleckner83498642014-08-26 00:33:28 +00001841 if (IsMustTailCall && InVarArgsFunc)
1842 return TokError("expected '...' at end of argument list for musttail call "
1843 "in varargs function");
1844
Chris Lattnerac161bf2009-01-02 07:01:27 +00001845 Lex.Lex(); // Lex the ')'.
1846 return false;
1847}
1848
1849
1850
Chris Lattner2ed06b42009-01-05 18:34:07 +00001851/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001852/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853/// ::= '(' ArgTypeListI ')'
1854/// ArgTypeListI
1855/// ::= /*empty*/
1856/// ::= '...'
1857/// ::= ArgTypeList ',' '...'
1858/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001859///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001860bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1861 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001862 isVarArg = false;
1863 assert(Lex.getKind() == lltok::lparen);
1864 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001865
Chris Lattnerac161bf2009-01-02 07:01:27 +00001866 if (Lex.getKind() == lltok::rparen) {
1867 // empty
1868 } else if (Lex.getKind() == lltok::dotdotdot) {
1869 isVarArg = true;
1870 Lex.Lex();
1871 } else {
1872 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001873 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001874 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001876
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001877 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001878 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001879
Chris Lattnerfdd87902009-10-05 05:54:46 +00001880 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001881 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001882
Chris Lattnerdef19492011-06-17 06:36:20 +00001883 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001884 Name = Lex.getStrVal();
1885 Lex.Lex();
1886 }
Chris Lattner3822f632009-01-02 08:05:26 +00001887
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001888 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001889 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001890
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001891 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001892 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001893 AttributeSet::get(ArgTy->getContext(),
1894 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001895
Chris Lattner3822f632009-01-02 08:05:26 +00001896 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001897 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001898 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001899 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900 break;
1901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001902
Chris Lattnerac161bf2009-01-02 07:01:27 +00001903 // Otherwise must be an argument type.
1904 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001905 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001906
Chris Lattnerfdd87902009-10-05 05:54:46 +00001907 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001908 return Error(TypeLoc, "argument can not have void type");
1909
Chris Lattnerdef19492011-06-17 06:36:20 +00001910 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 Name = Lex.getStrVal();
1912 Lex.Lex();
1913 } else {
1914 Name = "";
1915 }
Chris Lattner3822f632009-01-02 08:05:26 +00001916
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001918 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001919
Bill Wendlingd079a442012-10-15 04:46:55 +00001920 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001921 AttributeSet::get(ArgTy->getContext(),
1922 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001923 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924 }
1925 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001926
Chris Lattner3822f632009-01-02 08:05:26 +00001927 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001929
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930/// ParseFunctionType
1931/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933 assert(Lex.getKind() == lltok::lparen);
1934
Chris Lattnerce473c72009-01-05 08:04:33 +00001935 if (!FunctionType::isValidReturnType(Result))
1936 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001938 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001939 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001940 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001941 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001942
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943 // Reject names on the arguments lists.
1944 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1945 if (!ArgList[i].Name.empty())
1946 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001947 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001948 return Error(ArgList[i].Loc,
1949 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001950 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001951
Jay Foadb804a2b2011-07-12 14:06:48 +00001952 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001953 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001954 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001956 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957 return false;
1958}
1959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1961/// other structs.
1962bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1963 SmallVector<Type*, 8> Elts;
1964 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001966 Result = StructType::get(Context, Elts, Packed);
1967 return false;
1968}
1969
1970/// ParseStructDefinition - Parse a struct in a 'type' definition.
1971bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1972 std::pair<Type*, LocTy> &Entry,
1973 Type *&ResultTy) {
1974 // If the type was already defined, diagnose the redefinition.
1975 if (Entry.first && !Entry.second.isValid())
1976 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001977
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 // If we have opaque, just return without filling in the definition for the
1979 // struct. This counts as a definition as far as the .ll file goes.
1980 if (EatIfPresent(lltok::kw_opaque)) {
1981 // This type is being defined, so clear the location to indicate this.
1982 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001985 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001986 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 ResultTy = Entry.first;
1988 return false;
1989 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001990
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001991 // If the type starts with '<', then it is either a packed struct or a vector.
1992 bool isPacked = EatIfPresent(lltok::less);
1993
1994 // If we don't have a struct, then we have a random type alias, which we
1995 // accept for compatibility with old files. These types are not allowed to be
1996 // forward referenced and not allowed to be recursive.
1997 if (Lex.getKind() != lltok::lbrace) {
1998 if (Entry.first)
1999 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002000
Craig Topper2617dcc2014-04-15 06:32:26 +00002001 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002 if (isPacked)
2003 return ParseArrayVectorType(ResultTy, true);
2004 return ParseType(ResultTy);
2005 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002006
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 // This type is being defined, so clear the location to indicate this.
2008 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002011 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002012 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002016 SmallVector<Type*, 8> Body;
2017 if (ParseStructBody(Body) ||
2018 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2019 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002020
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021 STy->setBody(Body, isPacked);
2022 ResultTy = STy;
2023 return false;
2024}
2025
2026
Chris Lattnerac161bf2009-01-02 07:01:27 +00002027/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032/// ::= '<' '{' Type (',' Type)* '}' '>'
2033bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002034 assert(Lex.getKind() == lltok::lbrace);
2035 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002036
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 // Handle the empty struct.
2038 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002039 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002040
Chris Lattnerf880ca22009-03-09 04:49:14 +00002041 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002042 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043 if (ParseType(Ty)) return true;
2044 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002045
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002046 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002047 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002048
Chris Lattner3822f632009-01-02 08:05:26 +00002049 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002050 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002052
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002054 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002055
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002058
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002060}
2061
2062/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2063/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002064/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065/// ::= '[' APSINTVAL 'x' Types ']'
2066/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002067bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2069 Lex.getAPSIntVal().getBitWidth() > 64)
2070 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002071
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 LocTy SizeLoc = Lex.getLoc();
2073 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002074 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075
Chris Lattner3822f632009-01-02 08:05:26 +00002076 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2077 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078
2079 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002080 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002082
Chris Lattner3822f632009-01-02 08:05:26 +00002083 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2084 "expected end of sequential type"))
2085 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002086
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002088 if (Size == 0)
2089 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002090 if ((unsigned)Size != Size)
2091 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002092 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002093 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002094 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002096 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002097 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002098 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 }
2100 return false;
2101}
2102
2103//===----------------------------------------------------------------------===//
2104// Function Semantic Analysis.
2105//===----------------------------------------------------------------------===//
2106
Chris Lattner3432c622009-10-28 03:39:23 +00002107LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2108 int functionNumber)
2109 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110
2111 // Insert unnamed arguments into the NumberedVals list.
2112 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2113 AI != E; ++AI)
2114 if (!AI->hasName())
2115 NumberedVals.push_back(AI);
2116}
2117
2118LLParser::PerFunctionState::~PerFunctionState() {
2119 // If there were any forward referenced non-basicblock values, delete them.
2120 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2121 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2122 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002123 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002124 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002126 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002128
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2130 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2131 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002132 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002133 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002135 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 }
2137}
2138
Chris Lattner3432c622009-10-28 03:39:23 +00002139bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 if (!ForwardRefVals.empty())
2141 return P.Error(ForwardRefVals.begin()->second.second,
2142 "use of undefined value '%" + ForwardRefVals.begin()->first +
2143 "'");
2144 if (!ForwardRefValIDs.empty())
2145 return P.Error(ForwardRefValIDs.begin()->second.second,
2146 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002147 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 return false;
2149}
2150
2151
2152/// GetVal - Get a value with the specified name or ID, creating a
2153/// forward reference record if needed. This can return null if the value
2154/// exists but does not have the right type.
2155Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002156 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 // Look this name up in the normal function symbol table.
2158 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002159
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 // If this is a forward reference for the value, see if we already created a
2161 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002162 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2164 I = ForwardRefVals.find(Name);
2165 if (I != ForwardRefVals.end())
2166 Val = I->second.first;
2167 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002168
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 // If we have the value in the symbol table or fwd-ref table, return it.
2170 if (Val) {
2171 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002172 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 P.Error(Loc, "'%" + Name + "' is not a basic block");
2174 else
2175 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002176 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002177 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002179
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002181 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002183 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002185
Chris Lattnerac161bf2009-01-02 07:01:27 +00002186 // Otherwise, create a new forward reference for this value and remember it.
2187 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002188 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002189 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 else
2191 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002192
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2194 return FwdVal;
2195}
2196
Chris Lattner229907c2011-07-18 04:54:35 +00002197Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 LocTy Loc) {
2199 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002200 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002201
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202 // If this is a forward reference for the value, see if we already created a
2203 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002204 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2206 I = ForwardRefValIDs.find(ID);
2207 if (I != ForwardRefValIDs.end())
2208 Val = I->second.first;
2209 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattnerac161bf2009-01-02 07:01:27 +00002211 // If we have the value in the symbol table or fwd-ref table, return it.
2212 if (Val) {
2213 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002214 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002215 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002217 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002218 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002219 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002221
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002222 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002223 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002224 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattnerac161bf2009-01-02 07:01:27 +00002227 // Otherwise, create a new forward reference for this value and remember it.
2228 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002229 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002230 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 else
2232 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2235 return FwdVal;
2236}
2237
2238/// SetInstName - After an instruction is parsed and inserted into its
2239/// basic block, this installs its name.
2240bool LLParser::PerFunctionState::SetInstName(int NameID,
2241 const std::string &NameStr,
2242 LocTy NameLoc, Instruction *Inst) {
2243 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002244 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 if (NameID != -1 || !NameStr.empty())
2246 return P.Error(NameLoc, "instructions returning void cannot have a name");
2247 return false;
2248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 // If this was a numbered instruction, verify that the instruction is the
2251 // expected value and resolve any forward references.
2252 if (NameStr.empty()) {
2253 // If neither a name nor an ID was specified, just use the next ID.
2254 if (NameID == -1)
2255 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002256
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 if (unsigned(NameID) != NumberedVals.size())
2258 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002259 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002260
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2262 ForwardRefValIDs.find(NameID);
2263 if (FI != ForwardRefValIDs.end()) {
2264 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002266 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002268 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269 ForwardRefValIDs.erase(FI);
2270 }
2271
2272 NumberedVals.push_back(Inst);
2273 return false;
2274 }
2275
2276 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2277 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2278 FI = ForwardRefVals.find(NameStr);
2279 if (FI != ForwardRefVals.end()) {
2280 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002282 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002284 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 ForwardRefVals.erase(FI);
2286 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002287
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 // Set the name on the instruction.
2289 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002291 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002292 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 NameStr + "'");
2294 return false;
2295}
2296
2297/// GetBB - Get a basic block with the specified name or ID, creating a
2298/// forward reference record if needed.
2299BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2300 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002301 return cast_or_null<BasicBlock>(GetVal(Name,
2302 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303}
2304
2305BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002306 return cast_or_null<BasicBlock>(GetVal(ID,
2307 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308}
2309
2310/// DefineBB - Define the specified basic block, which is either named or
2311/// unnamed. If there is an error, this returns null otherwise it returns
2312/// the block being defined.
2313BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2314 LocTy Loc) {
2315 BasicBlock *BB;
2316 if (Name.empty())
2317 BB = GetBB(NumberedVals.size(), Loc);
2318 else
2319 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002320 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002321
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322 // Move the block to the end of the function. Forward ref'd blocks are
2323 // inserted wherever they happen to be referenced.
2324 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002325
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 // Remove the block from forward ref sets.
2327 if (Name.empty()) {
2328 ForwardRefValIDs.erase(NumberedVals.size());
2329 NumberedVals.push_back(BB);
2330 } else {
2331 // BB forward references are already in the function symbol table.
2332 ForwardRefVals.erase(Name);
2333 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002334
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335 return BB;
2336}
2337
2338//===----------------------------------------------------------------------===//
2339// Constants.
2340//===----------------------------------------------------------------------===//
2341
2342/// ParseValID - Parse an abstract value that doesn't necessarily have a
2343/// type implied. For example, if we parse "4" we don't know what integer type
2344/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002345/// sanity. PFS is used to convert function-local operands of metadata (since
2346/// metadata operands are not just parsed here but also converted to values).
2347/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002348bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 ID.Loc = Lex.getLoc();
2350 switch (Lex.getKind()) {
2351 default: return TokError("expected value token");
2352 case lltok::GlobalID: // @42
2353 ID.UIntVal = Lex.getUIntVal();
2354 ID.Kind = ValID::t_GlobalID;
2355 break;
2356 case lltok::GlobalVar: // @foo
2357 ID.StrVal = Lex.getStrVal();
2358 ID.Kind = ValID::t_GlobalName;
2359 break;
2360 case lltok::LocalVarID: // %42
2361 ID.UIntVal = Lex.getUIntVal();
2362 ID.Kind = ValID::t_LocalID;
2363 break;
2364 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002365 ID.StrVal = Lex.getStrVal();
2366 ID.Kind = ValID::t_LocalName;
2367 break;
2368 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 ID.Kind = ValID::t_APSInt;
2371 break;
2372 case lltok::APFloat:
2373 ID.APFloatVal = Lex.getAPFloatVal();
2374 ID.Kind = ValID::t_APFloat;
2375 break;
2376 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002377 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 ID.Kind = ValID::t_Constant;
2379 break;
2380 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002381 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 ID.Kind = ValID::t_Constant;
2383 break;
2384 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2385 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2386 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002387
Chris Lattnerac161bf2009-01-02 07:01:27 +00002388 case lltok::lbrace: {
2389 // ValID ::= '{' ConstVector '}'
2390 Lex.Lex();
2391 SmallVector<Constant*, 16> Elts;
2392 if (ParseGlobalValueVector(Elts) ||
2393 ParseToken(lltok::rbrace, "expected end of struct constant"))
2394 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 ID.ConstantStructElts = new Constant*[Elts.size()];
2397 ID.UIntVal = Elts.size();
2398 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2399 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 return false;
2401 }
2402 case lltok::less: {
2403 // ValID ::= '<' ConstVector '>' --> Vector.
2404 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2405 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002406 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002407
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 SmallVector<Constant*, 16> Elts;
2409 LocTy FirstEltLoc = Lex.getLoc();
2410 if (ParseGlobalValueVector(Elts) ||
2411 (isPackedStruct &&
2412 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2413 ParseToken(lltok::greater, "expected end of constant"))
2414 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002415
Chris Lattnerac161bf2009-01-02 07:01:27 +00002416 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002417 ID.ConstantStructElts = new Constant*[Elts.size()];
2418 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2419 ID.UIntVal = Elts.size();
2420 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421 return false;
2422 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002423
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424 if (Elts.empty())
2425 return Error(ID.Loc, "constant vector must not be empty");
2426
Duncan Sands9dff9be2010-02-15 16:12:20 +00002427 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002428 !Elts[0]->getType()->isFloatingPointTy() &&
2429 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002431 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002432
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433 // Verify that all the vector elements have the same type.
2434 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2435 if (Elts[i]->getType() != Elts[0]->getType())
2436 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002437 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002438 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002439
Chris Lattner69229312011-02-15 00:14:00 +00002440 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002441 ID.Kind = ValID::t_Constant;
2442 return false;
2443 }
2444 case lltok::lsquare: { // Array Constant
2445 Lex.Lex();
2446 SmallVector<Constant*, 16> Elts;
2447 LocTy FirstEltLoc = Lex.getLoc();
2448 if (ParseGlobalValueVector(Elts) ||
2449 ParseToken(lltok::rsquare, "expected end of array constant"))
2450 return true;
2451
2452 // Handle empty element.
2453 if (Elts.empty()) {
2454 // Use undef instead of an array because it's inconvenient to determine
2455 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002456 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457 return false;
2458 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002459
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002461 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002462 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Owen Anderson4056ca92009-07-29 22:17:13 +00002464 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002465
Chris Lattnerac161bf2009-01-02 07:01:27 +00002466 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002467 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002468 if (Elts[i]->getType() != Elts[0]->getType())
2469 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002470 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002471 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002473
Jay Foad83be3612011-06-22 09:24:39 +00002474 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 ID.Kind = ValID::t_Constant;
2476 return false;
2477 }
2478 case lltok::kw_c: // c "foo"
2479 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002480 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2481 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002482 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2483 ID.Kind = ValID::t_Constant;
2484 return false;
2485
2486 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002487 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2488 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002489 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 Lex.Lex();
2491 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002492 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002493 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002494 ParseStringConstant(ID.StrVal) ||
2495 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 ParseToken(lltok::StringConstant, "expected constraint string"))
2497 return true;
2498 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002499 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002500 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 ID.Kind = ValID::t_InlineAsm;
2502 return false;
2503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattner3432c622009-10-28 03:39:23 +00002505 case lltok::kw_blockaddress: {
2506 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2507 Lex.Lex();
2508
2509 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002510
Chris Lattner3432c622009-10-28 03:39:23 +00002511 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2512 ParseValID(Fn) ||
2513 ParseToken(lltok::comma, "expected comma in block address expression")||
2514 ParseValID(Label) ||
2515 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2516 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002517
Chris Lattner3432c622009-10-28 03:39:23 +00002518 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2519 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002520 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002521 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002522
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002523 // Try to find the function (but skip it if it's forward-referenced).
2524 GlobalValue *GV = nullptr;
2525 if (Fn.Kind == ValID::t_GlobalID) {
2526 if (Fn.UIntVal < NumberedVals.size())
2527 GV = NumberedVals[Fn.UIntVal];
2528 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2529 GV = M->getNamedValue(Fn.StrVal);
2530 }
2531 Function *F = nullptr;
2532 if (GV) {
2533 // Confirm that it's actually a function with a definition.
2534 if (!isa<Function>(GV))
2535 return Error(Fn.Loc, "expected function name in blockaddress");
2536 F = cast<Function>(GV);
2537 if (F->isDeclaration())
2538 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2539 }
2540
2541 if (!F) {
2542 // Make a global variable as a placeholder for this reference.
2543 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2544 if (!FwdRef)
2545 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2546 GlobalValue::InternalLinkage, nullptr, "");
2547 ID.ConstantVal = FwdRef;
2548 ID.Kind = ValID::t_Constant;
2549 return false;
2550 }
2551
2552 // We found the function; now find the basic block. Don't use PFS, since we
2553 // might be inside a constant expression.
2554 BasicBlock *BB;
2555 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2556 if (Label.Kind == ValID::t_LocalID)
2557 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2558 else
2559 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2560 if (!BB)
2561 return Error(Label.Loc, "referenced value is not a basic block");
2562 } else {
2563 if (Label.Kind == ValID::t_LocalID)
2564 return Error(Label.Loc, "cannot take address of numeric label after "
2565 "the function is defined");
2566 BB = dyn_cast_or_null<BasicBlock>(
2567 F->getValueSymbolTable().lookup(Label.StrVal));
2568 if (!BB)
2569 return Error(Label.Loc, "referenced value is not a basic block");
2570 }
2571
2572 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002573 ID.Kind = ValID::t_Constant;
2574 return false;
2575 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002576
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 case lltok::kw_trunc:
2578 case lltok::kw_zext:
2579 case lltok::kw_sext:
2580 case lltok::kw_fptrunc:
2581 case lltok::kw_fpext:
2582 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002583 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002584 case lltok::kw_uitofp:
2585 case lltok::kw_sitofp:
2586 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002587 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002589 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002590 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002591 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 Constant *SrcVal;
2593 Lex.Lex();
2594 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2595 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002596 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 ParseType(DestTy) ||
2598 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2599 return true;
2600 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2601 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002602 getTypeString(SrcVal->getType()) + "' to '" +
2603 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002604 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002605 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002606 ID.Kind = ValID::t_Constant;
2607 return false;
2608 }
2609 case lltok::kw_extractvalue: {
2610 Lex.Lex();
2611 Constant *Val;
2612 SmallVector<unsigned, 4> Indices;
2613 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2614 ParseGlobalTypeAndValue(Val) ||
2615 ParseIndexList(Indices) ||
2616 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2617 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002618
Chris Lattner392be582010-02-12 20:49:41 +00002619 if (!Val->getType()->isAggregateType())
2620 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002621 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002623 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 ID.Kind = ValID::t_Constant;
2625 return false;
2626 }
2627 case lltok::kw_insertvalue: {
2628 Lex.Lex();
2629 Constant *Val0, *Val1;
2630 SmallVector<unsigned, 4> Indices;
2631 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2632 ParseGlobalTypeAndValue(Val0) ||
2633 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2634 ParseGlobalTypeAndValue(Val1) ||
2635 ParseIndexList(Indices) ||
2636 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2637 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002638 if (!Val0->getType()->isAggregateType())
2639 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002640 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002642 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 ID.Kind = ValID::t_Constant;
2644 return false;
2645 }
2646 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002647 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 unsigned PredVal, Opc = Lex.getUIntVal();
2649 Constant *Val0, *Val1;
2650 Lex.Lex();
2651 if (ParseCmpPredicate(PredVal, Opc) ||
2652 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2653 ParseGlobalTypeAndValue(Val0) ||
2654 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2655 ParseGlobalTypeAndValue(Val1) ||
2656 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2657 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002658
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 if (Val0->getType() != Val1->getType())
2660 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002661
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663
Chris Lattnerac161bf2009-01-02 07:01:27 +00002664 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002665 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002667 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002668 } else {
2669 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002670 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002671 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002672 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002673 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 }
2675 ID.Kind = ValID::t_Constant;
2676 return false;
2677 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002678
Chris Lattnerac161bf2009-01-02 07:01:27 +00002679 // Binary Operators.
2680 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002681 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002682 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002683 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002684 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002685 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 case lltok::kw_udiv:
2687 case lltok::kw_sdiv:
2688 case lltok::kw_fdiv:
2689 case lltok::kw_urem:
2690 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002691 case lltok::kw_frem:
2692 case lltok::kw_shl:
2693 case lltok::kw_lshr:
2694 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002695 bool NUW = false;
2696 bool NSW = false;
2697 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 unsigned Opc = Lex.getUIntVal();
2699 Constant *Val0, *Val1;
2700 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002701 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002702 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2703 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002704 if (EatIfPresent(lltok::kw_nuw))
2705 NUW = true;
2706 if (EatIfPresent(lltok::kw_nsw)) {
2707 NSW = true;
2708 if (EatIfPresent(lltok::kw_nuw))
2709 NUW = true;
2710 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002711 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2712 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002713 if (EatIfPresent(lltok::kw_exact))
2714 Exact = true;
2715 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2717 ParseGlobalTypeAndValue(Val0) ||
2718 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2719 ParseGlobalTypeAndValue(Val1) ||
2720 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2721 return true;
2722 if (Val0->getType() != Val1->getType())
2723 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002724 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002725 if (NUW)
2726 return Error(ModifierLoc, "nuw only applies to integer operations");
2727 if (NSW)
2728 return Error(ModifierLoc, "nsw only applies to integer operations");
2729 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002730 // Check that the type is valid for the operator.
2731 switch (Opc) {
2732 case Instruction::Add:
2733 case Instruction::Sub:
2734 case Instruction::Mul:
2735 case Instruction::UDiv:
2736 case Instruction::SDiv:
2737 case Instruction::URem:
2738 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002739 case Instruction::Shl:
2740 case Instruction::AShr:
2741 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002742 if (!Val0->getType()->isIntOrIntVectorTy())
2743 return Error(ID.Loc, "constexpr requires integer operands");
2744 break;
2745 case Instruction::FAdd:
2746 case Instruction::FSub:
2747 case Instruction::FMul:
2748 case Instruction::FDiv:
2749 case Instruction::FRem:
2750 if (!Val0->getType()->isFPOrFPVectorTy())
2751 return Error(ID.Loc, "constexpr requires fp operands");
2752 break;
2753 default: llvm_unreachable("Unknown binary operator!");
2754 }
Dan Gohman1b849082009-09-07 23:54:19 +00002755 unsigned Flags = 0;
2756 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2757 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002758 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002759 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002760 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 ID.Kind = ValID::t_Constant;
2762 return false;
2763 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002764
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 case lltok::kw_and:
2767 case lltok::kw_or:
2768 case lltok::kw_xor: {
2769 unsigned Opc = Lex.getUIntVal();
2770 Constant *Val0, *Val1;
2771 Lex.Lex();
2772 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2773 ParseGlobalTypeAndValue(Val0) ||
2774 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2775 ParseGlobalTypeAndValue(Val1) ||
2776 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2777 return true;
2778 if (Val0->getType() != Val1->getType())
2779 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002780 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 return Error(ID.Loc,
2782 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002783 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 ID.Kind = ValID::t_Constant;
2785 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002786 }
2787
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 case lltok::kw_getelementptr:
2789 case lltok::kw_shufflevector:
2790 case lltok::kw_insertelement:
2791 case lltok::kw_extractelement:
2792 case lltok::kw_select: {
2793 unsigned Opc = Lex.getUIntVal();
2794 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002795 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002797 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002798 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2800 ParseGlobalValueVector(Elts) ||
2801 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2802 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002803
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002805 if (Elts.size() == 0 ||
2806 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002807 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808
Jay Foaded8db7d2011-07-21 14:31:17 +00002809 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002810 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002812 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2813 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002814 } else if (Opc == Instruction::Select) {
2815 if (Elts.size() != 3)
2816 return Error(ID.Loc, "expected three operands to select");
2817 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2818 Elts[2]))
2819 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002820 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 } else if (Opc == Instruction::ShuffleVector) {
2822 if (Elts.size() != 3)
2823 return Error(ID.Loc, "expected three operands to shufflevector");
2824 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2825 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002826 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002827 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 } else if (Opc == Instruction::ExtractElement) {
2829 if (Elts.size() != 2)
2830 return Error(ID.Loc, "expected two operands to extractelement");
2831 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2832 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002833 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002834 } else {
2835 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2836 if (Elts.size() != 3)
2837 return Error(ID.Loc, "expected three operands to insertelement");
2838 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2839 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002840 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002841 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002842 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002843
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 ID.Kind = ValID::t_Constant;
2845 return false;
2846 }
2847 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002848
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 Lex.Lex();
2850 return false;
2851}
2852
2853/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002854bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002855 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002857 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002858 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002859 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002860 if (V && !(C = dyn_cast<Constant>(V)))
2861 return Error(ID.Loc, "global values must be constants");
2862 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863}
2864
Victor Hernandez9d75c962010-01-11 22:31:58 +00002865bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002866 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002867 return ParseType(Ty) ||
2868 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002869}
2870
Rafael Espindola83a362c2015-01-06 22:55:16 +00002871bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002872 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002873
2874 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002875 if (!EatIfPresent(lltok::kw_comdat))
2876 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002877
2878 if (EatIfPresent(lltok::lparen)) {
2879 if (Lex.getKind() != lltok::ComdatVar)
2880 return TokError("expected comdat variable");
2881 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2882 Lex.Lex();
2883 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2884 return true;
2885 } else {
2886 if (GlobalName.empty())
2887 return TokError("comdat cannot be unnamed");
2888 C = getComdat(GlobalName, KwLoc);
2889 }
2890
David Majnemerdad0a642014-06-27 18:19:56 +00002891 return false;
2892}
2893
Victor Hernandez9d75c962010-01-11 22:31:58 +00002894/// ParseGlobalValueVector
2895/// ::= /*empty*/
2896/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002897bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002898 // Empty list.
2899 if (Lex.getKind() == lltok::rbrace ||
2900 Lex.getKind() == lltok::rsquare ||
2901 Lex.getKind() == lltok::greater ||
2902 Lex.getKind() == lltok::rparen)
2903 return false;
2904
2905 Constant *C;
2906 if (ParseGlobalTypeAndValue(C)) return true;
2907 Elts.push_back(C);
2908
2909 while (EatIfPresent(lltok::comma)) {
2910 if (ParseGlobalTypeAndValue(C)) return true;
2911 Elts.push_back(C);
2912 }
2913
2914 return false;
2915}
2916
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002917bool LLParser::ParseMDNode(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002918 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002919 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002920 return true;
2921
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002922 if (IsDistinct)
2923 MD = MDNode::getDistinct(Context, Elts);
2924 else
2925 MD = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002926 return false;
2927}
2928
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002929/// ParseMetadataAsValue
2930/// ::= metadata i32 %local
2931/// ::= metadata i32 @global
2932/// ::= metadata i32 7
2933/// ::= metadata !0
2934/// ::= metadata !{...}
2935/// ::= metadata !"string"
2936bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
2937 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002938 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002939 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002940 return true;
2941
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002942 V = MetadataAsValue::get(Context, MD);
2943 return false;
2944}
2945
2946/// ParseValueAsMetadata
2947/// ::= i32 %local
2948/// ::= i32 @global
2949/// ::= i32 7
2950bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
2951 Type *Ty;
2952 LocTy Loc;
2953 if (ParseType(Ty, "expected metadata operand", Loc))
2954 return true;
2955 if (Ty->isMetadataTy())
2956 return Error(Loc, "invalid metadata-value-metadata roundtrip");
2957
2958 Value *V;
2959 if (ParseValue(Ty, V, PFS))
2960 return true;
2961
2962 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002963 return false;
2964}
2965
2966/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002967/// ::= i32 %local
2968/// ::= i32 @global
2969/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00002970/// ::= !42
2971/// ::= !{...}
2972/// ::= !"string"
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002973bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002974 // ValueAsMetadata:
2975 // <type> <value>
2976 if (Lex.getKind() != lltok::exclaim)
2977 return ParseValueAsMetadata(MD, PFS);
2978
2979 // '!'.
2980 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
2981 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00002982
2983 // MDNode:
2984 // !{ ... }
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002985 if (Lex.getKind() == lltok::lbrace) {
2986 MDNode *N;
2987 if (ParseMDNode(N))
2988 return true;
2989 MD = N;
2990 return false;
2991 }
Dan Gohman8939ba332010-07-14 18:26:50 +00002992
2993 // Standalone metadata reference
2994 // !42
2995 if (Lex.getKind() == lltok::APSInt) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002996 MDNode *N;
2997 if (ParseMDNodeID(N))
2998 return true;
2999 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003000 return false;
3001 }
3002
3003 // MDString:
3004 // ::= '!' STRINGCONSTANT
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003005 MDString *S;
3006 if (ParseMDString(S))
3007 return true;
3008 MD = S;
Dan Gohman8939ba332010-07-14 18:26:50 +00003009 return false;
3010}
3011
Victor Hernandez9d75c962010-01-11 22:31:58 +00003012
3013//===----------------------------------------------------------------------===//
3014// Function Parsing.
3015//===----------------------------------------------------------------------===//
3016
Chris Lattner229907c2011-07-18 04:54:35 +00003017bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003018 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003019 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003021
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003024 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3025 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003026 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003028 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3029 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003030 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003031 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003032 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003033 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003034 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003035 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3036 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003037 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003038 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003039 return false;
3040 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 case ValID::t_GlobalName:
3042 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003043 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003044 case ValID::t_GlobalID:
3045 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003046 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003048 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003050 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003051 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 return false;
3053 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003054 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3056 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003057
Dan Gohman518cda42011-12-17 00:04:22 +00003058 // The lexer has no type info, so builds all half, float, and double FP
3059 // constants as double. Fix this here. Long double does not need this.
3060 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003061 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003062 if (Ty->isHalfTy())
3063 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3064 &Ignored);
3065 else if (Ty->isFloatTy())
3066 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3067 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003069 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003070
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003071 if (V->getType() != Ty)
3072 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003073 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003074
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075 return false;
3076 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003077 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003079 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 return false;
3081 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003082 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003083 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003084 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003085 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003087 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003088 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003089 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003090 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003091 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003092 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003093 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003094 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003095 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003096 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 return false;
3098 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003099 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003100 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003101
Chris Lattnerac161bf2009-01-02 07:01:27 +00003102 V = ID.ConstantVal;
3103 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003104 case ValID::t_ConstantStruct:
3105 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003106 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003107 if (ST->getNumElements() != ID.UIntVal)
3108 return Error(ID.Loc,
3109 "initializer with struct type has wrong # elements");
3110 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3111 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003112
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003113 // Verify that the elements are compatible with the structtype.
3114 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3115 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3116 return Error(ID.Loc, "element " + Twine(i) +
3117 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003118
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003119 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3120 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003121 } else
3122 return Error(ID.Loc, "constant expression type mismatch");
3123 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003125 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003126}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003127
Chris Lattner229907c2011-07-18 04:54:35 +00003128bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003129 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003130 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003131 return ParseValID(ID, PFS) ||
3132 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003133}
3134
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003135bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003136 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003137 return ParseType(Ty) ||
3138 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003139}
3140
Chris Lattner3ed871f2009-10-27 19:13:16 +00003141bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3142 PerFunctionState &PFS) {
3143 Value *V;
3144 Loc = Lex.getLoc();
3145 if (ParseTypeAndValue(V, PFS)) return true;
3146 if (!isa<BasicBlock>(V))
3147 return Error(Loc, "expected a basic block");
3148 BB = cast<BasicBlock>(V);
3149 return false;
3150}
3151
3152
Chris Lattnerac161bf2009-01-02 07:01:27 +00003153/// FunctionHeader
3154/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003155/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003156/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003157bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3158 // Parse the linkage.
3159 LocTy LinkageLoc = Lex.getLoc();
3160 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003161
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003162 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003163 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003164 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003165 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003166 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003167 LocTy RetTypeLoc = Lex.getLoc();
3168 if (ParseOptionalLinkage(Linkage) ||
3169 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003170 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003171 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003172 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003173 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 return true;
3175
3176 // Verify that the linkage is ok.
3177 switch ((GlobalValue::LinkageTypes)Linkage) {
3178 case GlobalValue::ExternalLinkage:
3179 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003180 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 if (isDefine)
3182 return Error(LinkageLoc, "invalid linkage for function definition");
3183 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003184 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003185 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003186 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003187 case GlobalValue::LinkOnceAnyLinkage:
3188 case GlobalValue::LinkOnceODRLinkage:
3189 case GlobalValue::WeakAnyLinkage:
3190 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003191 if (!isDefine)
3192 return Error(LinkageLoc, "invalid linkage for function declaration");
3193 break;
3194 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003195 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003196 return Error(LinkageLoc, "invalid function linkage type");
3197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003199 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3200 return Error(LinkageLoc,
3201 "symbol with local linkage must have default visibility");
3202
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003203 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003204 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003205
Chris Lattnerac161bf2009-01-02 07:01:27 +00003206 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003207
3208 std::string FunctionName;
3209 if (Lex.getKind() == lltok::GlobalVar) {
3210 FunctionName = Lex.getStrVal();
3211 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3212 unsigned NameID = Lex.getUIntVal();
3213
3214 if (NameID != NumberedVals.size())
3215 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003216 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003217 } else {
3218 return TokError("expected function name");
3219 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003220
Chris Lattner3822f632009-01-02 08:05:26 +00003221 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003222
Chris Lattner3822f632009-01-02 08:05:26 +00003223 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003224 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003225
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003226 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003227 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003228 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003229 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003230 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003231 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003232 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003233 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003234 bool UnnamedAddr;
3235 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003236 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003237 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003238 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003239
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003240 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003241 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3242 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003243 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003244 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003245 (EatIfPresent(lltok::kw_section) &&
3246 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00003247 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003248 ParseOptionalAlignment(Alignment) ||
3249 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003250 ParseStringConstant(GC)) ||
3251 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003252 ParseGlobalTypeAndValue(Prefix)) ||
3253 (EatIfPresent(lltok::kw_prologue) &&
3254 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003255 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003256
Michael Gottesman41748d72013-06-27 00:25:01 +00003257 if (FuncAttrs.contains(Attribute::Builtin))
3258 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003259
Chris Lattnerac161bf2009-01-02 07:01:27 +00003260 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003261 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003262 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003263 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003264 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003265
Chris Lattnerac161bf2009-01-02 07:01:27 +00003266 // Okay, if we got here, the function is syntactically valid. Convert types
3267 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003268 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003269 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003270
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003271 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003272 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3273 AttributeSet::ReturnIndex,
3274 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003275
Chris Lattnerac161bf2009-01-02 07:01:27 +00003276 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003277 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003278 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3279 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003280 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3281 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003282 }
3283
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003284 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003285 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3286 AttributeSet::FunctionIndex,
3287 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288
Bill Wendlinge94d8432012-12-07 23:16:57 +00003289 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003290
Bill Wendling749a43d2012-12-30 13:50:49 +00003291 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003292 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3293
Chris Lattner229907c2011-07-18 04:54:35 +00003294 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003295 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003296 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003297
Craig Topper2617dcc2014-04-15 06:32:26 +00003298 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003299 if (!FunctionName.empty()) {
3300 // If this was a definition of a forward reference, remove the definition
3301 // from the forward reference table and fill in the forward ref.
3302 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3303 ForwardRefVals.find(FunctionName);
3304 if (FRVI != ForwardRefVals.end()) {
3305 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003306 if (!Fn)
3307 return Error(FRVI->second.second, "invalid forward reference to "
3308 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003309 if (Fn->getType() != PFT)
3310 return Error(FRVI->second.second, "invalid forward reference to "
3311 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003312
Chris Lattnerac161bf2009-01-02 07:01:27 +00003313 ForwardRefVals.erase(FRVI);
3314 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003315 // Reject redefinitions.
3316 return Error(NameLoc, "invalid redefinition of function '" +
3317 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003318 } else if (M->getNamedValue(FunctionName)) {
3319 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003321
Dan Gohman399d6ae2009-08-29 23:37:49 +00003322 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 // If this is a definition of a forward referenced function, make sure the
3324 // types agree.
3325 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3326 = ForwardRefValIDs.find(NumberedVals.size());
3327 if (I != ForwardRefValIDs.end()) {
3328 Fn = cast<Function>(I->second.first);
3329 if (Fn->getType() != PFT)
3330 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003331 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003332 ForwardRefValIDs.erase(I);
3333 }
3334 }
3335
Craig Topper2617dcc2014-04-15 06:32:26 +00003336 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003337 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3338 else // Move the forward-reference to the correct spot in the module.
3339 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3340
3341 if (FunctionName.empty())
3342 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003343
Chris Lattnerac161bf2009-01-02 07:01:27 +00003344 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3345 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003346 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003347 Fn->setCallingConv(CC);
3348 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003349 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003350 Fn->setAlignment(Alignment);
3351 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003352 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003353 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003354 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003355 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003356 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003357
Chris Lattnerac161bf2009-01-02 07:01:27 +00003358 // Add all of the arguments we parsed to the function.
3359 Function::arg_iterator ArgIt = Fn->arg_begin();
3360 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3361 // If the argument has a name, insert it into the argument symbol table.
3362 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003363
Chris Lattnerac161bf2009-01-02 07:01:27 +00003364 // Set the name, if it conflicted, it will be auto-renamed.
3365 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003366
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003367 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003368 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3369 ArgList[i].Name + "'");
3370 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003371
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003372 if (isDefine)
3373 return false;
3374
Robin Morisset039781e2014-08-29 21:53:01 +00003375 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003376 ValID ID;
3377 if (FunctionName.empty()) {
3378 ID.Kind = ValID::t_GlobalID;
3379 ID.UIntVal = NumberedVals.size() - 1;
3380 } else {
3381 ID.Kind = ValID::t_GlobalName;
3382 ID.StrVal = FunctionName;
3383 }
3384 auto Blocks = ForwardRefBlockAddresses.find(ID);
3385 if (Blocks != ForwardRefBlockAddresses.end())
3386 return Error(Blocks->first.Loc,
3387 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003388 return false;
3389}
3390
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003391bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3392 ValID ID;
3393 if (FunctionNumber == -1) {
3394 ID.Kind = ValID::t_GlobalName;
3395 ID.StrVal = F.getName();
3396 } else {
3397 ID.Kind = ValID::t_GlobalID;
3398 ID.UIntVal = FunctionNumber;
3399 }
3400
3401 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3402 if (Blocks == P.ForwardRefBlockAddresses.end())
3403 return false;
3404
3405 for (const auto &I : Blocks->second) {
3406 const ValID &BBID = I.first;
3407 GlobalValue *GV = I.second;
3408
3409 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3410 "Expected local id or name");
3411 BasicBlock *BB;
3412 if (BBID.Kind == ValID::t_LocalName)
3413 BB = GetBB(BBID.StrVal, BBID.Loc);
3414 else
3415 BB = GetBB(BBID.UIntVal, BBID.Loc);
3416 if (!BB)
3417 return P.Error(BBID.Loc, "referenced value is not a basic block");
3418
3419 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3420 GV->eraseFromParent();
3421 }
3422
3423 P.ForwardRefBlockAddresses.erase(Blocks);
3424 return false;
3425}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003426
3427/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003428/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003429bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003430 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003431 return TokError("expected '{' in function body");
3432 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003433
Chris Lattner3432c622009-10-28 03:39:23 +00003434 int FunctionNumber = -1;
3435 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003436
Chris Lattner3432c622009-10-28 03:39:23 +00003437 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003438
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003439 // Resolve block addresses and allow basic blocks to be forward-declared
3440 // within this function.
3441 if (PFS.resolveForwardRefBlockAddresses())
3442 return true;
3443 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3444
Chris Lattnerbbddd962010-01-09 19:20:07 +00003445 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003446 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003447 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003448
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003449 while (Lex.getKind() != lltok::rbrace &&
3450 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003451 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003452
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003453 while (Lex.getKind() != lltok::rbrace)
3454 if (ParseUseListOrder(&PFS))
3455 return true;
3456
Chris Lattnerac161bf2009-01-02 07:01:27 +00003457 // Eat the }.
3458 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003459
Chris Lattnerac161bf2009-01-02 07:01:27 +00003460 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003461 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003462}
3463
3464/// ParseBasicBlock
3465/// ::= LabelStr? Instruction*
3466bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3467 // If this basic block starts out with a name, remember it.
3468 std::string Name;
3469 LocTy NameLoc = Lex.getLoc();
3470 if (Lex.getKind() == lltok::LabelStr) {
3471 Name = Lex.getStrVal();
3472 Lex.Lex();
3473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003474
Chris Lattnerac161bf2009-01-02 07:01:27 +00003475 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003476 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003477
Chris Lattnerac161bf2009-01-02 07:01:27 +00003478 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003479
Chris Lattnerac161bf2009-01-02 07:01:27 +00003480 // Parse the instructions in this block until we get a terminator.
3481 Instruction *Inst;
3482 do {
3483 // This instruction may have three possibilities for a name: a) none
3484 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3485 LocTy NameLoc = Lex.getLoc();
3486 int NameID = -1;
3487 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003488
Chris Lattnerac161bf2009-01-02 07:01:27 +00003489 if (Lex.getKind() == lltok::LocalVarID) {
3490 NameID = Lex.getUIntVal();
3491 Lex.Lex();
3492 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3493 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003494 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003495 NameStr = Lex.getStrVal();
3496 Lex.Lex();
3497 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3498 return true;
3499 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003500
Chris Lattner77b89dc2009-12-30 05:23:43 +00003501 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003502 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003503 case InstError: return true;
3504 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003505 BB->getInstList().push_back(Inst);
3506
Chris Lattner77b89dc2009-12-30 05:23:43 +00003507 // With a normal result, we check to see if the instruction is followed by
3508 // a comma and metadata.
3509 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003510 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003511 return true;
3512 break;
3513 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003514 BB->getInstList().push_back(Inst);
3515
Chris Lattner77b89dc2009-12-30 05:23:43 +00003516 // If the instruction parser ate an extra comma at the end of it, it
3517 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003518 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003519 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003520 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003521 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003522
Chris Lattnerac161bf2009-01-02 07:01:27 +00003523 // Set the name on the instruction.
3524 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3525 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003526
Chris Lattnerac161bf2009-01-02 07:01:27 +00003527 return false;
3528}
3529
3530//===----------------------------------------------------------------------===//
3531// Instruction Parsing.
3532//===----------------------------------------------------------------------===//
3533
3534/// ParseInstruction - Parse one of the many different instructions.
3535///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003536int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3537 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003538 lltok::Kind Token = Lex.getKind();
3539 if (Token == lltok::Eof)
3540 return TokError("found end of file when expecting more instructions");
3541 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003542 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003543 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003544
Chris Lattnerac161bf2009-01-02 07:01:27 +00003545 switch (Token) {
3546 default: return Error(Loc, "expected instruction opcode");
3547 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003548 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003549 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3550 case lltok::kw_br: return ParseBr(Inst, PFS);
3551 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003552 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003553 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003554 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003555 // Binary Operators.
3556 case lltok::kw_add:
3557 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003558 case lltok::kw_mul:
3559 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003560 bool NUW = EatIfPresent(lltok::kw_nuw);
3561 bool NSW = EatIfPresent(lltok::kw_nsw);
3562 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003563
Chris Lattnera676c0f2011-02-07 16:40:21 +00003564 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003565
Chris Lattnera676c0f2011-02-07 16:40:21 +00003566 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3567 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3568 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003569 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003570 case lltok::kw_fadd:
3571 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003572 case lltok::kw_fmul:
3573 case lltok::kw_fdiv:
3574 case lltok::kw_frem: {
3575 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3576 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3577 if (Res != 0)
3578 return Res;
3579 if (FMF.any())
3580 Inst->setFastMathFlags(FMF);
3581 return 0;
3582 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003583
Chris Lattner35315d02011-02-06 21:44:57 +00003584 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003585 case lltok::kw_udiv:
3586 case lltok::kw_lshr:
3587 case lltok::kw_ashr: {
3588 bool Exact = EatIfPresent(lltok::kw_exact);
3589
3590 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3591 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3592 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003593 }
3594
Chris Lattnerac161bf2009-01-02 07:01:27 +00003595 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003596 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003597 case lltok::kw_and:
3598 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003599 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003600 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003601 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003602 // Casts.
3603 case lltok::kw_trunc:
3604 case lltok::kw_zext:
3605 case lltok::kw_sext:
3606 case lltok::kw_fptrunc:
3607 case lltok::kw_fpext:
3608 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003609 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003610 case lltok::kw_uitofp:
3611 case lltok::kw_sitofp:
3612 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003613 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003614 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003615 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003616 // Other.
3617 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003618 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003619 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3620 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3621 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3622 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003623 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003624 // Call.
3625 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3626 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3627 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003628 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003629 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003630 case lltok::kw_load: return ParseLoad(Inst, PFS);
3631 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003632 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3633 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003634 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003635 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3636 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3637 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3638 }
3639}
3640
3641/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3642bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003643 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003644 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003645 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003646 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3647 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3648 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3649 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3650 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3651 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3652 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3653 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3654 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3655 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3656 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3657 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3658 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3659 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3660 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3661 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3662 }
3663 } else {
3664 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003665 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003666 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3667 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3668 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3669 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3670 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3671 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3672 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3673 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3674 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3675 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3676 }
3677 }
3678 Lex.Lex();
3679 return false;
3680}
3681
3682//===----------------------------------------------------------------------===//
3683// Terminator Instructions.
3684//===----------------------------------------------------------------------===//
3685
3686/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003687/// ::= 'ret' void (',' !dbg, !1)*
3688/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003689bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003690 PerFunctionState &PFS) {
3691 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003692 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003693 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003694
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003695 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003696
Chris Lattnerfdd87902009-10-05 05:54:46 +00003697 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003698 if (!ResType->isVoidTy())
3699 return Error(TypeLoc, "value doesn't match function result type '" +
3700 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003701
Owen Anderson55f1c092009-08-13 21:58:54 +00003702 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003703 return false;
3704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003705
Chris Lattnerac161bf2009-01-02 07:01:27 +00003706 Value *RV;
3707 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003708
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003709 if (ResType != RV->getType())
3710 return Error(TypeLoc, "value doesn't match function result type '" +
3711 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003712
Owen Anderson55f1c092009-08-13 21:58:54 +00003713 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003714 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003715}
3716
3717
3718/// ParseBr
3719/// ::= 'br' TypeAndValue
3720/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3721bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3722 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003723 Value *Op0;
3724 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003725 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003726
Chris Lattnerac161bf2009-01-02 07:01:27 +00003727 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3728 Inst = BranchInst::Create(BB);
3729 return false;
3730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003731
Owen Anderson55f1c092009-08-13 21:58:54 +00003732 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003733 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003734
Chris Lattnerac161bf2009-01-02 07:01:27 +00003735 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003736 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003737 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003738 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003739 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003740
Chris Lattner3ed871f2009-10-27 19:13:16 +00003741 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003742 return false;
3743}
3744
3745/// ParseSwitch
3746/// Instruction
3747/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3748/// JumpTable
3749/// ::= (TypeAndValue ',' TypeAndValue)*
3750bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3751 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003752 Value *Cond;
3753 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003754 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3755 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003756 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003757 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3758 return true;
3759
Duncan Sands19d0b472010-02-16 11:11:14 +00003760 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003761 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003762
Chris Lattnerac161bf2009-01-02 07:01:27 +00003763 // Parse the jump table pairs.
3764 SmallPtrSet<Value*, 32> SeenCases;
3765 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3766 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003767 Value *Constant;
3768 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003769
Chris Lattnerac161bf2009-01-02 07:01:27 +00003770 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3771 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003772 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003773 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003774
David Blaikie70573dc2014-11-19 07:49:26 +00003775 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003776 return Error(CondLoc, "duplicate case value in switch");
3777 if (!isa<ConstantInt>(Constant))
3778 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003779
Chris Lattner3ed871f2009-10-27 19:13:16 +00003780 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003781 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003782
Chris Lattnerac161bf2009-01-02 07:01:27 +00003783 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003784
Chris Lattner3ed871f2009-10-27 19:13:16 +00003785 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003786 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3787 SI->addCase(Table[i].first, Table[i].second);
3788 Inst = SI;
3789 return false;
3790}
3791
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003792/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003793/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003794/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3795bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003796 LocTy AddrLoc;
3797 Value *Address;
3798 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003799 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3800 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003801 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003802
Duncan Sands19d0b472010-02-16 11:11:14 +00003803 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003804 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003805
Chris Lattner3ed871f2009-10-27 19:13:16 +00003806 // Parse the destination list.
3807 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003808
Chris Lattner3ed871f2009-10-27 19:13:16 +00003809 if (Lex.getKind() != lltok::rsquare) {
3810 BasicBlock *DestBB;
3811 if (ParseTypeAndBasicBlock(DestBB, PFS))
3812 return true;
3813 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003814
Chris Lattner3ed871f2009-10-27 19:13:16 +00003815 while (EatIfPresent(lltok::comma)) {
3816 if (ParseTypeAndBasicBlock(DestBB, PFS))
3817 return true;
3818 DestList.push_back(DestBB);
3819 }
3820 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003821
Chris Lattner3ed871f2009-10-27 19:13:16 +00003822 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3823 return true;
3824
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003825 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003826 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3827 IBI->addDestination(DestList[i]);
3828 Inst = IBI;
3829 return false;
3830}
3831
3832
Chris Lattnerac161bf2009-01-02 07:01:27 +00003833/// ParseInvoke
3834/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3835/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3836bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3837 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003838 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003839 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003840 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003841 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003842 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 LocTy RetTypeLoc;
3844 ValID CalleeID;
3845 SmallVector<ParamInfo, 16> ArgList;
3846
Chris Lattner3ed871f2009-10-27 19:13:16 +00003847 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003848 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003849 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003850 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003851 ParseValID(CalleeID) ||
3852 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003853 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3854 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003855 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003856 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003857 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003858 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003859 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003860
Chris Lattnerac161bf2009-01-02 07:01:27 +00003861 // If RetType is a non-function pointer type, then this is the short syntax
3862 // for the call, which means that RetType is just the return type. Infer the
3863 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003864 PointerType *PFTy = nullptr;
3865 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003866 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3867 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3868 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003869 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003870 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3871 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003872
Chris Lattnerac161bf2009-01-02 07:01:27 +00003873 if (!FunctionType::isValidReturnType(RetType))
3874 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003875
Owen Anderson4056ca92009-07-29 22:17:13 +00003876 Ty = FunctionType::get(RetType, ParamTypes, false);
3877 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003878 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003879
Chris Lattnerac161bf2009-01-02 07:01:27 +00003880 // Look up the callee.
3881 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003882 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003883
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003884 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003885 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003886 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003887 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3888 AttributeSet::ReturnIndex,
3889 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003890
Chris Lattnerac161bf2009-01-02 07:01:27 +00003891 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003892
Chris Lattnerac161bf2009-01-02 07:01:27 +00003893 // Loop through FunctionType's arguments and ensure they are specified
3894 // correctly. Also, gather any parameter attributes.
3895 FunctionType::param_iterator I = Ty->param_begin();
3896 FunctionType::param_iterator E = Ty->param_end();
3897 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003898 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003899 if (I != E) {
3900 ExpectedTy = *I++;
3901 } else if (!Ty->isVarArg()) {
3902 return Error(ArgList[i].Loc, "too many arguments specified");
3903 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003904
Chris Lattnerac161bf2009-01-02 07:01:27 +00003905 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3906 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003907 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003908 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003909 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3910 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003911 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3912 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003914
Chris Lattnerac161bf2009-01-02 07:01:27 +00003915 if (I != E)
3916 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003917
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003918 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003919 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3920 AttributeSet::FunctionIndex,
3921 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003922
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003923 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003924 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003925
Jay Foad5bd375a2011-07-15 08:37:34 +00003926 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003927 II->setCallingConv(CC);
3928 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003929 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003930 Inst = II;
3931 return false;
3932}
3933
Bill Wendlingf891bf82011-07-31 06:30:59 +00003934/// ParseResume
3935/// ::= 'resume' TypeAndValue
3936bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3937 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003938 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3939 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003940
Bill Wendlingf891bf82011-07-31 06:30:59 +00003941 ResumeInst *RI = ResumeInst::Create(Exn);
3942 Inst = RI;
3943 return false;
3944}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003945
3946//===----------------------------------------------------------------------===//
3947// Binary Operators.
3948//===----------------------------------------------------------------------===//
3949
3950/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003951/// ::= ArithmeticOps TypeAndValue ',' Value
3952///
3953/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3954/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003955bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003956 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003957 LocTy Loc; Value *LHS, *RHS;
3958 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3959 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3960 ParseValue(LHS->getType(), RHS, PFS))
3961 return true;
3962
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003963 bool Valid;
3964 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003965 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003966 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003967 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3968 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003969 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003970 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3971 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003972 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003973
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003974 if (!Valid)
3975 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003976
Chris Lattnerac161bf2009-01-02 07:01:27 +00003977 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3978 return false;
3979}
3980
3981/// ParseLogical
3982/// ::= ArithmeticOps TypeAndValue ',' Value {
3983bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3984 unsigned Opc) {
3985 LocTy Loc; Value *LHS, *RHS;
3986 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3987 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3988 ParseValue(LHS->getType(), RHS, PFS))
3989 return true;
3990
Duncan Sands9dff9be2010-02-15 16:12:20 +00003991 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003992 return Error(Loc,"instruction requires integer or integer vector operands");
3993
3994 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3995 return false;
3996}
3997
3998
3999/// ParseCompare
4000/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4001/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004002bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4003 unsigned Opc) {
4004 // Parse the integer/fp comparison predicate.
4005 LocTy Loc;
4006 unsigned Pred;
4007 Value *LHS, *RHS;
4008 if (ParseCmpPredicate(Pred, Opc) ||
4009 ParseTypeAndValue(LHS, Loc, PFS) ||
4010 ParseToken(lltok::comma, "expected ',' after compare value") ||
4011 ParseValue(LHS->getType(), RHS, PFS))
4012 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004013
Chris Lattnerac161bf2009-01-02 07:01:27 +00004014 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004015 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004016 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004017 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004018 } else {
4019 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004020 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004021 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004022 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004023 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004024 }
4025 return false;
4026}
4027
4028//===----------------------------------------------------------------------===//
4029// Other Instructions.
4030//===----------------------------------------------------------------------===//
4031
4032
4033/// ParseCast
4034/// ::= CastOpc TypeAndValue 'to' Type
4035bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4036 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004037 LocTy Loc;
4038 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004039 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004040 if (ParseTypeAndValue(Op, Loc, PFS) ||
4041 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4042 ParseType(DestTy))
4043 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004044
Chris Lattner89d856e2009-03-01 00:53:13 +00004045 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4046 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004047 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004048 getTypeString(Op->getType()) + "' to '" +
4049 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004050 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004051 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4052 return false;
4053}
4054
4055/// ParseSelect
4056/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4057bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4058 LocTy Loc;
4059 Value *Op0, *Op1, *Op2;
4060 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4061 ParseToken(lltok::comma, "expected ',' after select condition") ||
4062 ParseTypeAndValue(Op1, PFS) ||
4063 ParseToken(lltok::comma, "expected ',' after select value") ||
4064 ParseTypeAndValue(Op2, PFS))
4065 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004066
Chris Lattnerac161bf2009-01-02 07:01:27 +00004067 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4068 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004069
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070 Inst = SelectInst::Create(Op0, Op1, Op2);
4071 return false;
4072}
4073
Chris Lattnerb55ab542009-01-05 08:18:44 +00004074/// ParseVA_Arg
4075/// ::= 'va_arg' TypeAndValue ',' Type
4076bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004077 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004078 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004079 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 if (ParseTypeAndValue(Op, PFS) ||
4081 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004082 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004083 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004084
Chris Lattnerb55ab542009-01-05 08:18:44 +00004085 if (!EltTy->isFirstClassType())
4086 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004087
4088 Inst = new VAArgInst(Op, EltTy);
4089 return false;
4090}
4091
4092/// ParseExtractElement
4093/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4094bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4095 LocTy Loc;
4096 Value *Op0, *Op1;
4097 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4098 ParseToken(lltok::comma, "expected ',' after extract value") ||
4099 ParseTypeAndValue(Op1, PFS))
4100 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004101
Chris Lattnerac161bf2009-01-02 07:01:27 +00004102 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4103 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004104
Eric Christopherc9742252009-07-25 02:28:41 +00004105 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004106 return false;
4107}
4108
4109/// ParseInsertElement
4110/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4111bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4112 LocTy Loc;
4113 Value *Op0, *Op1, *Op2;
4114 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4115 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4116 ParseTypeAndValue(Op1, PFS) ||
4117 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4118 ParseTypeAndValue(Op2, PFS))
4119 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004120
Chris Lattnerac161bf2009-01-02 07:01:27 +00004121 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004122 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004123
Chris Lattnerac161bf2009-01-02 07:01:27 +00004124 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4125 return false;
4126}
4127
4128/// ParseShuffleVector
4129/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4130bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4131 LocTy Loc;
4132 Value *Op0, *Op1, *Op2;
4133 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4134 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4135 ParseTypeAndValue(Op1, PFS) ||
4136 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4137 ParseTypeAndValue(Op2, PFS))
4138 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004139
Chris Lattnerac161bf2009-01-02 07:01:27 +00004140 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004141 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004142
Chris Lattnerac161bf2009-01-02 07:01:27 +00004143 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4144 return false;
4145}
4146
4147/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004148/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004149int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004150 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004151 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004152
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004153 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004154 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4155 ParseValue(Ty, Op0, PFS) ||
4156 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004157 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004158 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4159 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004160
Chris Lattnerf4f03422009-12-30 05:27:33 +00004161 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004162 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4163 while (1) {
4164 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004165
Chris Lattner3822f632009-01-02 08:05:26 +00004166 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004167 break;
4168
Chris Lattnerf4f03422009-12-30 05:27:33 +00004169 if (Lex.getKind() == lltok::MetadataVar) {
4170 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004171 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004172 }
Devang Patel8f842d32009-10-16 18:45:49 +00004173
Chris Lattner3822f632009-01-02 08:05:26 +00004174 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004175 ParseValue(Ty, Op0, PFS) ||
4176 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004177 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004178 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4179 return true;
4180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004181
Chris Lattnerac161bf2009-01-02 07:01:27 +00004182 if (!Ty->isFirstClassType())
4183 return Error(TypeLoc, "phi node must have first class type");
4184
Jay Foad52131342011-03-30 11:28:46 +00004185 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004186 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4187 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4188 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004189 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004190}
4191
Bill Wendlingfae14752011-08-12 20:24:12 +00004192/// ParseLandingPad
4193/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4194/// Clause
4195/// ::= 'catch' TypeAndValue
4196/// ::= 'filter'
4197/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4198bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004199 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004200 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004201
4202 if (ParseType(Ty, TyLoc) ||
4203 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4204 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4205 return true;
4206
4207 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4208 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4209
4210 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4211 LandingPadInst::ClauseType CT;
4212 if (EatIfPresent(lltok::kw_catch))
4213 CT = LandingPadInst::Catch;
4214 else if (EatIfPresent(lltok::kw_filter))
4215 CT = LandingPadInst::Filter;
4216 else
4217 return TokError("expected 'catch' or 'filter' clause type");
4218
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004219 Value *V;
4220 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004221 if (ParseTypeAndValue(V, VLoc, PFS)) {
4222 delete LP;
4223 return true;
4224 }
4225
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004226 // A 'catch' type expects a non-array constant. A filter clause expects an
4227 // array constant.
4228 if (CT == LandingPadInst::Catch) {
4229 if (isa<ArrayType>(V->getType()))
4230 Error(VLoc, "'catch' clause has an invalid type");
4231 } else {
4232 if (!isa<ArrayType>(V->getType()))
4233 Error(VLoc, "'filter' clause has an invalid type");
4234 }
4235
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004236 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004237 }
4238
4239 Inst = LP;
4240 return false;
4241}
4242
Chris Lattnerac161bf2009-01-02 07:01:27 +00004243/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004244/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4245/// ParameterList OptionalAttrs
4246/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4247/// ParameterList OptionalAttrs
4248/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004249/// ParameterList OptionalAttrs
4250bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004251 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004252 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004253 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004254 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004255 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004256 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 LocTy RetTypeLoc;
4258 ValID CalleeID;
4259 SmallVector<ParamInfo, 16> ArgList;
4260 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004261
Reid Kleckner5772b772014-04-24 20:14:34 +00004262 if ((TCK != CallInst::TCK_None &&
4263 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004264 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004265 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004266 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004267 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004268 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4269 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004270 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004271 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004272 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004273
Chris Lattnerac161bf2009-01-02 07:01:27 +00004274 // If RetType is a non-function pointer type, then this is the short syntax
4275 // for the call, which means that RetType is just the return type. Infer the
4276 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004277 PointerType *PFTy = nullptr;
4278 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004279 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4280 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4281 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004282 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004283 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4284 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004285
Chris Lattnerac161bf2009-01-02 07:01:27 +00004286 if (!FunctionType::isValidReturnType(RetType))
4287 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004288
Owen Anderson4056ca92009-07-29 22:17:13 +00004289 Ty = FunctionType::get(RetType, ParamTypes, false);
4290 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004291 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004292
Chris Lattnerac161bf2009-01-02 07:01:27 +00004293 // Look up the callee.
4294 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004295 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004296
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004297 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004298 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004299 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004300 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4301 AttributeSet::ReturnIndex,
4302 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004303
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004305
Chris Lattnerac161bf2009-01-02 07:01:27 +00004306 // Loop through FunctionType's arguments and ensure they are specified
4307 // correctly. Also, gather any parameter attributes.
4308 FunctionType::param_iterator I = Ty->param_begin();
4309 FunctionType::param_iterator E = Ty->param_end();
4310 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004311 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 if (I != E) {
4313 ExpectedTy = *I++;
4314 } else if (!Ty->isVarArg()) {
4315 return Error(ArgList[i].Loc, "too many arguments specified");
4316 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004317
Chris Lattnerac161bf2009-01-02 07:01:27 +00004318 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4319 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004320 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004321 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004322 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4323 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004324 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4325 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004326 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004327
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328 if (I != E)
4329 return Error(CallLoc, "not enough parameters specified for call");
4330
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004331 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004332 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4333 AttributeSet::FunctionIndex,
4334 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004336 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004337 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004338
Jay Foad5bd375a2011-07-15 08:37:34 +00004339 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004340 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004341 CI->setCallingConv(CC);
4342 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004343 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004344 Inst = CI;
4345 return false;
4346}
4347
4348//===----------------------------------------------------------------------===//
4349// Memory Instructions.
4350//===----------------------------------------------------------------------===//
4351
4352/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004353/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004354int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004355 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004356 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004358 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004359
4360 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4361
Chris Lattner3822f632009-01-02 08:05:26 +00004362 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004363
Chris Lattnerb2f39502009-12-30 05:44:30 +00004364 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004365 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004366 if (Lex.getKind() == lltok::kw_align) {
4367 if (ParseOptionalAlignment(Alignment)) return true;
4368 } else if (Lex.getKind() == lltok::MetadataVar) {
4369 AteExtraComma = true;
4370 } else {
4371 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4372 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4373 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004374 }
4375 }
4376
Dan Gohman2140a742010-05-28 01:14:11 +00004377 if (Size && !Size->getType()->isIntegerTy())
4378 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004379
Reid Kleckner436c42e2014-01-17 23:58:17 +00004380 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4381 AI->setUsedWithInAlloca(IsInAlloca);
4382 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004383 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004384}
4385
4386/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004387/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004388/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004389/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004390int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004391 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004392 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004393 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004394 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004395 AtomicOrdering Ordering = NotAtomic;
4396 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004397
4398 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004399 isAtomic = true;
4400 Lex.Lex();
4401 }
4402
Chris Lattnerbc639292011-11-27 06:56:53 +00004403 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004404 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004405 isVolatile = true;
4406 Lex.Lex();
4407 }
4408
Chris Lattnerb2f39502009-12-30 05:44:30 +00004409 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004410 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004411 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4412 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004413
Duncan Sands19d0b472010-02-16 11:11:14 +00004414 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004415 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4416 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004417 if (isAtomic && !Alignment)
4418 return Error(Loc, "atomic load must have explicit non-zero alignment");
4419 if (Ordering == Release || Ordering == AcquireRelease)
4420 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004421
Eli Friedman59b66882011-08-09 23:02:53 +00004422 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004423 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004424}
4425
4426/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004427
4428/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4429/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004430/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004431int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004432 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004433 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004434 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004435 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004436 AtomicOrdering Ordering = NotAtomic;
4437 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004438
4439 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004440 isAtomic = true;
4441 Lex.Lex();
4442 }
4443
Chris Lattnerbc639292011-11-27 06:56:53 +00004444 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004445 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004446 isVolatile = true;
4447 Lex.Lex();
4448 }
4449
Chris Lattnerac161bf2009-01-02 07:01:27 +00004450 if (ParseTypeAndValue(Val, Loc, PFS) ||
4451 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004452 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004453 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004454 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004455 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004456
Duncan Sands19d0b472010-02-16 11:11:14 +00004457 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004458 return Error(PtrLoc, "store operand must be a pointer");
4459 if (!Val->getType()->isFirstClassType())
4460 return Error(Loc, "store operand must be a first class value");
4461 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4462 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004463 if (isAtomic && !Alignment)
4464 return Error(Loc, "atomic store must have explicit non-zero alignment");
4465 if (Ordering == Acquire || Ordering == AcquireRelease)
4466 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004467
Eli Friedman59b66882011-08-09 23:02:53 +00004468 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004469 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004470}
4471
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004472/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004473/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4474/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004475int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004476 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4477 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004478 AtomicOrdering SuccessOrdering = NotAtomic;
4479 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004480 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004481 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004482 bool isWeak = false;
4483
4484 if (EatIfPresent(lltok::kw_weak))
4485 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004486
4487 if (EatIfPresent(lltok::kw_volatile))
4488 isVolatile = true;
4489
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004490 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4491 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4492 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4493 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4494 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004495 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4496 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004497 return true;
4498
Tim Northovere94a5182014-03-11 10:48:52 +00004499 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004500 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004501 if (SuccessOrdering < FailureOrdering)
4502 return TokError("cmpxchg must be at least as ordered on success as failure");
4503 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4504 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004505 if (!Ptr->getType()->isPointerTy())
4506 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4507 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4508 return Error(CmpLoc, "compare value and pointer type do not match");
4509 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4510 return Error(NewLoc, "new value and pointer type do not match");
4511 if (!New->getType()->isIntegerTy())
4512 return Error(NewLoc, "cmpxchg operand must be an integer");
4513 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4514 if (Size < 8 || (Size & (Size - 1)))
4515 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4516 " integer");
4517
Tim Northover420a2162014-06-13 14:24:07 +00004518 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4519 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004520 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004521 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004522 Inst = CXI;
4523 return AteExtraComma ? InstExtraComma : InstNormal;
4524}
4525
4526/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004527/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4528/// 'singlethread'? AtomicOrdering
4529int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004530 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4531 bool AteExtraComma = false;
4532 AtomicOrdering Ordering = NotAtomic;
4533 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004534 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004535 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004536
4537 if (EatIfPresent(lltok::kw_volatile))
4538 isVolatile = true;
4539
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004540 switch (Lex.getKind()) {
4541 default: return TokError("expected binary operation in atomicrmw");
4542 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4543 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4544 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4545 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4546 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4547 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4548 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4549 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4550 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4551 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4552 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4553 }
4554 Lex.Lex(); // Eat the operation.
4555
4556 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4557 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4558 ParseTypeAndValue(Val, ValLoc, PFS) ||
4559 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4560 return true;
4561
4562 if (Ordering == Unordered)
4563 return TokError("atomicrmw cannot be unordered");
4564 if (!Ptr->getType()->isPointerTy())
4565 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4566 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4567 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4568 if (!Val->getType()->isIntegerTy())
4569 return Error(ValLoc, "atomicrmw operand must be an integer");
4570 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4571 if (Size < 8 || (Size & (Size - 1)))
4572 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4573 " integer");
4574
4575 AtomicRMWInst *RMWI =
4576 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4577 RMWI->setVolatile(isVolatile);
4578 Inst = RMWI;
4579 return AteExtraComma ? InstExtraComma : InstNormal;
4580}
4581
Eli Friedmanfee02c62011-07-25 23:16:38 +00004582/// ParseFence
4583/// ::= 'fence' 'singlethread'? AtomicOrdering
4584int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4585 AtomicOrdering Ordering = NotAtomic;
4586 SynchronizationScope Scope = CrossThread;
4587 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4588 return true;
4589
4590 if (Ordering == Unordered)
4591 return TokError("fence cannot be unordered");
4592 if (Ordering == Monotonic)
4593 return TokError("fence cannot be monotonic");
4594
4595 Inst = new FenceInst(Context, Ordering, Scope);
4596 return InstNormal;
4597}
4598
Chris Lattnerac161bf2009-01-02 07:01:27 +00004599/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004600/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004601int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004602 Value *Ptr = nullptr;
4603 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004604 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004605
Dan Gohman16cbbe42009-07-29 15:58:36 +00004606 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004607
Chris Lattner3822f632009-01-02 08:05:26 +00004608 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004609
Eli Benderskyd9806682013-04-22 17:03:42 +00004610 Type *BaseType = Ptr->getType();
4611 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4612 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004613 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004614
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004616 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004617 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004618 if (Lex.getKind() == lltok::MetadataVar) {
4619 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004620 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004621 }
Chris Lattner3822f632009-01-02 08:05:26 +00004622 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004623 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004624 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004625 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4626 return Error(EltLoc, "getelementptr index type missmatch");
4627 if (Val->getType()->isVectorTy()) {
4628 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4629 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4630 if (ValNumEl != PtrNumEl)
4631 return Error(EltLoc,
4632 "getelementptr vector index has a wrong number of elements");
4633 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 Indices.push_back(Val);
4635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Eli Benderskyd9806682013-04-22 17:03:42 +00004637 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4638 return Error(Loc, "base element of getelementptr must be sized");
4639
4640 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004641 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004642 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004643 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004644 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004645 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646}
4647
4648/// ParseExtractValue
4649/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004650int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004651 Value *Val; LocTy Loc;
4652 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004653 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004655 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 return true;
4657
Chris Lattner392be582010-02-12 20:49:41 +00004658 if (!Val->getType()->isAggregateType())
4659 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004660
Jay Foad57aa6362011-07-13 10:26:04 +00004661 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004662 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004663 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004664 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665}
4666
4667/// ParseInsertValue
4668/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004669int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004670 Value *Val0, *Val1; LocTy Loc0, Loc1;
4671 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004672 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004673 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4674 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4675 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004676 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004677 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004678
Chris Lattner392be582010-02-12 20:49:41 +00004679 if (!Val0->getType()->isAggregateType())
4680 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004681
Jay Foad57aa6362011-07-13 10:26:04 +00004682 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004683 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004684 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004685 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004686}
Nick Lewycky49f89192009-04-04 07:22:01 +00004687
4688//===----------------------------------------------------------------------===//
4689// Embedded metadata.
4690//===----------------------------------------------------------------------===//
4691
4692/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004693/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004694/// Element
4695/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004696bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00004697 if (ParseToken(lltok::lbrace, "expected '{' here"))
4698 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004699
Dan Gohman1e0213a2010-07-13 19:33:27 +00004700 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004701 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004702 return false;
4703
Nick Lewycky49f89192009-04-04 07:22:01 +00004704 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004705 // Null is a special case since it is typeless.
4706 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004707 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004708 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004709 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004710
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004711 Metadata *MD;
4712 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004713 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004714 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00004715 } while (EatIfPresent(lltok::comma));
4716
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004717 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004718}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004719
4720//===----------------------------------------------------------------------===//
4721// Use-list order directives.
4722//===----------------------------------------------------------------------===//
4723bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4724 SMLoc Loc) {
4725 if (V->use_empty())
4726 return Error(Loc, "value has no uses");
4727
4728 unsigned NumUses = 0;
4729 SmallDenseMap<const Use *, unsigned, 16> Order;
4730 for (const Use &U : V->uses()) {
4731 if (++NumUses > Indexes.size())
4732 break;
4733 Order[&U] = Indexes[NumUses - 1];
4734 }
4735 if (NumUses < 2)
4736 return Error(Loc, "value only has one use");
4737 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4738 return Error(Loc, "wrong number of indexes, expected " +
4739 Twine(std::distance(V->use_begin(), V->use_end())));
4740
4741 V->sortUseList([&](const Use &L, const Use &R) {
4742 return Order.lookup(&L) < Order.lookup(&R);
4743 });
4744 return false;
4745}
4746
4747/// ParseUseListOrderIndexes
4748/// ::= '{' uint32 (',' uint32)+ '}'
4749bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4750 SMLoc Loc = Lex.getLoc();
4751 if (ParseToken(lltok::lbrace, "expected '{' here"))
4752 return true;
4753 if (Lex.getKind() == lltok::rbrace)
4754 return Lex.Error("expected non-empty list of uselistorder indexes");
4755
4756 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4757 // indexes should be distinct numbers in the range [0, size-1], and should
4758 // not be in order.
4759 unsigned Offset = 0;
4760 unsigned Max = 0;
4761 bool IsOrdered = true;
4762 assert(Indexes.empty() && "Expected empty order vector");
4763 do {
4764 unsigned Index;
4765 if (ParseUInt32(Index))
4766 return true;
4767
4768 // Update consistency checks.
4769 Offset += Index - Indexes.size();
4770 Max = std::max(Max, Index);
4771 IsOrdered &= Index == Indexes.size();
4772
4773 Indexes.push_back(Index);
4774 } while (EatIfPresent(lltok::comma));
4775
4776 if (ParseToken(lltok::rbrace, "expected '}' here"))
4777 return true;
4778
4779 if (Indexes.size() < 2)
4780 return Error(Loc, "expected >= 2 uselistorder indexes");
4781 if (Offset != 0 || Max >= Indexes.size())
4782 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4783 if (IsOrdered)
4784 return Error(Loc, "expected uselistorder indexes to change the order");
4785
4786 return false;
4787}
4788
4789/// ParseUseListOrder
4790/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4791bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4792 SMLoc Loc = Lex.getLoc();
4793 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4794 return true;
4795
4796 Value *V;
4797 SmallVector<unsigned, 16> Indexes;
4798 if (ParseTypeAndValue(V, PFS) ||
4799 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4800 ParseUseListOrderIndexes(Indexes))
4801 return true;
4802
4803 return sortUseListOrder(V, Indexes, Loc);
4804}
4805
4806/// ParseUseListOrderBB
4807/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4808bool LLParser::ParseUseListOrderBB() {
4809 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4810 SMLoc Loc = Lex.getLoc();
4811 Lex.Lex();
4812
4813 ValID Fn, Label;
4814 SmallVector<unsigned, 16> Indexes;
4815 if (ParseValID(Fn) ||
4816 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4817 ParseValID(Label) ||
4818 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4819 ParseUseListOrderIndexes(Indexes))
4820 return true;
4821
4822 // Check the function.
4823 GlobalValue *GV;
4824 if (Fn.Kind == ValID::t_GlobalName)
4825 GV = M->getNamedValue(Fn.StrVal);
4826 else if (Fn.Kind == ValID::t_GlobalID)
4827 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4828 else
4829 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4830 if (!GV)
4831 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4832 auto *F = dyn_cast<Function>(GV);
4833 if (!F)
4834 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4835 if (F->isDeclaration())
4836 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4837
4838 // Check the basic block.
4839 if (Label.Kind == ValID::t_LocalID)
4840 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4841 if (Label.Kind != ValID::t_LocalName)
4842 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4843 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4844 if (!V)
4845 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4846 if (!isa<BasicBlock>(V))
4847 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4848
4849 return sortUseListOrder(V, Indexes, Loc);
4850}