blob: b0edeb40d05d9d43f154d255b7f27bb08988f85f [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() {
Chris Lattner8eff0152010-04-01 05:14:45 +000050 // Handle any instruction metadata forward references.
51 if (!ForwardRefInstMetadata.empty()) {
52 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
53 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 I != E; ++I) {
55 Instruction *Inst = I->first;
56 const std::vector<MDRef> &MDList = I->second;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000057
Chris Lattner8eff0152010-04-01 05:14:45 +000058 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
59 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000060
Craig Topper2617dcc2014-04-15 06:32:26 +000061 if (SlotNo >= NumberedMetadata.size() ||
62 NumberedMetadata[SlotNo] == nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +000063 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +000064 Twine(SlotNo) + "'");
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +000065 assert(!NumberedMetadata[SlotNo]->isFunctionLocal() &&
66 "Unexpected function-local metadata");
Chris Lattner8eff0152010-04-01 05:14:45 +000067 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
68 }
69 }
70 ForwardRefInstMetadata.clear();
71 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +000072
Manman Ren209b17c2013-09-28 00:22:27 +000073 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
74 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
75
Bill Wendlingb32b0412013-02-08 06:32:06 +000076 // Handle any function attribute group forward references.
77 for (std::map<Value*, std::vector<unsigned> >::iterator
78 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
79 I != E; ++I) {
80 Value *V = I->first;
81 std::vector<unsigned> &Vec = I->second;
82 AttrBuilder B;
83
84 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
85 VI != VE; ++VI)
86 B.merge(NumberedAttrBuilders[*VI]);
87
88 if (Function *Fn = dyn_cast<Function>(V)) {
89 AttributeSet AS = Fn->getAttributes();
90 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92 AS.getFnAttributes());
93
94 FnAttrs.merge(B);
95
96 // If the alignment was parsed as an attribute, move to the alignment
97 // field.
98 if (FnAttrs.hasAlignmentAttr()) {
99 Fn->setAlignment(FnAttrs.getAlignment());
100 FnAttrs.removeAttribute(Attribute::Alignment);
101 }
102
103 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
104 AttributeSet::get(Context,
105 AttributeSet::FunctionIndex,
106 FnAttrs));
107 Fn->setAttributes(AS);
108 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
109 AttributeSet AS = CI->getAttributes();
110 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
111 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
112 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000113 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000114 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
115 AttributeSet::get(Context,
116 AttributeSet::FunctionIndex,
117 FnAttrs));
118 CI->setAttributes(AS);
119 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
120 AttributeSet AS = II->getAttributes();
121 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
122 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
123 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000124 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000125 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
126 AttributeSet::get(Context,
127 AttributeSet::FunctionIndex,
128 FnAttrs));
129 II->setAttributes(AS);
130 } else {
131 llvm_unreachable("invalid object with forward attribute group reference");
132 }
133 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000134
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000135 // If there are entries in ForwardRefBlockAddresses at this point, the
136 // function was never defined.
137 if (!ForwardRefBlockAddresses.empty())
138 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
139 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000140
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000141 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
142 if (NumberedTypes[i].second.isValid())
143 return Error(NumberedTypes[i].second,
144 "use of undefined type '%" + Twine(i) + "'");
145
146 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
147 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
148 if (I->second.second.isValid())
149 return Error(I->second.second,
150 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000151
David Majnemerdad0a642014-06-27 18:19:56 +0000152 if (!ForwardRefComdats.empty())
153 return Error(ForwardRefComdats.begin()->second,
154 "use of undefined comdat '$" +
155 ForwardRefComdats.begin()->first + "'");
156
Chris Lattnerac161bf2009-01-02 07:01:27 +0000157 if (!ForwardRefVals.empty())
158 return Error(ForwardRefVals.begin()->second.second,
159 "use of undefined value '@" + ForwardRefVals.begin()->first +
160 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000161
Chris Lattnerac161bf2009-01-02 07:01:27 +0000162 if (!ForwardRefValIDs.empty())
163 return Error(ForwardRefValIDs.begin()->second.second,
164 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000165 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000166
Devang Pateld2541152009-07-08 19:23:54 +0000167 if (!ForwardRefMDNodes.empty())
168 return Error(ForwardRefMDNodes.begin()->second.second,
169 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000170 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000171
Devang Pateld2541152009-07-08 19:23:54 +0000172
Chris Lattnerac161bf2009-01-02 07:01:27 +0000173 // Look for intrinsic functions and CallInst that need to be upgraded
174 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
175 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000176
Manman Ren8b4306c2013-12-02 21:29:56 +0000177 UpgradeDebugInfo(*M);
178
Chris Lattnerac161bf2009-01-02 07:01:27 +0000179 return false;
180}
181
182//===----------------------------------------------------------------------===//
183// Top-Level Entities
184//===----------------------------------------------------------------------===//
185
186bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 while (1) {
188 switch (Lex.getKind()) {
189 default: return TokError("expected top-level entity");
190 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000191 case lltok::kw_declare: if (ParseDeclare()) return true; break;
192 case lltok::kw_define: if (ParseDefine()) return true; break;
193 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
194 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000195 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000196 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000197 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000198 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000199 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000200 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000201 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000202 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203
204 // The Global variable production with no name can have many different
205 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000206 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
207 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000208 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000209 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000210 case lltok::kw_internal: // OptionalLinkage
211 case lltok::kw_weak: // OptionalLinkage
212 case lltok::kw_weak_odr: // OptionalLinkage
213 case lltok::kw_linkonce: // OptionalLinkage
214 case lltok::kw_linkonce_odr: // OptionalLinkage
215 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000216 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000217 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000218 case lltok::kw_external: // OptionalLinkage
219 case lltok::kw_default: // OptionalVisibility
220 case lltok::kw_hidden: // OptionalVisibility
221 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000222 case lltok::kw_dllimport: // OptionalDLLStorageClass
223 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000224 case lltok::kw_thread_local: // OptionalThreadLocal
225 case lltok::kw_addrspace: // OptionalAddrSpace
226 case lltok::kw_constant: // GlobalType
227 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000228 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000229 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000230 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000231 bool HasLinkage;
232 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000233 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000234 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000235 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000236 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000237 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000238 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 return true;
240 break;
241 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000242
243 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000244 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
245 case lltok::kw_uselistorder_bb:
246 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000247 }
248 }
249}
250
251
252/// toplevelentity
253/// ::= 'module' 'asm' STRINGCONSTANT
254bool LLParser::ParseModuleAsm() {
255 assert(Lex.getKind() == lltok::kw_module);
256 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000257
258 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000259 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
260 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000261
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000262 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000263 return false;
264}
265
266/// toplevelentity
267/// ::= 'target' 'triple' '=' STRINGCONSTANT
268/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
269bool LLParser::ParseTargetDefinition() {
270 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000271 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000272 switch (Lex.Lex()) {
273 default: return TokError("unknown target property");
274 case lltok::kw_triple:
275 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000276 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
277 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000278 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000279 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 return false;
281 case lltok::kw_datalayout:
282 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000283 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
284 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000285 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000286 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000287 return false;
288 }
289}
290
Bill Wendling706d3d62012-11-28 08:41:48 +0000291/// toplevelentity
292/// ::= 'deplibs' '=' '[' ']'
293/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
294/// FIXME: Remove in 4.0. Currently parse, but ignore.
295bool LLParser::ParseDepLibs() {
296 assert(Lex.getKind() == lltok::kw_deplibs);
297 Lex.Lex();
298 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
299 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
300 return true;
301
302 if (EatIfPresent(lltok::rsquare))
303 return false;
304
305 do {
306 std::string Str;
307 if (ParseStringConstant(Str)) return true;
308 } while (EatIfPresent(lltok::comma));
309
310 return ParseToken(lltok::rsquare, "expected ']' at end of list");
311}
312
Dan Gohman466876b2009-08-12 23:32:33 +0000313/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000314/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000315bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000316 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000317 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000318 Lex.Lex(); // eat LocalVarID;
319
320 if (ParseToken(lltok::equal, "expected '=' after name") ||
321 ParseToken(lltok::kw_type, "expected 'type' after '='"))
322 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000324 if (TypeID >= NumberedTypes.size())
325 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000326
Craig Topper2617dcc2014-04-15 06:32:26 +0000327 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000328 if (ParseStructDefinition(TypeLoc, "",
329 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000330
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000331 if (!isa<StructType>(Result)) {
332 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
333 if (Entry.first)
334 return Error(TypeLoc, "non-struct types may not be recursive");
335 Entry.first = Result;
336 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000337 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000338
Chris Lattnerac161bf2009-01-02 07:01:27 +0000339 return false;
340}
341
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000342
Chris Lattnerac161bf2009-01-02 07:01:27 +0000343/// toplevelentity
344/// ::= LocalVar '=' 'type' type
345bool LLParser::ParseNamedType() {
346 std::string Name = Lex.getStrVal();
347 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000348 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000349
Chris Lattner3822f632009-01-02 08:05:26 +0000350 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000351 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000352 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000353
Craig Topper2617dcc2014-04-15 06:32:26 +0000354 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000355 if (ParseStructDefinition(NameLoc, Name,
356 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358 if (!isa<StructType>(Result)) {
359 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
360 if (Entry.first)
361 return Error(NameLoc, "non-struct types may not be recursive");
362 Entry.first = Result;
363 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000364 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000365
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000366 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367}
368
369
370/// toplevelentity
371/// ::= 'declare' FunctionHeader
372bool LLParser::ParseDeclare() {
373 assert(Lex.getKind() == lltok::kw_declare);
374 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000375
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376 Function *F;
377 return ParseFunctionHeader(F, false);
378}
379
380/// toplevelentity
381/// ::= 'define' FunctionHeader '{' ...
382bool LLParser::ParseDefine() {
383 assert(Lex.getKind() == lltok::kw_define);
384 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000385
Chris Lattnerac161bf2009-01-02 07:01:27 +0000386 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000387 return ParseFunctionHeader(F, true) ||
388 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000389}
390
Chris Lattner3822f632009-01-02 08:05:26 +0000391/// ParseGlobalType
392/// ::= 'constant'
393/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000394bool LLParser::ParseGlobalType(bool &IsConstant) {
395 if (Lex.getKind() == lltok::kw_constant)
396 IsConstant = true;
397 else if (Lex.getKind() == lltok::kw_global)
398 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000399 else {
400 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000401 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000402 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000403 Lex.Lex();
404 return false;
405}
406
Dan Gohman466876b2009-08-12 23:32:33 +0000407/// ParseUnnamedGlobal:
408/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000409/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
410/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000411/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000412/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
413/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000414bool LLParser::ParseUnnamedGlobal() {
415 unsigned VarID = NumberedVals.size();
416 std::string Name;
417 LocTy NameLoc = Lex.getLoc();
418
419 // Handle the GlobalID form.
420 if (Lex.getKind() == lltok::GlobalID) {
421 if (Lex.getUIntVal() != VarID)
422 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000423 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000424 Lex.Lex(); // eat GlobalID;
425
426 if (ParseToken(lltok::equal, "expected '=' after name"))
427 return true;
428 }
429
430 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000431 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000432 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000433 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000434 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000435 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000436 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000437 ParseOptionalThreadLocal(TLM) ||
438 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000439 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000440
Rafael Espindola464fe022014-07-30 22:51:54 +0000441 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000442 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000443 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000444 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000445 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000446}
447
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448/// ParseNamedGlobal:
449/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000450/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
451/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452bool LLParser::ParseNamedGlobal() {
453 assert(Lex.getKind() == lltok::GlobalVar);
454 LocTy NameLoc = Lex.getLoc();
455 std::string Name = Lex.getStrVal();
456 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000457
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000459 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000460 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000461 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000462 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
463 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000464 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000465 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000466 ParseOptionalThreadLocal(TLM) ||
467 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000468 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000469
Rafael Espindola464fe022014-07-30 22:51:54 +0000470 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000471 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000472 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000473
474 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000475 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000476}
477
David Majnemerdad0a642014-06-27 18:19:56 +0000478bool LLParser::parseComdat() {
479 assert(Lex.getKind() == lltok::ComdatVar);
480 std::string Name = Lex.getStrVal();
481 LocTy NameLoc = Lex.getLoc();
482 Lex.Lex();
483
484 if (ParseToken(lltok::equal, "expected '=' here"))
485 return true;
486
487 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
488 return TokError("expected comdat type");
489
490 Comdat::SelectionKind SK;
491 switch (Lex.getKind()) {
492 default:
493 return TokError("unknown selection kind");
494 case lltok::kw_any:
495 SK = Comdat::Any;
496 break;
497 case lltok::kw_exactmatch:
498 SK = Comdat::ExactMatch;
499 break;
500 case lltok::kw_largest:
501 SK = Comdat::Largest;
502 break;
503 case lltok::kw_noduplicates:
504 SK = Comdat::NoDuplicates;
505 break;
506 case lltok::kw_samesize:
507 SK = Comdat::SameSize;
508 break;
509 }
510 Lex.Lex();
511
512 // See if the comdat was forward referenced, if so, use the comdat.
513 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
514 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
515 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
516 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
517
518 Comdat *C;
519 if (I != ComdatSymTab.end())
520 C = &I->second;
521 else
522 C = M->getOrInsertComdat(Name);
523 C->setSelectionKind(SK);
524
525 return false;
526}
527
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000528// MDString:
529// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000530bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000531 std::string Str;
532 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000533 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000534 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000535 return false;
536}
537
538// MDNode:
539// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000540//
541/// This version of ParseMDNodeID returns the slot number and null in the case
542/// of a forward reference.
543bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
544 // !{ ..., !42, ... }
545 if (ParseUInt32(SlotNo)) return true;
546
547 // Check existing MDNode.
Craig Topper2617dcc2014-04-15 06:32:26 +0000548 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +0000549 Result = NumberedMetadata[SlotNo];
550 else
Craig Topper2617dcc2014-04-15 06:32:26 +0000551 Result = nullptr;
Chris Lattner8eff0152010-04-01 05:14:45 +0000552 return false;
553}
554
Chris Lattner6dac02a2009-12-30 04:15:23 +0000555bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000556 // !{ ..., !42, ... }
557 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000558 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000559
Chris Lattner8eff0152010-04-01 05:14:45 +0000560 // If not a forward reference, just return it now.
561 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000562
Chris Lattner8eff0152010-04-01 05:14:45 +0000563 // Otherwise, create MDNode forward reference.
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000564 MDNode *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000565 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000566
Chris Lattnerfc58af22009-12-30 04:51:58 +0000567 if (NumberedMetadata.size() <= MID)
568 NumberedMetadata.resize(MID+1);
569 NumberedMetadata[MID] = FwdNode;
Chris Lattner1797fc72009-12-29 21:53:55 +0000570 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000571 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000572}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000573
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000574/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000575/// !foo = !{ !1, !2 }
576bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000577 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000578 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000579 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000580
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000581 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000582 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000583 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000584 return true;
585
Dan Gohman2637cc12010-07-21 23:38:33 +0000586 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000587 if (Lex.getKind() != lltok::rbrace)
588 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000589 if (ParseToken(lltok::exclaim, "Expected '!' here"))
590 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000591
Craig Topper2617dcc2014-04-15 06:32:26 +0000592 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000593 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000594 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000595 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000596
597 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
598 return true;
599
Devang Patelbe626972009-07-29 00:34:02 +0000600 return false;
601}
602
Devang Patel39e64d42009-07-01 19:21:12 +0000603/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000604/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000605bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000606 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000607 Lex.Lex();
608 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000609
610 LocTy TyLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +0000611 Type *Ty = nullptr;
Devang Patele059ba6e2009-07-23 01:07:34 +0000612 SmallVector<Value *, 16> Elts;
Chris Lattner278bc952009-12-29 22:40:21 +0000613 if (ParseUInt32(MetadataID) ||
614 ParseToken(lltok::equal, "expected '=' here") ||
615 ParseType(Ty, TyLoc) ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000616 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner278bc952009-12-29 22:40:21 +0000617 ParseToken(lltok::lbrace, "Expected '{' here") ||
Craig Topper2617dcc2014-04-15 06:32:26 +0000618 ParseMDNodeVector(Elts, nullptr) ||
Chris Lattner278bc952009-12-29 22:40:21 +0000619 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patele059ba6e2009-07-23 01:07:34 +0000620 return true;
621
Jay Foad5514afe2011-04-21 19:59:31 +0000622 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000623
Chris Lattnerfc58af22009-12-30 04:51:58 +0000624 // See if this was forward referenced, if so, handle it.
Chris Lattner218b22f2009-12-29 21:43:58 +0000625 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Pateld2541152009-07-08 19:23:54 +0000626 FI = ForwardRefMDNodes.find(MetadataID);
627 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman16a5d982010-08-20 22:02:26 +0000628 MDNode *Temp = FI->second.first;
629 Temp->replaceAllUsesWith(Init);
630 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000631 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000632
Chris Lattnerfc58af22009-12-30 04:51:58 +0000633 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
634 } else {
635 if (MetadataID >= NumberedMetadata.size())
636 NumberedMetadata.resize(MetadataID+1);
637
Craig Topper2617dcc2014-04-15 06:32:26 +0000638 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000639 return TokError("Metadata id is already used");
640 NumberedMetadata[MetadataID] = Init;
Devang Pateld2541152009-07-08 19:23:54 +0000641 }
642
Devang Patel39e64d42009-07-01 19:21:12 +0000643 return false;
644}
645
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000646static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
647 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
648 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
649}
650
Chris Lattnerac161bf2009-01-02 07:01:27 +0000651/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000652/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
653/// OptionalDLLStorageClass OptionalThreadLocal
654/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000655///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000656/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000657/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000658///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000659/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000660///
Rafael Espindola464fe022014-07-30 22:51:54 +0000661bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000662 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000663 GlobalVariable::ThreadLocalMode TLM,
664 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000665 assert(Lex.getKind() == lltok::kw_alias);
666 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000667
Rafael Espindola78527052013-10-06 15:10:43 +0000668 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
669
Rafael Espindolacaa43562013-10-09 16:07:32 +0000670 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000671 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000672
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000673 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000674 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000675 "symbol with local linkage must have default visibility");
676
Rafael Espindola64c1e182014-06-03 02:41:57 +0000677 Constant *Aliasee;
678 LocTy AliaseeLoc = Lex.getLoc();
679 if (Lex.getKind() != lltok::kw_bitcast &&
680 Lex.getKind() != lltok::kw_getelementptr &&
681 Lex.getKind() != lltok::kw_addrspacecast &&
682 Lex.getKind() != lltok::kw_inttoptr) {
683 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000684 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000685 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000686 // The bitcast dest type is not present, it is implied by the dest type.
687 ValID ID;
688 if (ParseValID(ID))
689 return true;
690 if (ID.Kind != ValID::t_Constant)
691 return Error(AliaseeLoc, "invalid aliasee");
692 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000693 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000694
Rafael Espindola64c1e182014-06-03 02:41:57 +0000695 Type *AliaseeType = Aliasee->getType();
696 auto *PTy = dyn_cast<PointerType>(AliaseeType);
697 if (!PTy)
698 return Error(AliaseeLoc, "An alias must have pointer type");
699 Type *Ty = PTy->getElementType();
700 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000701
702 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000703 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000704 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
705 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000706 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000707 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000708 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000709 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000710
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711 // See if this value already exists in the symbol table. If so, it is either
712 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000713 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000714 // See if this was a redefinition. If so, there is no entry in
715 // ForwardRefVals.
716 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
717 I = ForwardRefVals.find(Name);
718 if (I == ForwardRefVals.end())
719 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
720
721 // Otherwise, this was a definition of forward ref. Verify that types
722 // agree.
723 if (Val->getType() != GA->getType())
724 return Error(NameLoc,
725 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000726
Chris Lattnerac161bf2009-01-02 07:01:27 +0000727 // If they agree, just RAUW the old value with the alias and remove the
728 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000729 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000730 Val->eraseFromParent();
731 ForwardRefVals.erase(I);
732 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000733
Chris Lattnerac161bf2009-01-02 07:01:27 +0000734 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000735 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000736 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
Rafael Espindolaaa273822014-05-09 21:49:17 +0000738 // The module owns this now
739 GA.release();
740
Chris Lattnerac161bf2009-01-02 07:01:27 +0000741 return false;
742}
743
744/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000745/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000746/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000747/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000748/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000749/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000750/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000751///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000752/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000753/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000754///
755bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
756 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000757 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000758 GlobalVariable::ThreadLocalMode TLM,
759 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000760 if (!isValidVisibilityForLinkage(Visibility, Linkage))
761 return Error(NameLoc,
762 "symbol with local linkage must have default visibility");
763
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000765 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000766 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000767 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000768
Craig Topper2617dcc2014-04-15 06:32:26 +0000769 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000770 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000771 ParseOptionalToken(lltok::kw_externally_initialized,
772 IsExternallyInitialized,
773 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000774 ParseGlobalType(IsConstant) ||
775 ParseType(Ty, TyLoc))
776 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000777
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 // If the linkage is specified and is external, then no initializer is
779 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000780 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000781 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 Linkage != GlobalValue::ExternalLinkage)) {
783 if (ParseGlobalValue(Ty, Init))
784 return true;
785 }
786
Duncan Sands19d0b472010-02-16 11:11:14 +0000787 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000788 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000789
David Majnemer598bd052014-12-09 05:56:09 +0000790 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000791
792 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000793 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000794 GVal = M->getNamedValue(Name);
795 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000796 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
797 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000798 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000799 } else {
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(NumberedVals.size());
802 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000803 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 ForwardRefValIDs.erase(I);
805 }
806 }
807
David Majnemer598bd052014-12-09 05:56:09 +0000808 GlobalVariable *GV;
809 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000810 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
811 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000812 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000813 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000814 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000815 return Error(TyLoc,
816 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000817
David Majnemer598bd052014-12-09 05:56:09 +0000818 GV = cast<GlobalVariable>(GVal);
819
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 // Move the forward-reference to the correct spot in the module.
821 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
822 }
823
824 if (Name.empty())
825 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 // Set the parsed properties on the global.
828 if (Init)
829 GV->setInitializer(Init);
830 GV->setConstant(IsConstant);
831 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
832 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000833 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000834 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000835 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000836 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000837
Chris Lattnerac161bf2009-01-02 07:01:27 +0000838 // Parse attributes on the global.
839 while (Lex.getKind() == lltok::comma) {
840 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000841
Chris Lattnerac161bf2009-01-02 07:01:27 +0000842 if (Lex.getKind() == lltok::kw_section) {
843 Lex.Lex();
844 GV->setSection(Lex.getStrVal());
845 if (ParseToken(lltok::StringConstant, "expected global section string"))
846 return true;
847 } else if (Lex.getKind() == lltok::kw_align) {
848 unsigned Alignment;
849 if (ParseOptionalAlignment(Alignment)) return true;
850 GV->setAlignment(Alignment);
851 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000852 Comdat *C;
853 if (parseOptionalComdat(C))
854 return true;
855 if (C)
856 GV->setComdat(C);
857 else
858 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 }
860 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000861
Chris Lattnerac161bf2009-01-02 07:01:27 +0000862 return false;
863}
864
Bill Wendling63b88192013-02-06 06:52:58 +0000865/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000866/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000867bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000868 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000869 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000870 Lex.Lex();
871
872 assert(Lex.getKind() == lltok::AttrGrpID);
Bill Wendling63b88192013-02-06 06:52:58 +0000873 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000874 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000875 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000876 Lex.Lex();
877
878 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000879 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000880 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000881 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000882 ParseToken(lltok::rbrace, "expected end of attribute group"))
883 return true;
884
Bill Wendlingb32b0412013-02-08 06:32:06 +0000885 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000886 return Error(AttrGrpLoc, "attribute group has no attributes");
887
888 return false;
889}
890
Bill Wendling8b0321d2013-02-08 00:52:31 +0000891/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000892/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000893bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
894 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000895 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000896 bool HaveError = false;
897
898 B.clear();
899
Bill Wendling63b88192013-02-06 06:52:58 +0000900 while (true) {
901 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000902 if (Token == lltok::kw_builtin)
903 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000904 switch (Token) {
905 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000906 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000907 return Error(Lex.getLoc(), "unterminated attribute group");
908 case lltok::rbrace:
909 // Finished.
910 return false;
911
Bill Wendlingb32b0412013-02-08 06:32:06 +0000912 case lltok::AttrGrpID: {
913 // Allow a function to reference an attribute group:
914 //
915 // define void @foo() #1 { ... }
916 if (inAttrGrp)
917 HaveError |=
918 Error(Lex.getLoc(),
919 "cannot have an attribute group reference in an attribute group");
920
921 unsigned AttrGrpNum = Lex.getUIntVal();
922 if (inAttrGrp) break;
923
924 // Save the reference to the attribute group. We'll fill it in later.
925 FwdRefAttrGrps.push_back(AttrGrpNum);
926 break;
927 }
Bill Wendling63b88192013-02-06 06:52:58 +0000928 // Target-dependent attributes:
929 case lltok::StringConstant: {
930 std::string Attr = Lex.getStrVal();
931 Lex.Lex();
932 std::string Val;
933 if (EatIfPresent(lltok::equal) &&
934 ParseStringConstant(Val))
935 return true;
936
937 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000938 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000939 }
940
941 // Target-independent attributes:
942 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000943 // As a hack, we allow function alignment to be initially parsed as an
944 // attribute on a function declaration/definition or added to an attribute
945 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000946 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000947 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000948 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000949 if (ParseToken(lltok::equal, "expected '=' here") ||
950 ParseUInt32(Alignment))
951 return true;
952 } else {
953 if (ParseOptionalAlignment(Alignment))
954 return true;
955 }
Bill Wendling63b88192013-02-06 06:52:58 +0000956 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000957 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000958 }
959 case lltok::kw_alignstack: {
960 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000961 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000962 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000963 if (ParseToken(lltok::equal, "expected '=' here") ||
964 ParseUInt32(Alignment))
965 return true;
966 } else {
967 if (ParseOptionalStackAlignment(Alignment))
968 return true;
969 }
Bill Wendling63b88192013-02-06 06:52:58 +0000970 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000971 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000972 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000973 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000974 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000975 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000976 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000977 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000978 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
979 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
980 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
981 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
982 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
983 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
984 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
985 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
986 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
987 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000988 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000989 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
990 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
991 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
992 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
993 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
994 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
995 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
996 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
997 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
998 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
999 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001000
1001 // Error handling.
1002 case lltok::kw_inreg:
1003 case lltok::kw_signext:
1004 case lltok::kw_zeroext:
1005 HaveError |=
1006 Error(Lex.getLoc(),
1007 "invalid use of attribute on a function");
1008 break;
1009 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001010 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +00001011 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001012 case lltok::kw_nest:
1013 case lltok::kw_noalias:
1014 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001015 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001016 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001017 case lltok::kw_sret:
1018 HaveError |=
1019 Error(Lex.getLoc(),
1020 "invalid use of parameter-only attribute on a function");
1021 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001022 }
1023
1024 Lex.Lex();
1025 }
1026}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001027
1028//===----------------------------------------------------------------------===//
1029// GlobalValue Reference/Resolution Routines.
1030//===----------------------------------------------------------------------===//
1031
1032/// GetGlobalVal - Get a value with the specified name or ID, creating a
1033/// forward reference record if needed. This can return null if the value
1034/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001035GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001036 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001037 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001038 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001040 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001042
Chris Lattnerac161bf2009-01-02 07:01:27 +00001043 // Look this name up in the normal function symbol table.
1044 GlobalValue *Val =
1045 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001046
Chris Lattnerac161bf2009-01-02 07:01:27 +00001047 // If this is a forward reference for the value, see if we already created a
1048 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001050 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1051 I = ForwardRefVals.find(Name);
1052 if (I != ForwardRefVals.end())
1053 Val = I->second.first;
1054 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001055
Chris Lattnerac161bf2009-01-02 07:01:27 +00001056 // If we have the value in the symbol table or fwd-ref table, return it.
1057 if (Val) {
1058 if (Val->getType() == Ty) return Val;
1059 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001060 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001061 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001063
Chris Lattnerac161bf2009-01-02 07:01:27 +00001064 // Otherwise, create a new forward reference for this value and remember it.
1065 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001066 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001067 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001068 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001069 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001070 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1071 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001072 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001073
Chris Lattnerac161bf2009-01-02 07:01:27 +00001074 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1075 return FwdVal;
1076}
1077
Chris Lattner229907c2011-07-18 04:54:35 +00001078GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1079 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001080 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001082 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001083 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001084
Craig Topper2617dcc2014-04-15 06:32:26 +00001085 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001086
Chris Lattnerac161bf2009-01-02 07:01:27 +00001087 // If this is a forward reference for the value, see if we already created a
1088 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001089 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001090 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1091 I = ForwardRefValIDs.find(ID);
1092 if (I != ForwardRefValIDs.end())
1093 Val = I->second.first;
1094 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001095
Chris Lattnerac161bf2009-01-02 07:01:27 +00001096 // If we have the value in the symbol table or fwd-ref table, return it.
1097 if (Val) {
1098 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001099 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001100 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001101 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001103
Chris Lattnerac161bf2009-01-02 07:01:27 +00001104 // Otherwise, create a new forward reference for this value and remember it.
1105 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001106 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001107 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001108 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001109 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001110 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001111
Chris Lattnerac161bf2009-01-02 07:01:27 +00001112 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1113 return FwdVal;
1114}
1115
1116
1117//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001118// Comdat Reference/Resolution Routines.
1119//===----------------------------------------------------------------------===//
1120
1121Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1122 // Look this name up in the comdat symbol table.
1123 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1124 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1125 if (I != ComdatSymTab.end())
1126 return &I->second;
1127
1128 // Otherwise, create a new forward reference for this value and remember it.
1129 Comdat *C = M->getOrInsertComdat(Name);
1130 ForwardRefComdats[Name] = Loc;
1131 return C;
1132}
1133
1134
1135//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001136// Helper Routines.
1137//===----------------------------------------------------------------------===//
1138
1139/// ParseToken - If the current token has the specified kind, eat it and return
1140/// success. Otherwise, emit the specified error and return failure.
1141bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1142 if (Lex.getKind() != T)
1143 return TokError(ErrMsg);
1144 Lex.Lex();
1145 return false;
1146}
1147
Chris Lattner3822f632009-01-02 08:05:26 +00001148/// ParseStringConstant
1149/// ::= StringConstant
1150bool LLParser::ParseStringConstant(std::string &Result) {
1151 if (Lex.getKind() != lltok::StringConstant)
1152 return TokError("expected string constant");
1153 Result = Lex.getStrVal();
1154 Lex.Lex();
1155 return false;
1156}
1157
1158/// ParseUInt32
1159/// ::= uint32
1160bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001161 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1162 return TokError("expected integer");
1163 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1164 if (Val64 != unsigned(Val64))
1165 return TokError("expected 32-bit integer (too large)");
1166 Val = Val64;
1167 Lex.Lex();
1168 return false;
1169}
1170
Hal Finkelb0407ba2014-07-18 15:51:28 +00001171/// ParseUInt64
1172/// ::= uint64
1173bool LLParser::ParseUInt64(uint64_t &Val) {
1174 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1175 return TokError("expected integer");
1176 Val = Lex.getAPSIntVal().getLimitedValue();
1177 Lex.Lex();
1178 return false;
1179}
1180
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001181/// ParseTLSModel
1182/// := 'localdynamic'
1183/// := 'initialexec'
1184/// := 'localexec'
1185bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1186 switch (Lex.getKind()) {
1187 default:
1188 return TokError("expected localdynamic, initialexec or localexec");
1189 case lltok::kw_localdynamic:
1190 TLM = GlobalVariable::LocalDynamicTLSModel;
1191 break;
1192 case lltok::kw_initialexec:
1193 TLM = GlobalVariable::InitialExecTLSModel;
1194 break;
1195 case lltok::kw_localexec:
1196 TLM = GlobalVariable::LocalExecTLSModel;
1197 break;
1198 }
1199
1200 Lex.Lex();
1201 return false;
1202}
1203
1204/// ParseOptionalThreadLocal
1205/// := /*empty*/
1206/// := 'thread_local'
1207/// := 'thread_local' '(' tlsmodel ')'
1208bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1209 TLM = GlobalVariable::NotThreadLocal;
1210 if (!EatIfPresent(lltok::kw_thread_local))
1211 return false;
1212
1213 TLM = GlobalVariable::GeneralDynamicTLSModel;
1214 if (Lex.getKind() == lltok::lparen) {
1215 Lex.Lex();
1216 return ParseTLSModel(TLM) ||
1217 ParseToken(lltok::rparen, "expected ')' after thread local model");
1218 }
1219 return false;
1220}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001221
1222/// ParseOptionalAddrSpace
1223/// := /*empty*/
1224/// := 'addrspace' '(' uint32 ')'
1225bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1226 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001227 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001229 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001230 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001232}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001233
Bill Wendling34c2eb22012-12-04 23:40:58 +00001234/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1235bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1236 bool HaveError = false;
1237
1238 B.clear();
1239
1240 while (1) {
1241 lltok::Kind Token = Lex.getKind();
1242 switch (Token) {
1243 default: // End of attributes.
1244 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001245 case lltok::kw_align: {
1246 unsigned Alignment;
1247 if (ParseOptionalAlignment(Alignment))
1248 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001249 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001250 continue;
1251 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001252 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001253 case lltok::kw_dereferenceable: {
1254 uint64_t Bytes;
1255 if (ParseOptionalDereferenceableBytes(Bytes))
1256 return true;
1257 B.addDereferenceableAttr(Bytes);
1258 continue;
1259 }
Reid Klecknera534a382013-12-19 02:14:12 +00001260 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001261 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1262 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1263 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1264 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001265 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001266 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1267 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001268 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001269 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1270 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1271 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001272
Stephen Lin7577ed52013-04-20 13:16:13 +00001273 case lltok::kw_alignstack:
1274 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001275 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001276 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001277 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001278 case lltok::kw_minsize:
1279 case lltok::kw_naked:
1280 case lltok::kw_nobuiltin:
1281 case lltok::kw_noduplicate:
1282 case lltok::kw_noimplicitfloat:
1283 case lltok::kw_noinline:
1284 case lltok::kw_nonlazybind:
1285 case lltok::kw_noredzone:
1286 case lltok::kw_noreturn:
1287 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001288 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001289 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001290 case lltok::kw_returns_twice:
1291 case lltok::kw_sanitize_address:
1292 case lltok::kw_sanitize_memory:
1293 case lltok::kw_sanitize_thread:
1294 case lltok::kw_ssp:
1295 case lltok::kw_sspreq:
1296 case lltok::kw_sspstrong:
1297 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001298 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1299 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001300 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001301
Bill Wendling34c2eb22012-12-04 23:40:58 +00001302 Lex.Lex();
1303 }
1304}
1305
1306/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1307bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1308 bool HaveError = false;
1309
1310 B.clear();
1311
1312 while (1) {
1313 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001314 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001315 default: // End of attributes.
1316 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001317 case lltok::kw_dereferenceable: {
1318 uint64_t Bytes;
1319 if (ParseOptionalDereferenceableBytes(Bytes))
1320 return true;
1321 B.addDereferenceableAttr(Bytes);
1322 continue;
1323 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001324 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1325 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001326 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001327 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1328 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001329
Bill Wendling34c2eb22012-12-04 23:40:58 +00001330 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001331 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001332 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001333 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001334 case lltok::kw_nest:
1335 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001336 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001337 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001338 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001339 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001340
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001341 case lltok::kw_alignstack:
1342 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001343 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001344 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001345 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001346 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001347 case lltok::kw_minsize:
1348 case lltok::kw_naked:
1349 case lltok::kw_nobuiltin:
1350 case lltok::kw_noduplicate:
1351 case lltok::kw_noimplicitfloat:
1352 case lltok::kw_noinline:
1353 case lltok::kw_nonlazybind:
1354 case lltok::kw_noredzone:
1355 case lltok::kw_noreturn:
1356 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001357 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001358 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001359 case lltok::kw_returns_twice:
1360 case lltok::kw_sanitize_address:
1361 case lltok::kw_sanitize_memory:
1362 case lltok::kw_sanitize_thread:
1363 case lltok::kw_ssp:
1364 case lltok::kw_sspreq:
1365 case lltok::kw_sspstrong:
1366 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001367 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001368 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001369
1370 case lltok::kw_readnone:
1371 case lltok::kw_readonly:
1372 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001373 }
1374
Chris Lattnerac161bf2009-01-02 07:01:27 +00001375 Lex.Lex();
1376 }
1377}
1378
1379/// ParseOptionalLinkage
1380/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001381/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382/// ::= 'internal'
1383/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001384/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001386/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001387/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001388/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001389/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001390/// ::= 'extern_weak'
1391/// ::= 'external'
1392bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1393 HasLinkage = false;
1394 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001395 default: Res=GlobalValue::ExternalLinkage; return false;
1396 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001397 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1398 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1399 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1400 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1401 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001402 case lltok::kw_available_externally:
1403 Res = GlobalValue::AvailableExternallyLinkage;
1404 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001405 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001406 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001407 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1408 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001409 }
1410 Lex.Lex();
1411 HasLinkage = true;
1412 return false;
1413}
1414
1415/// ParseOptionalVisibility
1416/// ::= /*empty*/
1417/// ::= 'default'
1418/// ::= 'hidden'
1419/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001420///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001421bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1422 switch (Lex.getKind()) {
1423 default: Res = GlobalValue::DefaultVisibility; return false;
1424 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1425 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1426 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1427 }
1428 Lex.Lex();
1429 return false;
1430}
1431
Nico Rieck7157bb72014-01-14 15:22:47 +00001432/// ParseOptionalDLLStorageClass
1433/// ::= /*empty*/
1434/// ::= 'dllimport'
1435/// ::= 'dllexport'
1436///
1437bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1438 switch (Lex.getKind()) {
1439 default: Res = GlobalValue::DefaultStorageClass; return false;
1440 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1441 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1442 }
1443 Lex.Lex();
1444 return false;
1445}
1446
Chris Lattnerac161bf2009-01-02 07:01:27 +00001447/// ParseOptionalCallingConv
1448/// ::= /*empty*/
1449/// ::= 'ccc'
1450/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001451/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001452/// ::= 'coldcc'
1453/// ::= 'x86_stdcallcc'
1454/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001455/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001456/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001457/// ::= 'arm_apcscc'
1458/// ::= 'arm_aapcscc'
1459/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001460/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001461/// ::= 'ptx_kernel'
1462/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001463/// ::= 'spir_func'
1464/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001465/// ::= 'x86_64_sysvcc'
1466/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001467/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001468/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001469/// ::= 'preserve_mostcc'
1470/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001471/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001472/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001473///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001474bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001475 switch (Lex.getKind()) {
1476 default: CC = CallingConv::C; return false;
1477 case lltok::kw_ccc: CC = CallingConv::C; break;
1478 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1479 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1480 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1481 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001482 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001483 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001484 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1485 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1486 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001487 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001488 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1489 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001490 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1491 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001492 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001493 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1494 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001495 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001496 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001497 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1498 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001499 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001500 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001501 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001502 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001503 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001504 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001505
Chris Lattnerac161bf2009-01-02 07:01:27 +00001506 Lex.Lex();
1507 return false;
1508}
1509
Chris Lattner5c427632009-12-30 05:31:19 +00001510/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001511/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001512bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1513 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001514 do {
1515 if (Lex.getKind() != lltok::MetadataVar)
1516 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001517
Chris Lattner596760d2009-12-29 21:25:40 +00001518 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001519 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001520 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001521
Chris Lattner1797fc72009-12-29 21:53:55 +00001522 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001523 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001524
1525 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001526 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001527
Dan Gohmanf0715b12010-08-24 14:35:45 +00001528 // This code is similar to that of ParseMetadataValue, however it needs to
1529 // have special-case code for a forward reference; see the comments on
1530 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1531 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001532 if (Lex.getKind() == lltok::lbrace) {
1533 ValID ID;
1534 if (ParseMetadataListValue(ID, PFS))
1535 return true;
1536 assert(ID.Kind == ValID::t_MDNode);
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00001537 if (ID.MDNodeVal->isFunctionLocal())
Duncan P. N. Exon Smith545a9b02014-12-07 17:56:16 +00001538 return Error(Loc, "unexpected function-local metadata");
Dan Gohmanc828c542010-08-24 02:24:03 +00001539 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001540 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001541 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001542 if (ParseMDNodeID(Node, NodeID))
1543 return true;
1544 if (Node) {
1545 // If we got the node, add it to the instruction.
1546 Inst->setMetadata(MDK, Node);
1547 } else {
1548 MDRef R = { Loc, MDK, NodeID };
1549 // Otherwise, remember that this should be resolved later.
1550 ForwardRefInstMetadata[Inst].push_back(R);
1551 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001552 }
Chris Lattner596760d2009-12-29 21:25:40 +00001553
Manman Ren209b17c2013-09-28 00:22:27 +00001554 if (MDK == LLVMContext::MD_tbaa)
1555 InstsWithTBAATag.push_back(Inst);
1556
Chris Lattner596760d2009-12-29 21:25:40 +00001557 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001558 } while (EatIfPresent(lltok::comma));
1559 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001560}
1561
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562/// ParseOptionalAlignment
1563/// ::= /* empty */
1564/// ::= 'align' 4
1565bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1566 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001567 if (!EatIfPresent(lltok::kw_align))
1568 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001569 LocTy AlignLoc = Lex.getLoc();
1570 if (ParseUInt32(Alignment)) return true;
1571 if (!isPowerOf2_32(Alignment))
1572 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001573 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001574 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001575 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001576}
1577
Hal Finkelb0407ba2014-07-18 15:51:28 +00001578/// ParseOptionalDereferenceableBytes
1579/// ::= /* empty */
1580/// ::= 'dereferenceable' '(' 4 ')'
1581bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1582 Bytes = 0;
1583 if (!EatIfPresent(lltok::kw_dereferenceable))
1584 return false;
1585 LocTy ParenLoc = Lex.getLoc();
1586 if (!EatIfPresent(lltok::lparen))
1587 return Error(ParenLoc, "expected '('");
1588 LocTy DerefLoc = Lex.getLoc();
1589 if (ParseUInt64(Bytes)) return true;
1590 ParenLoc = Lex.getLoc();
1591 if (!EatIfPresent(lltok::rparen))
1592 return Error(ParenLoc, "expected ')'");
1593 if (!Bytes)
1594 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1595 return false;
1596}
1597
Chris Lattnerb2f39502009-12-30 05:44:30 +00001598/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001599/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001600/// ::= ',' align 4
1601///
1602/// This returns with AteExtraComma set to true if it ate an excess comma at the
1603/// end.
1604bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1605 bool &AteExtraComma) {
1606 AteExtraComma = false;
1607 while (EatIfPresent(lltok::comma)) {
1608 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001609 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001610 AteExtraComma = true;
1611 return false;
1612 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001613
Chris Lattner95b0ff42010-04-23 00:50:50 +00001614 if (Lex.getKind() != lltok::kw_align)
1615 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001616
Chris Lattner95b0ff42010-04-23 00:50:50 +00001617 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001619
Devang Patelea8a4b92009-09-17 23:04:48 +00001620 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621}
1622
Eli Friedmanfee02c62011-07-25 23:16:38 +00001623/// ParseScopeAndOrdering
1624/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1625/// else: ::=
1626///
1627/// This sets Scope and Ordering to the parsed values.
1628bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1629 AtomicOrdering &Ordering) {
1630 if (!isAtomic)
1631 return false;
1632
1633 Scope = CrossThread;
1634 if (EatIfPresent(lltok::kw_singlethread))
1635 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001636
1637 return ParseOrdering(Ordering);
1638}
1639
1640/// ParseOrdering
1641/// ::= AtomicOrdering
1642///
1643/// This sets Ordering to the parsed value.
1644bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001645 switch (Lex.getKind()) {
1646 default: return TokError("Expected ordering on atomic instruction");
1647 case lltok::kw_unordered: Ordering = Unordered; break;
1648 case lltok::kw_monotonic: Ordering = Monotonic; break;
1649 case lltok::kw_acquire: Ordering = Acquire; break;
1650 case lltok::kw_release: Ordering = Release; break;
1651 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1652 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1653 }
1654 Lex.Lex();
1655 return false;
1656}
1657
Charles Davisbe5557e2010-02-12 00:31:15 +00001658/// ParseOptionalStackAlignment
1659/// ::= /* empty */
1660/// ::= 'alignstack' '(' 4 ')'
1661bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1662 Alignment = 0;
1663 if (!EatIfPresent(lltok::kw_alignstack))
1664 return false;
1665 LocTy ParenLoc = Lex.getLoc();
1666 if (!EatIfPresent(lltok::lparen))
1667 return Error(ParenLoc, "expected '('");
1668 LocTy AlignLoc = Lex.getLoc();
1669 if (ParseUInt32(Alignment)) return true;
1670 ParenLoc = Lex.getLoc();
1671 if (!EatIfPresent(lltok::rparen))
1672 return Error(ParenLoc, "expected ')'");
1673 if (!isPowerOf2_32(Alignment))
1674 return Error(AlignLoc, "stack alignment is not a power of two");
1675 return false;
1676}
Devang Patelea8a4b92009-09-17 23:04:48 +00001677
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001678/// ParseIndexList - This parses the index list for an insert/extractvalue
1679/// instruction. This sets AteExtraComma in the case where we eat an extra
1680/// comma at the end of the line and find that it is followed by metadata.
1681/// Clients that don't allow metadata can call the version of this function that
1682/// only takes one argument.
1683///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001684/// ParseIndexList
1685/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001686///
1687bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1688 bool &AteExtraComma) {
1689 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001690
Chris Lattnerac161bf2009-01-02 07:01:27 +00001691 if (Lex.getKind() != lltok::comma)
1692 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001693
Chris Lattner3822f632009-01-02 08:05:26 +00001694 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001695 if (Lex.getKind() == lltok::MetadataVar) {
1696 AteExtraComma = true;
1697 return false;
1698 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001699 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001700 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701 Indices.push_back(Idx);
1702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001703
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704 return false;
1705}
1706
1707//===----------------------------------------------------------------------===//
1708// Type Parsing.
1709//===----------------------------------------------------------------------===//
1710
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711/// ParseType - Parse a type.
1712bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1713 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001714 switch (Lex.getKind()) {
1715 default:
1716 return TokError("expected type");
1717 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001718 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001720 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001721 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001723 // Type ::= StructType
1724 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 return true;
1726 break;
1727 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001728 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729 Lex.Lex(); // eat the lsquare.
1730 if (ParseArrayVectorType(Result, false))
1731 return true;
1732 break;
1733 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001734 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001735 Lex.Lex();
1736 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001737 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001738 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740 } else if (ParseArrayVectorType(Result, true))
1741 return true;
1742 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 case lltok::LocalVar: {
1744 // Type ::= %foo
1745 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001746
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 // If the type hasn't been defined yet, create a forward definition and
1748 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001749 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001750 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 Lex.Lex();
1755 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001757
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001758 case lltok::LocalVarID: {
1759 // Type ::= %4
1760 if (Lex.getUIntVal() >= NumberedTypes.size())
1761 NumberedTypes.resize(Lex.getUIntVal()+1);
1762 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001763
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001764 // If the type hasn't been defined yet, create a forward definition and
1765 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001766 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001767 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001768 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001769 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001770 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 Lex.Lex();
1772 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 }
1774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001775
1776 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001777 while (1) {
1778 switch (Lex.getKind()) {
1779 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001780 default:
1781 if (!AllowVoid && Result->isVoidTy())
1782 return Error(TypeLoc, "void type only allowed for function results");
1783 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001785 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001786 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001787 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001788 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001789 if (Result->isVoidTy())
1790 return TokError("pointers to void are invalid - use i8* instead");
1791 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001792 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001794 Lex.Lex();
1795 break;
1796
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001798 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001799 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001800 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001801 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001802 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001803 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001804 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001805 unsigned AddrSpace;
1806 if (ParseOptionalAddrSpace(AddrSpace) ||
1807 ParseToken(lltok::star, "expected '*' in address space"))
1808 return true;
1809
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001810 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 break;
1812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001813
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1815 case lltok::lparen:
1816 if (ParseFunctionType(Result))
1817 return true;
1818 break;
1819 }
1820 }
1821}
1822
1823/// ParseParameterList
1824/// ::= '(' ')'
1825/// ::= '(' Arg (',' Arg)* ')'
1826/// Arg
1827/// ::= Type OptionalAttributes Value OptionalAttributes
1828bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001829 PerFunctionState &PFS, bool IsMustTailCall,
1830 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 if (ParseToken(lltok::lparen, "expected '(' in call"))
1832 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001833
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001834 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001835 while (Lex.getKind() != lltok::rparen) {
1836 // If this isn't the first argument, we need a comma.
1837 if (!ArgList.empty() &&
1838 ParseToken(lltok::comma, "expected ',' in argument list"))
1839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001840
Reid Kleckner83498642014-08-26 00:33:28 +00001841 // Parse an ellipsis if this is a musttail call in a variadic function.
1842 if (Lex.getKind() == lltok::dotdotdot) {
1843 const char *Msg = "unexpected ellipsis in argument list for ";
1844 if (!IsMustTailCall)
1845 return TokError(Twine(Msg) + "non-musttail call");
1846 if (!InVarArgsFunc)
1847 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1848 Lex.Lex(); // Lex the '...', it is purely for readability.
1849 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1850 }
1851
Chris Lattnerac161bf2009-01-02 07:01:27 +00001852 // Parse the argument.
1853 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001854 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001855 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001857 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001859
Chris Lattner5b4a9622009-12-30 02:11:14 +00001860 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001861 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001862 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001863 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1864 AttrIndex++,
1865 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001866 }
1867
Reid Kleckner83498642014-08-26 00:33:28 +00001868 if (IsMustTailCall && InVarArgsFunc)
1869 return TokError("expected '...' at end of argument list for musttail call "
1870 "in varargs function");
1871
Chris Lattnerac161bf2009-01-02 07:01:27 +00001872 Lex.Lex(); // Lex the ')'.
1873 return false;
1874}
1875
1876
1877
Chris Lattner2ed06b42009-01-05 18:34:07 +00001878/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001879/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001880/// ::= '(' ArgTypeListI ')'
1881/// ArgTypeListI
1882/// ::= /*empty*/
1883/// ::= '...'
1884/// ::= ArgTypeList ',' '...'
1885/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001886///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001887bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1888 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 isVarArg = false;
1890 assert(Lex.getKind() == lltok::lparen);
1891 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001892
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 if (Lex.getKind() == lltok::rparen) {
1894 // empty
1895 } else if (Lex.getKind() == lltok::dotdotdot) {
1896 isVarArg = true;
1897 Lex.Lex();
1898 } else {
1899 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001900 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001901 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001902 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001903
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001904 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001905 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +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");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001909
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 }
Chris Lattner3822f632009-01-02 08:05:26 +00001914
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001915 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001916 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001917
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001918 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001919 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001920 AttributeSet::get(ArgTy->getContext(),
1921 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001922
Chris Lattner3822f632009-01-02 08:05:26 +00001923 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001925 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001926 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 break;
1928 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001929
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930 // Otherwise must be an argument type.
1931 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001932 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001933
Chris Lattnerfdd87902009-10-05 05:54:46 +00001934 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001935 return Error(TypeLoc, "argument can not have void type");
1936
Chris Lattnerdef19492011-06-17 06:36:20 +00001937 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938 Name = Lex.getStrVal();
1939 Lex.Lex();
1940 } else {
1941 Name = "";
1942 }
Chris Lattner3822f632009-01-02 08:05:26 +00001943
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001944 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001945 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Bill Wendlingd079a442012-10-15 04:46:55 +00001947 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001948 AttributeSet::get(ArgTy->getContext(),
1949 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001950 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001951 }
1952 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Chris Lattner3822f632009-01-02 08:05:26 +00001954 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001955}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001956
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957/// ParseFunctionType
1958/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001959bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001960 assert(Lex.getKind() == lltok::lparen);
1961
Chris Lattnerce473c72009-01-05 08:04:33 +00001962 if (!FunctionType::isValidReturnType(Result))
1963 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001964
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001965 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001966 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001967 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001969
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 // Reject names on the arguments lists.
1971 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1972 if (!ArgList[i].Name.empty())
1973 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001974 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001975 return Error(ArgList[i].Loc,
1976 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Jay Foadb804a2b2011-07-12 14:06:48 +00001979 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001980 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001982
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001983 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001984 return false;
1985}
1986
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1988/// other structs.
1989bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1990 SmallVector<Type*, 8> Elts;
1991 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 Result = StructType::get(Context, Elts, Packed);
1994 return false;
1995}
1996
1997/// ParseStructDefinition - Parse a struct in a 'type' definition.
1998bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1999 std::pair<Type*, LocTy> &Entry,
2000 Type *&ResultTy) {
2001 // If the type was already defined, diagnose the redefinition.
2002 if (Entry.first && !Entry.second.isValid())
2003 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002004
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005 // If we have opaque, just return without filling in the definition for the
2006 // struct. This counts as a definition as far as the .ll file goes.
2007 if (EatIfPresent(lltok::kw_opaque)) {
2008 // This type is being defined, so clear the location to indicate this.
2009 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002010
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002011 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002012 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002013 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 ResultTy = Entry.first;
2015 return false;
2016 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002017
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002018 // If the type starts with '<', then it is either a packed struct or a vector.
2019 bool isPacked = EatIfPresent(lltok::less);
2020
2021 // If we don't have a struct, then we have a random type alias, which we
2022 // accept for compatibility with old files. These types are not allowed to be
2023 // forward referenced and not allowed to be recursive.
2024 if (Lex.getKind() != lltok::lbrace) {
2025 if (Entry.first)
2026 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002027
Craig Topper2617dcc2014-04-15 06:32:26 +00002028 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002029 if (isPacked)
2030 return ParseArrayVectorType(ResultTy, true);
2031 return ParseType(ResultTy);
2032 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 // This type is being defined, so clear the location to indicate this.
2035 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002036
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002038 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002039 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002040
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002041 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002042
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043 SmallVector<Type*, 8> Body;
2044 if (ParseStructBody(Body) ||
2045 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2046 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002047
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002048 STy->setBody(Body, isPacked);
2049 ResultTy = STy;
2050 return false;
2051}
2052
2053
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002055/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002056/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002057/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059/// ::= '<' '{' Type (',' Type)* '}' '>'
2060bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 assert(Lex.getKind() == lltok::lbrace);
2062 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002063
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002064 // Handle the empty struct.
2065 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067
Chris Lattnerf880ca22009-03-09 04:49:14 +00002068 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002069 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070 if (ParseType(Ty)) return true;
2071 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002072
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002073 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002074 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075
Chris Lattner3822f632009-01-02 08:05:26 +00002076 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002077 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002079
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002080 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002081 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002082
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002086 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087}
2088
2089/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2090/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092/// ::= '[' APSINTVAL 'x' Types ']'
2093/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002094bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2096 Lex.getAPSIntVal().getBitWidth() > 64)
2097 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 LocTy SizeLoc = Lex.getLoc();
2100 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002101 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002102
Chris Lattner3822f632009-01-02 08:05:26 +00002103 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2104 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105
2106 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002107 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002108 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002109
Chris Lattner3822f632009-01-02 08:05:26 +00002110 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2111 "expected end of sequential type"))
2112 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002115 if (Size == 0)
2116 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 if ((unsigned)Size != Size)
2118 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002119 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002120 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002121 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002123 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002125 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002126 }
2127 return false;
2128}
2129
2130//===----------------------------------------------------------------------===//
2131// Function Semantic Analysis.
2132//===----------------------------------------------------------------------===//
2133
Chris Lattner3432c622009-10-28 03:39:23 +00002134LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2135 int functionNumber)
2136 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137
2138 // Insert unnamed arguments into the NumberedVals list.
2139 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2140 AI != E; ++AI)
2141 if (!AI->hasName())
2142 NumberedVals.push_back(AI);
2143}
2144
2145LLParser::PerFunctionState::~PerFunctionState() {
2146 // If there were any forward referenced non-basicblock values, delete them.
2147 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2148 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2149 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002150 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002151 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002153 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002155
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2157 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2158 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002159 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002160 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002161 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002162 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 }
2164}
2165
Chris Lattner3432c622009-10-28 03:39:23 +00002166bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 if (!ForwardRefVals.empty())
2168 return P.Error(ForwardRefVals.begin()->second.second,
2169 "use of undefined value '%" + ForwardRefVals.begin()->first +
2170 "'");
2171 if (!ForwardRefValIDs.empty())
2172 return P.Error(ForwardRefValIDs.begin()->second.second,
2173 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002174 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 return false;
2176}
2177
2178
2179/// GetVal - Get a value with the specified name or ID, creating a
2180/// forward reference record if needed. This can return null if the value
2181/// exists but does not have the right type.
2182Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002183 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 // Look this name up in the normal function symbol table.
2185 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002186
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 // If this is a forward reference for the value, see if we already created a
2188 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002189 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2191 I = ForwardRefVals.find(Name);
2192 if (I != ForwardRefVals.end())
2193 Val = I->second.first;
2194 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002195
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 // If we have the value in the symbol table or fwd-ref table, return it.
2197 if (Val) {
2198 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002199 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200 P.Error(Loc, "'%" + Name + "' is not a basic block");
2201 else
2202 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002203 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002204 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002206
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002208 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002210 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002211 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 // Otherwise, create a new forward reference for this value and remember it.
2214 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002215 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002216 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 else
2218 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002219
Chris Lattnerac161bf2009-01-02 07:01:27 +00002220 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2221 return FwdVal;
2222}
2223
Chris Lattner229907c2011-07-18 04:54:35 +00002224Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 LocTy Loc) {
2226 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002227 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002228
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 // If this is a forward reference for the value, see if we already created a
2230 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002231 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2233 I = ForwardRefValIDs.find(ID);
2234 if (I != ForwardRefValIDs.end())
2235 Val = I->second.first;
2236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002237
Chris Lattnerac161bf2009-01-02 07:01:27 +00002238 // If we have the value in the symbol table or fwd-ref table, return it.
2239 if (Val) {
2240 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002241 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002242 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002244 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002245 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002246 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002249 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002251 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 // Otherwise, create a new forward reference for this value and remember it.
2255 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002256 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002257 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 else
2259 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002260
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2262 return FwdVal;
2263}
2264
2265/// SetInstName - After an instruction is parsed and inserted into its
2266/// basic block, this installs its name.
2267bool LLParser::PerFunctionState::SetInstName(int NameID,
2268 const std::string &NameStr,
2269 LocTy NameLoc, Instruction *Inst) {
2270 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002271 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 if (NameID != -1 || !NameStr.empty())
2273 return P.Error(NameLoc, "instructions returning void cannot have a name");
2274 return false;
2275 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002276
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277 // If this was a numbered instruction, verify that the instruction is the
2278 // expected value and resolve any forward references.
2279 if (NameStr.empty()) {
2280 // If neither a name nor an ID was specified, just use the next ID.
2281 if (NameID == -1)
2282 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002283
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284 if (unsigned(NameID) != NumberedVals.size())
2285 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002286 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002287
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2289 ForwardRefValIDs.find(NameID);
2290 if (FI != ForwardRefValIDs.end()) {
2291 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002292 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002293 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002295 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296 ForwardRefValIDs.erase(FI);
2297 }
2298
2299 NumberedVals.push_back(Inst);
2300 return false;
2301 }
2302
2303 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2304 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2305 FI = ForwardRefVals.find(NameStr);
2306 if (FI != ForwardRefVals.end()) {
2307 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002308 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002309 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002311 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 ForwardRefVals.erase(FI);
2313 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 // Set the name on the instruction.
2316 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002317
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002318 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002319 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 NameStr + "'");
2321 return false;
2322}
2323
2324/// GetBB - Get a basic block with the specified name or ID, creating a
2325/// forward reference record if needed.
2326BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2327 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002328 return cast_or_null<BasicBlock>(GetVal(Name,
2329 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002330}
2331
2332BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002333 return cast_or_null<BasicBlock>(GetVal(ID,
2334 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335}
2336
2337/// DefineBB - Define the specified basic block, which is either named or
2338/// unnamed. If there is an error, this returns null otherwise it returns
2339/// the block being defined.
2340BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2341 LocTy Loc) {
2342 BasicBlock *BB;
2343 if (Name.empty())
2344 BB = GetBB(NumberedVals.size(), Loc);
2345 else
2346 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002347 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 // Move the block to the end of the function. Forward ref'd blocks are
2350 // inserted wherever they happen to be referenced.
2351 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002352
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353 // Remove the block from forward ref sets.
2354 if (Name.empty()) {
2355 ForwardRefValIDs.erase(NumberedVals.size());
2356 NumberedVals.push_back(BB);
2357 } else {
2358 // BB forward references are already in the function symbol table.
2359 ForwardRefVals.erase(Name);
2360 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002361
Chris Lattnerac161bf2009-01-02 07:01:27 +00002362 return BB;
2363}
2364
2365//===----------------------------------------------------------------------===//
2366// Constants.
2367//===----------------------------------------------------------------------===//
2368
2369/// ParseValID - Parse an abstract value that doesn't necessarily have a
2370/// type implied. For example, if we parse "4" we don't know what integer type
2371/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002372/// sanity. PFS is used to convert function-local operands of metadata (since
2373/// metadata operands are not just parsed here but also converted to values).
2374/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002375bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 ID.Loc = Lex.getLoc();
2377 switch (Lex.getKind()) {
2378 default: return TokError("expected value token");
2379 case lltok::GlobalID: // @42
2380 ID.UIntVal = Lex.getUIntVal();
2381 ID.Kind = ValID::t_GlobalID;
2382 break;
2383 case lltok::GlobalVar: // @foo
2384 ID.StrVal = Lex.getStrVal();
2385 ID.Kind = ValID::t_GlobalName;
2386 break;
2387 case lltok::LocalVarID: // %42
2388 ID.UIntVal = Lex.getUIntVal();
2389 ID.Kind = ValID::t_LocalID;
2390 break;
2391 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392 ID.StrVal = Lex.getStrVal();
2393 ID.Kind = ValID::t_LocalName;
2394 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002395 case lltok::exclaim: // !42, !{...}, or !"foo"
2396 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002398 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 ID.Kind = ValID::t_APSInt;
2400 break;
2401 case lltok::APFloat:
2402 ID.APFloatVal = Lex.getAPFloatVal();
2403 ID.Kind = ValID::t_APFloat;
2404 break;
2405 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002406 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 ID.Kind = ValID::t_Constant;
2408 break;
2409 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002410 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411 ID.Kind = ValID::t_Constant;
2412 break;
2413 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2414 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2415 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 case lltok::lbrace: {
2418 // ValID ::= '{' ConstVector '}'
2419 Lex.Lex();
2420 SmallVector<Constant*, 16> Elts;
2421 if (ParseGlobalValueVector(Elts) ||
2422 ParseToken(lltok::rbrace, "expected end of struct constant"))
2423 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002424
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002425 ID.ConstantStructElts = new Constant*[Elts.size()];
2426 ID.UIntVal = Elts.size();
2427 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2428 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429 return false;
2430 }
2431 case lltok::less: {
2432 // ValID ::= '<' ConstVector '>' --> Vector.
2433 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2434 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002435 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002436
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 SmallVector<Constant*, 16> Elts;
2438 LocTy FirstEltLoc = Lex.getLoc();
2439 if (ParseGlobalValueVector(Elts) ||
2440 (isPackedStruct &&
2441 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2442 ParseToken(lltok::greater, "expected end of constant"))
2443 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002446 ID.ConstantStructElts = new Constant*[Elts.size()];
2447 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2448 ID.UIntVal = Elts.size();
2449 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 return false;
2451 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002452
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 if (Elts.empty())
2454 return Error(ID.Loc, "constant vector must not be empty");
2455
Duncan Sands9dff9be2010-02-15 16:12:20 +00002456 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002457 !Elts[0]->getType()->isFloatingPointTy() &&
2458 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002460 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002461
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462 // Verify that all the vector elements have the same type.
2463 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2464 if (Elts[i]->getType() != Elts[0]->getType())
2465 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002466 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002467 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002468
Chris Lattner69229312011-02-15 00:14:00 +00002469 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002470 ID.Kind = ValID::t_Constant;
2471 return false;
2472 }
2473 case lltok::lsquare: { // Array Constant
2474 Lex.Lex();
2475 SmallVector<Constant*, 16> Elts;
2476 LocTy FirstEltLoc = Lex.getLoc();
2477 if (ParseGlobalValueVector(Elts) ||
2478 ParseToken(lltok::rsquare, "expected end of array constant"))
2479 return true;
2480
2481 // Handle empty element.
2482 if (Elts.empty()) {
2483 // Use undef instead of an array because it's inconvenient to determine
2484 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002485 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002486 return false;
2487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002490 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002491 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002492
Owen Anderson4056ca92009-07-29 22:17:13 +00002493 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002494
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002496 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 if (Elts[i]->getType() != Elts[0]->getType())
2498 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002499 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002500 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002502
Jay Foad83be3612011-06-22 09:24:39 +00002503 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 ID.Kind = ValID::t_Constant;
2505 return false;
2506 }
2507 case lltok::kw_c: // c "foo"
2508 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002509 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2510 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2512 ID.Kind = ValID::t_Constant;
2513 return false;
2514
2515 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002516 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2517 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002518 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 Lex.Lex();
2520 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002521 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002522 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002523 ParseStringConstant(ID.StrVal) ||
2524 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 ParseToken(lltok::StringConstant, "expected constraint string"))
2526 return true;
2527 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002528 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002529 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002530 ID.Kind = ValID::t_InlineAsm;
2531 return false;
2532 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002533
Chris Lattner3432c622009-10-28 03:39:23 +00002534 case lltok::kw_blockaddress: {
2535 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2536 Lex.Lex();
2537
2538 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002539
Chris Lattner3432c622009-10-28 03:39:23 +00002540 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2541 ParseValID(Fn) ||
2542 ParseToken(lltok::comma, "expected comma in block address expression")||
2543 ParseValID(Label) ||
2544 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2545 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002546
Chris Lattner3432c622009-10-28 03:39:23 +00002547 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2548 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002549 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002550 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002551
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002552 // Try to find the function (but skip it if it's forward-referenced).
2553 GlobalValue *GV = nullptr;
2554 if (Fn.Kind == ValID::t_GlobalID) {
2555 if (Fn.UIntVal < NumberedVals.size())
2556 GV = NumberedVals[Fn.UIntVal];
2557 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2558 GV = M->getNamedValue(Fn.StrVal);
2559 }
2560 Function *F = nullptr;
2561 if (GV) {
2562 // Confirm that it's actually a function with a definition.
2563 if (!isa<Function>(GV))
2564 return Error(Fn.Loc, "expected function name in blockaddress");
2565 F = cast<Function>(GV);
2566 if (F->isDeclaration())
2567 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2568 }
2569
2570 if (!F) {
2571 // Make a global variable as a placeholder for this reference.
2572 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2573 if (!FwdRef)
2574 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2575 GlobalValue::InternalLinkage, nullptr, "");
2576 ID.ConstantVal = FwdRef;
2577 ID.Kind = ValID::t_Constant;
2578 return false;
2579 }
2580
2581 // We found the function; now find the basic block. Don't use PFS, since we
2582 // might be inside a constant expression.
2583 BasicBlock *BB;
2584 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2585 if (Label.Kind == ValID::t_LocalID)
2586 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2587 else
2588 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2589 if (!BB)
2590 return Error(Label.Loc, "referenced value is not a basic block");
2591 } else {
2592 if (Label.Kind == ValID::t_LocalID)
2593 return Error(Label.Loc, "cannot take address of numeric label after "
2594 "the function is defined");
2595 BB = dyn_cast_or_null<BasicBlock>(
2596 F->getValueSymbolTable().lookup(Label.StrVal));
2597 if (!BB)
2598 return Error(Label.Loc, "referenced value is not a basic block");
2599 }
2600
2601 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002602 ID.Kind = ValID::t_Constant;
2603 return false;
2604 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002605
Chris Lattnerac161bf2009-01-02 07:01:27 +00002606 case lltok::kw_trunc:
2607 case lltok::kw_zext:
2608 case lltok::kw_sext:
2609 case lltok::kw_fptrunc:
2610 case lltok::kw_fpext:
2611 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002612 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 case lltok::kw_uitofp:
2614 case lltok::kw_sitofp:
2615 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002616 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002620 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 Constant *SrcVal;
2622 Lex.Lex();
2623 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2624 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002625 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 ParseType(DestTy) ||
2627 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2628 return true;
2629 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2630 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002631 getTypeString(SrcVal->getType()) + "' to '" +
2632 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002633 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002634 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635 ID.Kind = ValID::t_Constant;
2636 return false;
2637 }
2638 case lltok::kw_extractvalue: {
2639 Lex.Lex();
2640 Constant *Val;
2641 SmallVector<unsigned, 4> Indices;
2642 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2643 ParseGlobalTypeAndValue(Val) ||
2644 ParseIndexList(Indices) ||
2645 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2646 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002647
Chris Lattner392be582010-02-12 20:49:41 +00002648 if (!Val->getType()->isAggregateType())
2649 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002650 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002652 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 ID.Kind = ValID::t_Constant;
2654 return false;
2655 }
2656 case lltok::kw_insertvalue: {
2657 Lex.Lex();
2658 Constant *Val0, *Val1;
2659 SmallVector<unsigned, 4> Indices;
2660 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2661 ParseGlobalTypeAndValue(Val0) ||
2662 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2663 ParseGlobalTypeAndValue(Val1) ||
2664 ParseIndexList(Indices) ||
2665 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2666 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002667 if (!Val0->getType()->isAggregateType())
2668 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002669 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002671 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002672 ID.Kind = ValID::t_Constant;
2673 return false;
2674 }
2675 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002676 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 unsigned PredVal, Opc = Lex.getUIntVal();
2678 Constant *Val0, *Val1;
2679 Lex.Lex();
2680 if (ParseCmpPredicate(PredVal, Opc) ||
2681 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2682 ParseGlobalTypeAndValue(Val0) ||
2683 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2684 ParseGlobalTypeAndValue(Val1) ||
2685 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2686 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002687
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 if (Val0->getType() != Val1->getType())
2689 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002692
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002694 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002696 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002697 } else {
2698 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002699 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002700 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002702 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002703 }
2704 ID.Kind = ValID::t_Constant;
2705 return false;
2706 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002707
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 // Binary Operators.
2709 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002710 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002712 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002714 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 case lltok::kw_udiv:
2716 case lltok::kw_sdiv:
2717 case lltok::kw_fdiv:
2718 case lltok::kw_urem:
2719 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002720 case lltok::kw_frem:
2721 case lltok::kw_shl:
2722 case lltok::kw_lshr:
2723 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002724 bool NUW = false;
2725 bool NSW = false;
2726 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 unsigned Opc = Lex.getUIntVal();
2728 Constant *Val0, *Val1;
2729 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002730 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002731 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2732 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002733 if (EatIfPresent(lltok::kw_nuw))
2734 NUW = true;
2735 if (EatIfPresent(lltok::kw_nsw)) {
2736 NSW = true;
2737 if (EatIfPresent(lltok::kw_nuw))
2738 NUW = true;
2739 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002740 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2741 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002742 if (EatIfPresent(lltok::kw_exact))
2743 Exact = true;
2744 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002745 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2746 ParseGlobalTypeAndValue(Val0) ||
2747 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2748 ParseGlobalTypeAndValue(Val1) ||
2749 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2750 return true;
2751 if (Val0->getType() != Val1->getType())
2752 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002753 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002754 if (NUW)
2755 return Error(ModifierLoc, "nuw only applies to integer operations");
2756 if (NSW)
2757 return Error(ModifierLoc, "nsw only applies to integer operations");
2758 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002759 // Check that the type is valid for the operator.
2760 switch (Opc) {
2761 case Instruction::Add:
2762 case Instruction::Sub:
2763 case Instruction::Mul:
2764 case Instruction::UDiv:
2765 case Instruction::SDiv:
2766 case Instruction::URem:
2767 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002768 case Instruction::Shl:
2769 case Instruction::AShr:
2770 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002771 if (!Val0->getType()->isIntOrIntVectorTy())
2772 return Error(ID.Loc, "constexpr requires integer operands");
2773 break;
2774 case Instruction::FAdd:
2775 case Instruction::FSub:
2776 case Instruction::FMul:
2777 case Instruction::FDiv:
2778 case Instruction::FRem:
2779 if (!Val0->getType()->isFPOrFPVectorTy())
2780 return Error(ID.Loc, "constexpr requires fp operands");
2781 break;
2782 default: llvm_unreachable("Unknown binary operator!");
2783 }
Dan Gohman1b849082009-09-07 23:54:19 +00002784 unsigned Flags = 0;
2785 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2786 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002787 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002788 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002789 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 ID.Kind = ValID::t_Constant;
2791 return false;
2792 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002793
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002795 case lltok::kw_and:
2796 case lltok::kw_or:
2797 case lltok::kw_xor: {
2798 unsigned Opc = Lex.getUIntVal();
2799 Constant *Val0, *Val1;
2800 Lex.Lex();
2801 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2802 ParseGlobalTypeAndValue(Val0) ||
2803 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2804 ParseGlobalTypeAndValue(Val1) ||
2805 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2806 return true;
2807 if (Val0->getType() != Val1->getType())
2808 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002809 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 return Error(ID.Loc,
2811 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002812 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 ID.Kind = ValID::t_Constant;
2814 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002815 }
2816
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 case lltok::kw_getelementptr:
2818 case lltok::kw_shufflevector:
2819 case lltok::kw_insertelement:
2820 case lltok::kw_extractelement:
2821 case lltok::kw_select: {
2822 unsigned Opc = Lex.getUIntVal();
2823 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002824 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002826 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002827 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2829 ParseGlobalValueVector(Elts) ||
2830 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2831 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002834 if (Elts.size() == 0 ||
2835 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002836 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002837
Jay Foaded8db7d2011-07-21 14:31:17 +00002838 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002839 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002841 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2842 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 } else if (Opc == Instruction::Select) {
2844 if (Elts.size() != 3)
2845 return Error(ID.Loc, "expected three operands to select");
2846 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2847 Elts[2]))
2848 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002849 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002850 } else if (Opc == Instruction::ShuffleVector) {
2851 if (Elts.size() != 3)
2852 return Error(ID.Loc, "expected three operands to shufflevector");
2853 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2854 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002855 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002856 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 } else if (Opc == Instruction::ExtractElement) {
2858 if (Elts.size() != 2)
2859 return Error(ID.Loc, "expected two operands to extractelement");
2860 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2861 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002862 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 } else {
2864 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2865 if (Elts.size() != 3)
2866 return Error(ID.Loc, "expected three operands to insertelement");
2867 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2868 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002869 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002870 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002872
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 ID.Kind = ValID::t_Constant;
2874 return false;
2875 }
2876 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002877
Chris Lattnerac161bf2009-01-02 07:01:27 +00002878 Lex.Lex();
2879 return false;
2880}
2881
2882/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002883bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002884 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002886 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002887 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002888 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002889 if (V && !(C = dyn_cast<Constant>(V)))
2890 return Error(ID.Loc, "global values must be constants");
2891 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002892}
2893
Victor Hernandez9d75c962010-01-11 22:31:58 +00002894bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002895 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002896 return ParseType(Ty) ||
2897 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002898}
2899
David Majnemerdad0a642014-06-27 18:19:56 +00002900bool LLParser::parseOptionalComdat(Comdat *&C) {
2901 C = nullptr;
2902 if (!EatIfPresent(lltok::kw_comdat))
2903 return false;
2904 if (Lex.getKind() != lltok::ComdatVar)
2905 return TokError("expected comdat variable");
2906 LocTy Loc = Lex.getLoc();
2907 StringRef Name = Lex.getStrVal();
2908 C = getComdat(Name, Loc);
2909 Lex.Lex();
2910 return false;
2911}
2912
Victor Hernandez9d75c962010-01-11 22:31:58 +00002913/// ParseGlobalValueVector
2914/// ::= /*empty*/
2915/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002916bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002917 // Empty list.
2918 if (Lex.getKind() == lltok::rbrace ||
2919 Lex.getKind() == lltok::rsquare ||
2920 Lex.getKind() == lltok::greater ||
2921 Lex.getKind() == lltok::rparen)
2922 return false;
2923
2924 Constant *C;
2925 if (ParseGlobalTypeAndValue(C)) return true;
2926 Elts.push_back(C);
2927
2928 while (EatIfPresent(lltok::comma)) {
2929 if (ParseGlobalTypeAndValue(C)) return true;
2930 Elts.push_back(C);
2931 }
2932
2933 return false;
2934}
2935
Dan Gohmanc828c542010-08-24 02:24:03 +00002936bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2937 assert(Lex.getKind() == lltok::lbrace);
2938 Lex.Lex();
2939
2940 SmallVector<Value*, 16> Elts;
2941 if (ParseMDNodeVector(Elts, PFS) ||
2942 ParseToken(lltok::rbrace, "expected end of metadata node"))
2943 return true;
2944
Jay Foad5514afe2011-04-21 19:59:31 +00002945 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002946 ID.Kind = ValID::t_MDNode;
2947 return false;
2948}
2949
Dan Gohman8939ba332010-07-14 18:26:50 +00002950/// ParseMetadataValue
2951/// ::= !42
2952/// ::= !{...}
2953/// ::= !"string"
2954bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2955 assert(Lex.getKind() == lltok::exclaim);
2956 Lex.Lex();
2957
2958 // MDNode:
2959 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002960 if (Lex.getKind() == lltok::lbrace)
2961 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002962
2963 // Standalone metadata reference
2964 // !42
2965 if (Lex.getKind() == lltok::APSInt) {
2966 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2967 ID.Kind = ValID::t_MDNode;
2968 return false;
2969 }
2970
2971 // MDString:
2972 // ::= '!' STRINGCONSTANT
2973 if (ParseMDString(ID.MDStringVal)) return true;
2974 ID.Kind = ValID::t_MDString;
2975 return false;
2976}
2977
Victor Hernandez9d75c962010-01-11 22:31:58 +00002978
2979//===----------------------------------------------------------------------===//
2980// Function Parsing.
2981//===----------------------------------------------------------------------===//
2982
Chris Lattner229907c2011-07-18 04:54:35 +00002983bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00002984 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002985 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002987
Chris Lattnerac161bf2009-01-02 07:01:27 +00002988 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002989 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002990 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2991 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002992 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002993 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002994 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2995 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002996 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002997 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00002998 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002999 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003000 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003001 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3002 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003003 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003004 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003005 return false;
3006 }
3007 case ValID::t_MDNode:
3008 if (!Ty->isMetadataTy())
3009 return Error(ID.Loc, "metadata value must have metadata type");
3010 V = ID.MDNodeVal;
3011 return false;
3012 case ValID::t_MDString:
3013 if (!Ty->isMetadataTy())
3014 return Error(ID.Loc, "metadata value must have metadata type");
3015 V = ID.MDStringVal;
3016 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003017 case ValID::t_GlobalName:
3018 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003019 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 case ValID::t_GlobalID:
3021 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003022 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003024 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003025 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003026 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003027 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003028 return false;
3029 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003030 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003031 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3032 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003033
Dan Gohman518cda42011-12-17 00:04:22 +00003034 // The lexer has no type info, so builds all half, float, and double FP
3035 // constants as double. Fix this here. Long double does not need this.
3036 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003038 if (Ty->isHalfTy())
3039 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3040 &Ignored);
3041 else if (Ty->isFloatTy())
3042 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3043 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003044 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003045 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003046
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003047 if (V->getType() != Ty)
3048 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003049 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003050
Chris Lattnerac161bf2009-01-02 07:01:27 +00003051 return false;
3052 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003053 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003054 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003055 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003056 return false;
3057 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003058 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003059 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003060 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003061 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003062 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003063 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003064 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003065 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003066 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003067 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003069 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003070 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003071 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003072 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 return false;
3074 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003075 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003076 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003077
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 V = ID.ConstantVal;
3079 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003080 case ValID::t_ConstantStruct:
3081 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003082 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003083 if (ST->getNumElements() != ID.UIntVal)
3084 return Error(ID.Loc,
3085 "initializer with struct type has wrong # elements");
3086 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3087 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003088
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003089 // Verify that the elements are compatible with the structtype.
3090 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3091 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3092 return Error(ID.Loc, "element " + Twine(i) +
3093 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003094
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003095 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3096 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003097 } else
3098 return Error(ID.Loc, "constant expression type mismatch");
3099 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003100 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003101 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003102}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003103
Chris Lattner229907c2011-07-18 04:54:35 +00003104bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003105 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003106 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003107 return ParseValID(ID, PFS) ||
3108 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003109}
3110
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003111bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003112 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003113 return ParseType(Ty) ||
3114 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003115}
3116
Chris Lattner3ed871f2009-10-27 19:13:16 +00003117bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3118 PerFunctionState &PFS) {
3119 Value *V;
3120 Loc = Lex.getLoc();
3121 if (ParseTypeAndValue(V, PFS)) return true;
3122 if (!isa<BasicBlock>(V))
3123 return Error(Loc, "expected a basic block");
3124 BB = cast<BasicBlock>(V);
3125 return false;
3126}
3127
3128
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129/// FunctionHeader
3130/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003131/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003132/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003133bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3134 // Parse the linkage.
3135 LocTy LinkageLoc = Lex.getLoc();
3136 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003137
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003138 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003139 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003140 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003141 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003142 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003143 LocTy RetTypeLoc = Lex.getLoc();
3144 if (ParseOptionalLinkage(Linkage) ||
3145 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003146 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003148 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003149 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003150 return true;
3151
3152 // Verify that the linkage is ok.
3153 switch ((GlobalValue::LinkageTypes)Linkage) {
3154 case GlobalValue::ExternalLinkage:
3155 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003156 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003157 if (isDefine)
3158 return Error(LinkageLoc, "invalid linkage for function definition");
3159 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003160 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003161 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003162 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003163 case GlobalValue::LinkOnceAnyLinkage:
3164 case GlobalValue::LinkOnceODRLinkage:
3165 case GlobalValue::WeakAnyLinkage:
3166 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003167 if (!isDefine)
3168 return Error(LinkageLoc, "invalid linkage for function declaration");
3169 break;
3170 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003171 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 return Error(LinkageLoc, "invalid function linkage type");
3173 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003174
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003175 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3176 return Error(LinkageLoc,
3177 "symbol with local linkage must have default visibility");
3178
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003179 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003180 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003181
Chris Lattnerac161bf2009-01-02 07:01:27 +00003182 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003183
3184 std::string FunctionName;
3185 if (Lex.getKind() == lltok::GlobalVar) {
3186 FunctionName = Lex.getStrVal();
3187 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3188 unsigned NameID = Lex.getUIntVal();
3189
3190 if (NameID != NumberedVals.size())
3191 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003192 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003193 } else {
3194 return TokError("expected function name");
3195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003196
Chris Lattner3822f632009-01-02 08:05:26 +00003197 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Chris Lattner3822f632009-01-02 08:05:26 +00003199 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003201
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003202 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003204 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003205 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003206 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003207 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003209 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003210 bool UnnamedAddr;
3211 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003212 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003213 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003214 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003216 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003217 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3218 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003219 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003220 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003221 (EatIfPresent(lltok::kw_section) &&
3222 ParseStringConstant(Section)) ||
David Majnemerdad0a642014-06-27 18:19:56 +00003223 parseOptionalComdat(C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003224 ParseOptionalAlignment(Alignment) ||
3225 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003226 ParseStringConstant(GC)) ||
3227 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003228 ParseGlobalTypeAndValue(Prefix)) ||
3229 (EatIfPresent(lltok::kw_prologue) &&
3230 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003231 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003232
Michael Gottesman41748d72013-06-27 00:25:01 +00003233 if (FuncAttrs.contains(Attribute::Builtin))
3234 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003235
Chris Lattnerac161bf2009-01-02 07:01:27 +00003236 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003237 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003238 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003239 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003240 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003241
Chris Lattnerac161bf2009-01-02 07:01:27 +00003242 // Okay, if we got here, the function is syntactically valid. Convert types
3243 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003244 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003245 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003246
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003247 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003248 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3249 AttributeSet::ReturnIndex,
3250 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003251
Chris Lattnerac161bf2009-01-02 07:01:27 +00003252 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003253 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003254 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3255 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003256 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3257 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003258 }
3259
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003260 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003261 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3262 AttributeSet::FunctionIndex,
3263 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003264
Bill Wendlinge94d8432012-12-07 23:16:57 +00003265 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003266
Bill Wendling749a43d2012-12-30 13:50:49 +00003267 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003268 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3269
Chris Lattner229907c2011-07-18 04:54:35 +00003270 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003271 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003272 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273
Craig Topper2617dcc2014-04-15 06:32:26 +00003274 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003275 if (!FunctionName.empty()) {
3276 // If this was a definition of a forward reference, remove the definition
3277 // from the forward reference table and fill in the forward ref.
3278 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3279 ForwardRefVals.find(FunctionName);
3280 if (FRVI != ForwardRefVals.end()) {
3281 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003282 if (!Fn)
3283 return Error(FRVI->second.second, "invalid forward reference to "
3284 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003285 if (Fn->getType() != PFT)
3286 return Error(FRVI->second.second, "invalid forward reference to "
3287 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003288
Chris Lattnerac161bf2009-01-02 07:01:27 +00003289 ForwardRefVals.erase(FRVI);
3290 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003291 // Reject redefinitions.
3292 return Error(NameLoc, "invalid redefinition of function '" +
3293 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003294 } else if (M->getNamedValue(FunctionName)) {
3295 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003297
Dan Gohman399d6ae2009-08-29 23:37:49 +00003298 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003299 // If this is a definition of a forward referenced function, make sure the
3300 // types agree.
3301 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3302 = ForwardRefValIDs.find(NumberedVals.size());
3303 if (I != ForwardRefValIDs.end()) {
3304 Fn = cast<Function>(I->second.first);
3305 if (Fn->getType() != PFT)
3306 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003307 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003308 ForwardRefValIDs.erase(I);
3309 }
3310 }
3311
Craig Topper2617dcc2014-04-15 06:32:26 +00003312 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003313 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3314 else // Move the forward-reference to the correct spot in the module.
3315 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3316
3317 if (FunctionName.empty())
3318 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003319
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3321 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003322 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 Fn->setCallingConv(CC);
3324 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003325 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003326 Fn->setAlignment(Alignment);
3327 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003328 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003329 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003330 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003331 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003332 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003333
Chris Lattnerac161bf2009-01-02 07:01:27 +00003334 // Add all of the arguments we parsed to the function.
3335 Function::arg_iterator ArgIt = Fn->arg_begin();
3336 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3337 // If the argument has a name, insert it into the argument symbol table.
3338 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003339
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 // Set the name, if it conflicted, it will be auto-renamed.
3341 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003342
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003343 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003344 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3345 ArgList[i].Name + "'");
3346 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003347
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003348 if (isDefine)
3349 return false;
3350
Robin Morisset039781e2014-08-29 21:53:01 +00003351 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003352 ValID ID;
3353 if (FunctionName.empty()) {
3354 ID.Kind = ValID::t_GlobalID;
3355 ID.UIntVal = NumberedVals.size() - 1;
3356 } else {
3357 ID.Kind = ValID::t_GlobalName;
3358 ID.StrVal = FunctionName;
3359 }
3360 auto Blocks = ForwardRefBlockAddresses.find(ID);
3361 if (Blocks != ForwardRefBlockAddresses.end())
3362 return Error(Blocks->first.Loc,
3363 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003364 return false;
3365}
3366
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003367bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3368 ValID ID;
3369 if (FunctionNumber == -1) {
3370 ID.Kind = ValID::t_GlobalName;
3371 ID.StrVal = F.getName();
3372 } else {
3373 ID.Kind = ValID::t_GlobalID;
3374 ID.UIntVal = FunctionNumber;
3375 }
3376
3377 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3378 if (Blocks == P.ForwardRefBlockAddresses.end())
3379 return false;
3380
3381 for (const auto &I : Blocks->second) {
3382 const ValID &BBID = I.first;
3383 GlobalValue *GV = I.second;
3384
3385 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3386 "Expected local id or name");
3387 BasicBlock *BB;
3388 if (BBID.Kind == ValID::t_LocalName)
3389 BB = GetBB(BBID.StrVal, BBID.Loc);
3390 else
3391 BB = GetBB(BBID.UIntVal, BBID.Loc);
3392 if (!BB)
3393 return P.Error(BBID.Loc, "referenced value is not a basic block");
3394
3395 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3396 GV->eraseFromParent();
3397 }
3398
3399 P.ForwardRefBlockAddresses.erase(Blocks);
3400 return false;
3401}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003402
3403/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003404/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003405bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003406 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003407 return TokError("expected '{' in function body");
3408 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003409
Chris Lattner3432c622009-10-28 03:39:23 +00003410 int FunctionNumber = -1;
3411 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003412
Chris Lattner3432c622009-10-28 03:39:23 +00003413 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003414
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003415 // Resolve block addresses and allow basic blocks to be forward-declared
3416 // within this function.
3417 if (PFS.resolveForwardRefBlockAddresses())
3418 return true;
3419 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3420
Chris Lattnerbbddd962010-01-09 19:20:07 +00003421 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003422 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003423 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003424
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003425 while (Lex.getKind() != lltok::rbrace &&
3426 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003427 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003428
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003429 while (Lex.getKind() != lltok::rbrace)
3430 if (ParseUseListOrder(&PFS))
3431 return true;
3432
Chris Lattnerac161bf2009-01-02 07:01:27 +00003433 // Eat the }.
3434 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003435
Chris Lattnerac161bf2009-01-02 07:01:27 +00003436 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003437 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003438}
3439
3440/// ParseBasicBlock
3441/// ::= LabelStr? Instruction*
3442bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3443 // If this basic block starts out with a name, remember it.
3444 std::string Name;
3445 LocTy NameLoc = Lex.getLoc();
3446 if (Lex.getKind() == lltok::LabelStr) {
3447 Name = Lex.getStrVal();
3448 Lex.Lex();
3449 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003450
Chris Lattnerac161bf2009-01-02 07:01:27 +00003451 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003452 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003453
Chris Lattnerac161bf2009-01-02 07:01:27 +00003454 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003455
Chris Lattnerac161bf2009-01-02 07:01:27 +00003456 // Parse the instructions in this block until we get a terminator.
3457 Instruction *Inst;
3458 do {
3459 // This instruction may have three possibilities for a name: a) none
3460 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3461 LocTy NameLoc = Lex.getLoc();
3462 int NameID = -1;
3463 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003464
Chris Lattnerac161bf2009-01-02 07:01:27 +00003465 if (Lex.getKind() == lltok::LocalVarID) {
3466 NameID = Lex.getUIntVal();
3467 Lex.Lex();
3468 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3469 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003470 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003471 NameStr = Lex.getStrVal();
3472 Lex.Lex();
3473 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3474 return true;
3475 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003476
Chris Lattner77b89dc2009-12-30 05:23:43 +00003477 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003478 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003479 case InstError: return true;
3480 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003481 BB->getInstList().push_back(Inst);
3482
Chris Lattner77b89dc2009-12-30 05:23:43 +00003483 // With a normal result, we check to see if the instruction is followed by
3484 // a comma and metadata.
3485 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003486 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003487 return true;
3488 break;
3489 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003490 BB->getInstList().push_back(Inst);
3491
Chris Lattner77b89dc2009-12-30 05:23:43 +00003492 // If the instruction parser ate an extra comma at the end of it, it
3493 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003494 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003495 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003496 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003497 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003498
Chris Lattnerac161bf2009-01-02 07:01:27 +00003499 // Set the name on the instruction.
3500 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3501 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003502
Chris Lattnerac161bf2009-01-02 07:01:27 +00003503 return false;
3504}
3505
3506//===----------------------------------------------------------------------===//
3507// Instruction Parsing.
3508//===----------------------------------------------------------------------===//
3509
3510/// ParseInstruction - Parse one of the many different instructions.
3511///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003512int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3513 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003514 lltok::Kind Token = Lex.getKind();
3515 if (Token == lltok::Eof)
3516 return TokError("found end of file when expecting more instructions");
3517 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003518 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003519 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003520
Chris Lattnerac161bf2009-01-02 07:01:27 +00003521 switch (Token) {
3522 default: return Error(Loc, "expected instruction opcode");
3523 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003524 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003525 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3526 case lltok::kw_br: return ParseBr(Inst, PFS);
3527 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003528 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003530 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003531 // Binary Operators.
3532 case lltok::kw_add:
3533 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003534 case lltok::kw_mul:
3535 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003536 bool NUW = EatIfPresent(lltok::kw_nuw);
3537 bool NSW = EatIfPresent(lltok::kw_nsw);
3538 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003539
Chris Lattnera676c0f2011-02-07 16:40:21 +00003540 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003541
Chris Lattnera676c0f2011-02-07 16:40:21 +00003542 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3543 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3544 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003545 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003546 case lltok::kw_fadd:
3547 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003548 case lltok::kw_fmul:
3549 case lltok::kw_fdiv:
3550 case lltok::kw_frem: {
3551 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3552 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3553 if (Res != 0)
3554 return Res;
3555 if (FMF.any())
3556 Inst->setFastMathFlags(FMF);
3557 return 0;
3558 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003559
Chris Lattner35315d02011-02-06 21:44:57 +00003560 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003561 case lltok::kw_udiv:
3562 case lltok::kw_lshr:
3563 case lltok::kw_ashr: {
3564 bool Exact = EatIfPresent(lltok::kw_exact);
3565
3566 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3567 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3568 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003569 }
3570
Chris Lattnerac161bf2009-01-02 07:01:27 +00003571 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003572 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003573 case lltok::kw_and:
3574 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003575 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003576 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003577 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003578 // Casts.
3579 case lltok::kw_trunc:
3580 case lltok::kw_zext:
3581 case lltok::kw_sext:
3582 case lltok::kw_fptrunc:
3583 case lltok::kw_fpext:
3584 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003585 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003586 case lltok::kw_uitofp:
3587 case lltok::kw_sitofp:
3588 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003589 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003590 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003591 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003592 // Other.
3593 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003594 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003595 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3596 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3597 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3598 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003599 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003600 // Call.
3601 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3602 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3603 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003604 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003605 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003606 case lltok::kw_load: return ParseLoad(Inst, PFS);
3607 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003608 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3609 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003610 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003611 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3612 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3613 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3614 }
3615}
3616
3617/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3618bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003619 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003620 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003621 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003622 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3623 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3624 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3625 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3626 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3627 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3628 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3629 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3630 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3631 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3632 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3633 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3634 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3635 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3636 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3637 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3638 }
3639 } else {
3640 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003641 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003642 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3643 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3644 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3645 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3646 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3647 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3648 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3649 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3650 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3651 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3652 }
3653 }
3654 Lex.Lex();
3655 return false;
3656}
3657
3658//===----------------------------------------------------------------------===//
3659// Terminator Instructions.
3660//===----------------------------------------------------------------------===//
3661
3662/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003663/// ::= 'ret' void (',' !dbg, !1)*
3664/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003665bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003666 PerFunctionState &PFS) {
3667 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003668 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003669 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003670
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003671 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003672
Chris Lattnerfdd87902009-10-05 05:54:46 +00003673 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003674 if (!ResType->isVoidTy())
3675 return Error(TypeLoc, "value doesn't match function result type '" +
3676 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003677
Owen Anderson55f1c092009-08-13 21:58:54 +00003678 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003679 return false;
3680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003681
Chris Lattnerac161bf2009-01-02 07:01:27 +00003682 Value *RV;
3683 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003684
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003685 if (ResType != RV->getType())
3686 return Error(TypeLoc, "value doesn't match function result type '" +
3687 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003688
Owen Anderson55f1c092009-08-13 21:58:54 +00003689 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003690 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003691}
3692
3693
3694/// ParseBr
3695/// ::= 'br' TypeAndValue
3696/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3697bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3698 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003699 Value *Op0;
3700 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003701 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003702
Chris Lattnerac161bf2009-01-02 07:01:27 +00003703 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3704 Inst = BranchInst::Create(BB);
3705 return false;
3706 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003707
Owen Anderson55f1c092009-08-13 21:58:54 +00003708 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003709 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003710
Chris Lattnerac161bf2009-01-02 07:01:27 +00003711 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003712 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003713 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003714 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003715 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003716
Chris Lattner3ed871f2009-10-27 19:13:16 +00003717 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003718 return false;
3719}
3720
3721/// ParseSwitch
3722/// Instruction
3723/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3724/// JumpTable
3725/// ::= (TypeAndValue ',' TypeAndValue)*
3726bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3727 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003728 Value *Cond;
3729 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003730 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3731 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003732 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003733 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3734 return true;
3735
Duncan Sands19d0b472010-02-16 11:11:14 +00003736 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003737 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003738
Chris Lattnerac161bf2009-01-02 07:01:27 +00003739 // Parse the jump table pairs.
3740 SmallPtrSet<Value*, 32> SeenCases;
3741 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3742 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003743 Value *Constant;
3744 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003745
Chris Lattnerac161bf2009-01-02 07:01:27 +00003746 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3747 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003748 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003749 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003750
David Blaikie70573dc2014-11-19 07:49:26 +00003751 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003752 return Error(CondLoc, "duplicate case value in switch");
3753 if (!isa<ConstantInt>(Constant))
3754 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003755
Chris Lattner3ed871f2009-10-27 19:13:16 +00003756 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003757 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003758
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003760
Chris Lattner3ed871f2009-10-27 19:13:16 +00003761 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003762 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3763 SI->addCase(Table[i].first, Table[i].second);
3764 Inst = SI;
3765 return false;
3766}
3767
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003768/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003769/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003770/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3771bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003772 LocTy AddrLoc;
3773 Value *Address;
3774 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003775 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3776 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003777 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003778
Duncan Sands19d0b472010-02-16 11:11:14 +00003779 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003780 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003781
Chris Lattner3ed871f2009-10-27 19:13:16 +00003782 // Parse the destination list.
3783 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003784
Chris Lattner3ed871f2009-10-27 19:13:16 +00003785 if (Lex.getKind() != lltok::rsquare) {
3786 BasicBlock *DestBB;
3787 if (ParseTypeAndBasicBlock(DestBB, PFS))
3788 return true;
3789 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003790
Chris Lattner3ed871f2009-10-27 19:13:16 +00003791 while (EatIfPresent(lltok::comma)) {
3792 if (ParseTypeAndBasicBlock(DestBB, PFS))
3793 return true;
3794 DestList.push_back(DestBB);
3795 }
3796 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003797
Chris Lattner3ed871f2009-10-27 19:13:16 +00003798 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3799 return true;
3800
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003801 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003802 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3803 IBI->addDestination(DestList[i]);
3804 Inst = IBI;
3805 return false;
3806}
3807
3808
Chris Lattnerac161bf2009-01-02 07:01:27 +00003809/// ParseInvoke
3810/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3811/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3812bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3813 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003814 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003815 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003816 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003817 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003818 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003819 LocTy RetTypeLoc;
3820 ValID CalleeID;
3821 SmallVector<ParamInfo, 16> ArgList;
3822
Chris Lattner3ed871f2009-10-27 19:13:16 +00003823 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003824 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003825 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003826 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003827 ParseValID(CalleeID) ||
3828 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003829 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3830 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003831 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003832 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003833 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003834 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003835 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003836
Chris Lattnerac161bf2009-01-02 07:01:27 +00003837 // If RetType is a non-function pointer type, then this is the short syntax
3838 // for the call, which means that RetType is just the return type. Infer the
3839 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003840 PointerType *PFTy = nullptr;
3841 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003842 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3843 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3844 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003845 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003846 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3847 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003848
Chris Lattnerac161bf2009-01-02 07:01:27 +00003849 if (!FunctionType::isValidReturnType(RetType))
3850 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003851
Owen Anderson4056ca92009-07-29 22:17:13 +00003852 Ty = FunctionType::get(RetType, ParamTypes, false);
3853 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003854 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003855
Chris Lattnerac161bf2009-01-02 07:01:27 +00003856 // Look up the callee.
3857 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003858 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003859
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003860 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003861 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003862 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003863 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3864 AttributeSet::ReturnIndex,
3865 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003866
Chris Lattnerac161bf2009-01-02 07:01:27 +00003867 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003868
Chris Lattnerac161bf2009-01-02 07:01:27 +00003869 // Loop through FunctionType's arguments and ensure they are specified
3870 // correctly. Also, gather any parameter attributes.
3871 FunctionType::param_iterator I = Ty->param_begin();
3872 FunctionType::param_iterator E = Ty->param_end();
3873 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003874 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003875 if (I != E) {
3876 ExpectedTy = *I++;
3877 } else if (!Ty->isVarArg()) {
3878 return Error(ArgList[i].Loc, "too many arguments specified");
3879 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003880
Chris Lattnerac161bf2009-01-02 07:01:27 +00003881 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3882 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003883 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003885 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3886 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003887 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3888 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003890
Chris Lattnerac161bf2009-01-02 07:01:27 +00003891 if (I != E)
3892 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003893
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003894 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003895 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3896 AttributeSet::FunctionIndex,
3897 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003898
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003899 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003900 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003901
Jay Foad5bd375a2011-07-15 08:37:34 +00003902 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003903 II->setCallingConv(CC);
3904 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003905 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003906 Inst = II;
3907 return false;
3908}
3909
Bill Wendlingf891bf82011-07-31 06:30:59 +00003910/// ParseResume
3911/// ::= 'resume' TypeAndValue
3912bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3913 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003914 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3915 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003916
Bill Wendlingf891bf82011-07-31 06:30:59 +00003917 ResumeInst *RI = ResumeInst::Create(Exn);
3918 Inst = RI;
3919 return false;
3920}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921
3922//===----------------------------------------------------------------------===//
3923// Binary Operators.
3924//===----------------------------------------------------------------------===//
3925
3926/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003927/// ::= ArithmeticOps TypeAndValue ',' Value
3928///
3929/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3930/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003932 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003933 LocTy Loc; Value *LHS, *RHS;
3934 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3935 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3936 ParseValue(LHS->getType(), RHS, PFS))
3937 return true;
3938
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003939 bool Valid;
3940 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003941 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003942 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003943 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3944 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003945 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003946 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3947 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003949
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003950 if (!Valid)
3951 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003952
Chris Lattnerac161bf2009-01-02 07:01:27 +00003953 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3954 return false;
3955}
3956
3957/// ParseLogical
3958/// ::= ArithmeticOps TypeAndValue ',' Value {
3959bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3960 unsigned Opc) {
3961 LocTy Loc; Value *LHS, *RHS;
3962 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3963 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3964 ParseValue(LHS->getType(), RHS, PFS))
3965 return true;
3966
Duncan Sands9dff9be2010-02-15 16:12:20 +00003967 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003968 return Error(Loc,"instruction requires integer or integer vector operands");
3969
3970 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3971 return false;
3972}
3973
3974
3975/// ParseCompare
3976/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3977/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3979 unsigned Opc) {
3980 // Parse the integer/fp comparison predicate.
3981 LocTy Loc;
3982 unsigned Pred;
3983 Value *LHS, *RHS;
3984 if (ParseCmpPredicate(Pred, Opc) ||
3985 ParseTypeAndValue(LHS, Loc, PFS) ||
3986 ParseToken(lltok::comma, "expected ',' after compare value") ||
3987 ParseValue(LHS->getType(), RHS, PFS))
3988 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003989
Chris Lattnerac161bf2009-01-02 07:01:27 +00003990 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003991 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003992 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003993 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003994 } else {
3995 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003996 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003997 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003998 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003999 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004000 }
4001 return false;
4002}
4003
4004//===----------------------------------------------------------------------===//
4005// Other Instructions.
4006//===----------------------------------------------------------------------===//
4007
4008
4009/// ParseCast
4010/// ::= CastOpc TypeAndValue 'to' Type
4011bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4012 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004013 LocTy Loc;
4014 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004015 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004016 if (ParseTypeAndValue(Op, Loc, PFS) ||
4017 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4018 ParseType(DestTy))
4019 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004020
Chris Lattner89d856e2009-03-01 00:53:13 +00004021 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4022 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004023 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004024 getTypeString(Op->getType()) + "' to '" +
4025 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004026 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004027 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4028 return false;
4029}
4030
4031/// ParseSelect
4032/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4033bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4034 LocTy Loc;
4035 Value *Op0, *Op1, *Op2;
4036 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4037 ParseToken(lltok::comma, "expected ',' after select condition") ||
4038 ParseTypeAndValue(Op1, PFS) ||
4039 ParseToken(lltok::comma, "expected ',' after select value") ||
4040 ParseTypeAndValue(Op2, PFS))
4041 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004042
Chris Lattnerac161bf2009-01-02 07:01:27 +00004043 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4044 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004045
Chris Lattnerac161bf2009-01-02 07:01:27 +00004046 Inst = SelectInst::Create(Op0, Op1, Op2);
4047 return false;
4048}
4049
Chris Lattnerb55ab542009-01-05 08:18:44 +00004050/// ParseVA_Arg
4051/// ::= 'va_arg' TypeAndValue ',' Type
4052bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004054 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004055 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056 if (ParseTypeAndValue(Op, PFS) ||
4057 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004058 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004059 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004060
Chris Lattnerb55ab542009-01-05 08:18:44 +00004061 if (!EltTy->isFirstClassType())
4062 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004063
4064 Inst = new VAArgInst(Op, EltTy);
4065 return false;
4066}
4067
4068/// ParseExtractElement
4069/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4070bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4071 LocTy Loc;
4072 Value *Op0, *Op1;
4073 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4074 ParseToken(lltok::comma, "expected ',' after extract value") ||
4075 ParseTypeAndValue(Op1, PFS))
4076 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004077
Chris Lattnerac161bf2009-01-02 07:01:27 +00004078 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4079 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004080
Eric Christopherc9742252009-07-25 02:28:41 +00004081 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004082 return false;
4083}
4084
4085/// ParseInsertElement
4086/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4087bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4088 LocTy Loc;
4089 Value *Op0, *Op1, *Op2;
4090 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4091 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4092 ParseTypeAndValue(Op1, PFS) ||
4093 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4094 ParseTypeAndValue(Op2, PFS))
4095 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004096
Chris Lattnerac161bf2009-01-02 07:01:27 +00004097 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004098 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004099
Chris Lattnerac161bf2009-01-02 07:01:27 +00004100 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4101 return false;
4102}
4103
4104/// ParseShuffleVector
4105/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4106bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4107 LocTy Loc;
4108 Value *Op0, *Op1, *Op2;
4109 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4110 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4111 ParseTypeAndValue(Op1, PFS) ||
4112 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4113 ParseTypeAndValue(Op2, PFS))
4114 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004115
Chris Lattnerac161bf2009-01-02 07:01:27 +00004116 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004117 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004118
Chris Lattnerac161bf2009-01-02 07:01:27 +00004119 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4120 return false;
4121}
4122
4123/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004124/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004125int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004126 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004127 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004129 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004130 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4131 ParseValue(Ty, Op0, PFS) ||
4132 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004133 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004134 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4135 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004136
Chris Lattnerf4f03422009-12-30 05:27:33 +00004137 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004138 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4139 while (1) {
4140 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004141
Chris Lattner3822f632009-01-02 08:05:26 +00004142 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004143 break;
4144
Chris Lattnerf4f03422009-12-30 05:27:33 +00004145 if (Lex.getKind() == lltok::MetadataVar) {
4146 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004147 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004148 }
Devang Patel8f842d32009-10-16 18:45:49 +00004149
Chris Lattner3822f632009-01-02 08:05:26 +00004150 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004151 ParseValue(Ty, Op0, PFS) ||
4152 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004153 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004154 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4155 return true;
4156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004157
Chris Lattnerac161bf2009-01-02 07:01:27 +00004158 if (!Ty->isFirstClassType())
4159 return Error(TypeLoc, "phi node must have first class type");
4160
Jay Foad52131342011-03-30 11:28:46 +00004161 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004162 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4163 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4164 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004165 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004166}
4167
Bill Wendlingfae14752011-08-12 20:24:12 +00004168/// ParseLandingPad
4169/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4170/// Clause
4171/// ::= 'catch' TypeAndValue
4172/// ::= 'filter'
4173/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4174bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004175 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004176 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004177
4178 if (ParseType(Ty, TyLoc) ||
4179 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4180 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4181 return true;
4182
4183 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4184 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4185
4186 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4187 LandingPadInst::ClauseType CT;
4188 if (EatIfPresent(lltok::kw_catch))
4189 CT = LandingPadInst::Catch;
4190 else if (EatIfPresent(lltok::kw_filter))
4191 CT = LandingPadInst::Filter;
4192 else
4193 return TokError("expected 'catch' or 'filter' clause type");
4194
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004195 Value *V;
4196 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004197 if (ParseTypeAndValue(V, VLoc, PFS)) {
4198 delete LP;
4199 return true;
4200 }
4201
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004202 // A 'catch' type expects a non-array constant. A filter clause expects an
4203 // array constant.
4204 if (CT == LandingPadInst::Catch) {
4205 if (isa<ArrayType>(V->getType()))
4206 Error(VLoc, "'catch' clause has an invalid type");
4207 } else {
4208 if (!isa<ArrayType>(V->getType()))
4209 Error(VLoc, "'filter' clause has an invalid type");
4210 }
4211
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004212 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004213 }
4214
4215 Inst = LP;
4216 return false;
4217}
4218
Chris Lattnerac161bf2009-01-02 07:01:27 +00004219/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004220/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4221/// ParameterList OptionalAttrs
4222/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4223/// ParameterList OptionalAttrs
4224/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004225/// ParameterList OptionalAttrs
4226bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004227 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004228 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004229 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004230 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004231 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004232 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004233 LocTy RetTypeLoc;
4234 ValID CalleeID;
4235 SmallVector<ParamInfo, 16> ArgList;
4236 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004237
Reid Kleckner5772b772014-04-24 20:14:34 +00004238 if ((TCK != CallInst::TCK_None &&
4239 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004240 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004241 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004242 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004243 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004244 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4245 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004246 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004247 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004248 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004249
Chris Lattnerac161bf2009-01-02 07:01:27 +00004250 // If RetType is a non-function pointer type, then this is the short syntax
4251 // for the call, which means that RetType is just the return type. Infer the
4252 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004253 PointerType *PFTy = nullptr;
4254 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004255 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4256 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4257 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004258 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004259 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4260 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004261
Chris Lattnerac161bf2009-01-02 07:01:27 +00004262 if (!FunctionType::isValidReturnType(RetType))
4263 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004264
Owen Anderson4056ca92009-07-29 22:17:13 +00004265 Ty = FunctionType::get(RetType, ParamTypes, false);
4266 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004267 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004268
Chris Lattnerac161bf2009-01-02 07:01:27 +00004269 // Look up the callee.
4270 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004271 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004272
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004273 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004274 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004275 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004276 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4277 AttributeSet::ReturnIndex,
4278 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004279
Chris Lattnerac161bf2009-01-02 07:01:27 +00004280 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004281
Chris Lattnerac161bf2009-01-02 07:01:27 +00004282 // Loop through FunctionType's arguments and ensure they are specified
4283 // correctly. Also, gather any parameter attributes.
4284 FunctionType::param_iterator I = Ty->param_begin();
4285 FunctionType::param_iterator E = Ty->param_end();
4286 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004287 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004288 if (I != E) {
4289 ExpectedTy = *I++;
4290 } else if (!Ty->isVarArg()) {
4291 return Error(ArgList[i].Loc, "too many arguments specified");
4292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004293
Chris Lattnerac161bf2009-01-02 07:01:27 +00004294 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4295 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004296 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004297 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004298 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4299 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004300 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4301 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004302 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004303
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304 if (I != E)
4305 return Error(CallLoc, "not enough parameters specified for call");
4306
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004307 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004308 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4309 AttributeSet::FunctionIndex,
4310 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004311
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004312 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004313 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004314
Jay Foad5bd375a2011-07-15 08:37:34 +00004315 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004316 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004317 CI->setCallingConv(CC);
4318 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004319 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004320 Inst = CI;
4321 return false;
4322}
4323
4324//===----------------------------------------------------------------------===//
4325// Memory Instructions.
4326//===----------------------------------------------------------------------===//
4327
4328/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004329/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004330int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004331 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004332 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004333 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004334 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004335
4336 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4337
Chris Lattner3822f632009-01-02 08:05:26 +00004338 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004339
Chris Lattnerb2f39502009-12-30 05:44:30 +00004340 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004341 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004342 if (Lex.getKind() == lltok::kw_align) {
4343 if (ParseOptionalAlignment(Alignment)) return true;
4344 } else if (Lex.getKind() == lltok::MetadataVar) {
4345 AteExtraComma = true;
4346 } else {
4347 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4348 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4349 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 }
4351 }
4352
Dan Gohman2140a742010-05-28 01:14:11 +00004353 if (Size && !Size->getType()->isIntegerTy())
4354 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355
Reid Kleckner436c42e2014-01-17 23:58:17 +00004356 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4357 AI->setUsedWithInAlloca(IsInAlloca);
4358 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004359 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004360}
4361
4362/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004363/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004364/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004365/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004366int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004367 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004368 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004369 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004370 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004371 AtomicOrdering Ordering = NotAtomic;
4372 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004373
4374 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004375 isAtomic = true;
4376 Lex.Lex();
4377 }
4378
Chris Lattnerbc639292011-11-27 06:56:53 +00004379 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004380 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004381 isVolatile = true;
4382 Lex.Lex();
4383 }
4384
Chris Lattnerb2f39502009-12-30 05:44:30 +00004385 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004386 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004387 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4388 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004389
Duncan Sands19d0b472010-02-16 11:11:14 +00004390 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004391 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4392 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004393 if (isAtomic && !Alignment)
4394 return Error(Loc, "atomic load must have explicit non-zero alignment");
4395 if (Ordering == Release || Ordering == AcquireRelease)
4396 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004397
Eli Friedman59b66882011-08-09 23:02:53 +00004398 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004399 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004400}
4401
4402/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004403
4404/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4405/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004406/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004407int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004409 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004410 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004411 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004412 AtomicOrdering Ordering = NotAtomic;
4413 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004414
4415 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004416 isAtomic = true;
4417 Lex.Lex();
4418 }
4419
Chris Lattnerbc639292011-11-27 06:56:53 +00004420 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004421 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004422 isVolatile = true;
4423 Lex.Lex();
4424 }
4425
Chris Lattnerac161bf2009-01-02 07:01:27 +00004426 if (ParseTypeAndValue(Val, Loc, PFS) ||
4427 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004428 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004429 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004430 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004431 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004432
Duncan Sands19d0b472010-02-16 11:11:14 +00004433 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004434 return Error(PtrLoc, "store operand must be a pointer");
4435 if (!Val->getType()->isFirstClassType())
4436 return Error(Loc, "store operand must be a first class value");
4437 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4438 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004439 if (isAtomic && !Alignment)
4440 return Error(Loc, "atomic store must have explicit non-zero alignment");
4441 if (Ordering == Acquire || Ordering == AcquireRelease)
4442 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004443
Eli Friedman59b66882011-08-09 23:02:53 +00004444 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004445 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004446}
4447
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004448/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004449/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4450/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004451int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004452 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4453 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004454 AtomicOrdering SuccessOrdering = NotAtomic;
4455 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004456 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004457 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004458 bool isWeak = false;
4459
4460 if (EatIfPresent(lltok::kw_weak))
4461 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004462
4463 if (EatIfPresent(lltok::kw_volatile))
4464 isVolatile = true;
4465
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004466 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4467 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4468 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4469 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4470 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004471 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4472 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004473 return true;
4474
Tim Northovere94a5182014-03-11 10:48:52 +00004475 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004476 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004477 if (SuccessOrdering < FailureOrdering)
4478 return TokError("cmpxchg must be at least as ordered on success as failure");
4479 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4480 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004481 if (!Ptr->getType()->isPointerTy())
4482 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4483 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4484 return Error(CmpLoc, "compare value and pointer type do not match");
4485 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4486 return Error(NewLoc, "new value and pointer type do not match");
4487 if (!New->getType()->isIntegerTy())
4488 return Error(NewLoc, "cmpxchg operand must be an integer");
4489 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4490 if (Size < 8 || (Size & (Size - 1)))
4491 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4492 " integer");
4493
Tim Northover420a2162014-06-13 14:24:07 +00004494 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4495 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004496 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004497 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004498 Inst = CXI;
4499 return AteExtraComma ? InstExtraComma : InstNormal;
4500}
4501
4502/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004503/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4504/// 'singlethread'? AtomicOrdering
4505int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004506 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4507 bool AteExtraComma = false;
4508 AtomicOrdering Ordering = NotAtomic;
4509 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004510 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004511 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004512
4513 if (EatIfPresent(lltok::kw_volatile))
4514 isVolatile = true;
4515
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004516 switch (Lex.getKind()) {
4517 default: return TokError("expected binary operation in atomicrmw");
4518 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4519 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4520 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4521 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4522 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4523 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4524 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4525 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4526 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4527 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4528 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4529 }
4530 Lex.Lex(); // Eat the operation.
4531
4532 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4533 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4534 ParseTypeAndValue(Val, ValLoc, PFS) ||
4535 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4536 return true;
4537
4538 if (Ordering == Unordered)
4539 return TokError("atomicrmw cannot be unordered");
4540 if (!Ptr->getType()->isPointerTy())
4541 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4542 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4543 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4544 if (!Val->getType()->isIntegerTy())
4545 return Error(ValLoc, "atomicrmw operand must be an integer");
4546 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4547 if (Size < 8 || (Size & (Size - 1)))
4548 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4549 " integer");
4550
4551 AtomicRMWInst *RMWI =
4552 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4553 RMWI->setVolatile(isVolatile);
4554 Inst = RMWI;
4555 return AteExtraComma ? InstExtraComma : InstNormal;
4556}
4557
Eli Friedmanfee02c62011-07-25 23:16:38 +00004558/// ParseFence
4559/// ::= 'fence' 'singlethread'? AtomicOrdering
4560int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4561 AtomicOrdering Ordering = NotAtomic;
4562 SynchronizationScope Scope = CrossThread;
4563 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4564 return true;
4565
4566 if (Ordering == Unordered)
4567 return TokError("fence cannot be unordered");
4568 if (Ordering == Monotonic)
4569 return TokError("fence cannot be monotonic");
4570
4571 Inst = new FenceInst(Context, Ordering, Scope);
4572 return InstNormal;
4573}
4574
Chris Lattnerac161bf2009-01-02 07:01:27 +00004575/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004576/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004577int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004578 Value *Ptr = nullptr;
4579 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004580 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004581
Dan Gohman16cbbe42009-07-29 15:58:36 +00004582 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004583
Chris Lattner3822f632009-01-02 08:05:26 +00004584 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004585
Eli Benderskyd9806682013-04-22 17:03:42 +00004586 Type *BaseType = Ptr->getType();
4587 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4588 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004589 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004590
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004592 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004593 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004594 if (Lex.getKind() == lltok::MetadataVar) {
4595 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004596 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004597 }
Chris Lattner3822f632009-01-02 08:05:26 +00004598 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004599 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004601 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4602 return Error(EltLoc, "getelementptr index type missmatch");
4603 if (Val->getType()->isVectorTy()) {
4604 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4605 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4606 if (ValNumEl != PtrNumEl)
4607 return Error(EltLoc,
4608 "getelementptr vector index has a wrong number of elements");
4609 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004610 Indices.push_back(Val);
4611 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004612
Eli Benderskyd9806682013-04-22 17:03:42 +00004613 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4614 return Error(Loc, "base element of getelementptr must be sized");
4615
4616 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004617 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004618 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004619 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004620 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004621 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622}
4623
4624/// ParseExtractValue
4625/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004626int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 Value *Val; LocTy Loc;
4628 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004629 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004631 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632 return true;
4633
Chris Lattner392be582010-02-12 20:49:41 +00004634 if (!Val->getType()->isAggregateType())
4635 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636
Jay Foad57aa6362011-07-13 10:26:04 +00004637 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004638 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004639 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004640 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004641}
4642
4643/// ParseInsertValue
4644/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004645int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646 Value *Val0, *Val1; LocTy Loc0, Loc1;
4647 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004648 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4650 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4651 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004652 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004653 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004654
Chris Lattner392be582010-02-12 20:49:41 +00004655 if (!Val0->getType()->isAggregateType())
4656 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004657
Jay Foad57aa6362011-07-13 10:26:04 +00004658 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004660 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004661 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004662}
Nick Lewycky49f89192009-04-04 07:22:01 +00004663
4664//===----------------------------------------------------------------------===//
4665// Embedded metadata.
4666//===----------------------------------------------------------------------===//
4667
4668/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004669/// ::= Element (',' Element)*
4670/// Element
4671/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004672bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004673 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004674 // Check for an empty list.
4675 if (Lex.getKind() == lltok::rbrace)
4676 return false;
4677
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004678 bool IsLocal = false;
Nick Lewycky49f89192009-04-04 07:22:01 +00004679 do {
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004680 if (IsLocal)
4681 return TokError("unexpected operand after function-local metadata");
4682
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004683 // Null is a special case since it is typeless.
4684 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004685 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004686 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004687 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004688
Craig Topper2617dcc2014-04-15 06:32:26 +00004689 Value *V = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004690 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004691 Elts.push_back(V);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004692
4693 if (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())
4694 return TokError("unexpected nested function-local metadata");
4695 if (!V->getType()->isMetadataTy() && !isa<Constant>(V)) {
4696 assert(PFS && "Unexpected function-local metadata without PFS");
4697 if (Elts.size() > 1)
4698 return TokError("unexpected function-local metadata");
4699 IsLocal = true;
4700 }
Nick Lewycky49f89192009-04-04 07:22:01 +00004701 } while (EatIfPresent(lltok::comma));
4702
4703 return false;
4704}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004705
4706//===----------------------------------------------------------------------===//
4707// Use-list order directives.
4708//===----------------------------------------------------------------------===//
4709bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4710 SMLoc Loc) {
4711 if (V->use_empty())
4712 return Error(Loc, "value has no uses");
4713
4714 unsigned NumUses = 0;
4715 SmallDenseMap<const Use *, unsigned, 16> Order;
4716 for (const Use &U : V->uses()) {
4717 if (++NumUses > Indexes.size())
4718 break;
4719 Order[&U] = Indexes[NumUses - 1];
4720 }
4721 if (NumUses < 2)
4722 return Error(Loc, "value only has one use");
4723 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4724 return Error(Loc, "wrong number of indexes, expected " +
4725 Twine(std::distance(V->use_begin(), V->use_end())));
4726
4727 V->sortUseList([&](const Use &L, const Use &R) {
4728 return Order.lookup(&L) < Order.lookup(&R);
4729 });
4730 return false;
4731}
4732
4733/// ParseUseListOrderIndexes
4734/// ::= '{' uint32 (',' uint32)+ '}'
4735bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4736 SMLoc Loc = Lex.getLoc();
4737 if (ParseToken(lltok::lbrace, "expected '{' here"))
4738 return true;
4739 if (Lex.getKind() == lltok::rbrace)
4740 return Lex.Error("expected non-empty list of uselistorder indexes");
4741
4742 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4743 // indexes should be distinct numbers in the range [0, size-1], and should
4744 // not be in order.
4745 unsigned Offset = 0;
4746 unsigned Max = 0;
4747 bool IsOrdered = true;
4748 assert(Indexes.empty() && "Expected empty order vector");
4749 do {
4750 unsigned Index;
4751 if (ParseUInt32(Index))
4752 return true;
4753
4754 // Update consistency checks.
4755 Offset += Index - Indexes.size();
4756 Max = std::max(Max, Index);
4757 IsOrdered &= Index == Indexes.size();
4758
4759 Indexes.push_back(Index);
4760 } while (EatIfPresent(lltok::comma));
4761
4762 if (ParseToken(lltok::rbrace, "expected '}' here"))
4763 return true;
4764
4765 if (Indexes.size() < 2)
4766 return Error(Loc, "expected >= 2 uselistorder indexes");
4767 if (Offset != 0 || Max >= Indexes.size())
4768 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4769 if (IsOrdered)
4770 return Error(Loc, "expected uselistorder indexes to change the order");
4771
4772 return false;
4773}
4774
4775/// ParseUseListOrder
4776/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4777bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4778 SMLoc Loc = Lex.getLoc();
4779 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4780 return true;
4781
4782 Value *V;
4783 SmallVector<unsigned, 16> Indexes;
4784 if (ParseTypeAndValue(V, PFS) ||
4785 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4786 ParseUseListOrderIndexes(Indexes))
4787 return true;
4788
4789 return sortUseListOrder(V, Indexes, Loc);
4790}
4791
4792/// ParseUseListOrderBB
4793/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4794bool LLParser::ParseUseListOrderBB() {
4795 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4796 SMLoc Loc = Lex.getLoc();
4797 Lex.Lex();
4798
4799 ValID Fn, Label;
4800 SmallVector<unsigned, 16> Indexes;
4801 if (ParseValID(Fn) ||
4802 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4803 ParseValID(Label) ||
4804 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4805 ParseUseListOrderIndexes(Indexes))
4806 return true;
4807
4808 // Check the function.
4809 GlobalValue *GV;
4810 if (Fn.Kind == ValID::t_GlobalName)
4811 GV = M->getNamedValue(Fn.StrVal);
4812 else if (Fn.Kind == ValID::t_GlobalID)
4813 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4814 else
4815 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4816 if (!GV)
4817 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4818 auto *F = dyn_cast<Function>(GV);
4819 if (!F)
4820 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4821 if (F->isDeclaration())
4822 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4823
4824 // Check the basic block.
4825 if (Label.Kind == ValID::t_LocalID)
4826 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4827 if (Label.Kind != ValID::t_LocalName)
4828 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4829 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4830 if (!V)
4831 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4832 if (!isa<BasicBlock>(V))
4833 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4834
4835 return sortUseListOrder(V, Indexes, Loc);
4836}