blob: e1c00cc4af0e9626e04b498b1535954f865a1db1 [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
Craig Topper2617dcc2014-04-15 06:32:26 +0000790 GlobalVariable *GV = 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()) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000794 if (GlobalValue *GVal = M->getNamedValue(Name)) {
795 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
796 return Error(NameLoc, "redefinition of global '@" + Name + "'");
797 GV = cast<GlobalVariable>(GVal);
798 }
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()) {
803 GV = cast<GlobalVariable>(I->second.first);
804 ForwardRefValIDs.erase(I);
805 }
806 }
807
Craig Topper2617dcc2014-04-15 06:32:26 +0000808 if (!GV) {
809 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
810 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000811 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 } else {
813 if (GV->getType()->getElementType() != Ty)
814 return Error(TyLoc,
815 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 // Move the forward-reference to the correct spot in the module.
818 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
819 }
820
821 if (Name.empty())
822 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000823
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 // Set the parsed properties on the global.
825 if (Init)
826 GV->setInitializer(Init);
827 GV->setConstant(IsConstant);
828 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
829 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000830 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000831 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000832 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000833 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000834
Chris Lattnerac161bf2009-01-02 07:01:27 +0000835 // Parse attributes on the global.
836 while (Lex.getKind() == lltok::comma) {
837 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000838
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839 if (Lex.getKind() == lltok::kw_section) {
840 Lex.Lex();
841 GV->setSection(Lex.getStrVal());
842 if (ParseToken(lltok::StringConstant, "expected global section string"))
843 return true;
844 } else if (Lex.getKind() == lltok::kw_align) {
845 unsigned Alignment;
846 if (ParseOptionalAlignment(Alignment)) return true;
847 GV->setAlignment(Alignment);
848 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000849 Comdat *C;
850 if (parseOptionalComdat(C))
851 return true;
852 if (C)
853 GV->setComdat(C);
854 else
855 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 }
857 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000858
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 return false;
860}
861
Bill Wendling63b88192013-02-06 06:52:58 +0000862/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000863/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000864bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000865 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000866 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000867 Lex.Lex();
868
869 assert(Lex.getKind() == lltok::AttrGrpID);
Bill Wendling63b88192013-02-06 06:52:58 +0000870 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000871 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000872 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000873 Lex.Lex();
874
875 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000876 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000877 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000878 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000879 ParseToken(lltok::rbrace, "expected end of attribute group"))
880 return true;
881
Bill Wendlingb32b0412013-02-08 06:32:06 +0000882 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000883 return Error(AttrGrpLoc, "attribute group has no attributes");
884
885 return false;
886}
887
Bill Wendling8b0321d2013-02-08 00:52:31 +0000888/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000889/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000890bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
891 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000892 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000893 bool HaveError = false;
894
895 B.clear();
896
Bill Wendling63b88192013-02-06 06:52:58 +0000897 while (true) {
898 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000899 if (Token == lltok::kw_builtin)
900 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000901 switch (Token) {
902 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000903 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000904 return Error(Lex.getLoc(), "unterminated attribute group");
905 case lltok::rbrace:
906 // Finished.
907 return false;
908
Bill Wendlingb32b0412013-02-08 06:32:06 +0000909 case lltok::AttrGrpID: {
910 // Allow a function to reference an attribute group:
911 //
912 // define void @foo() #1 { ... }
913 if (inAttrGrp)
914 HaveError |=
915 Error(Lex.getLoc(),
916 "cannot have an attribute group reference in an attribute group");
917
918 unsigned AttrGrpNum = Lex.getUIntVal();
919 if (inAttrGrp) break;
920
921 // Save the reference to the attribute group. We'll fill it in later.
922 FwdRefAttrGrps.push_back(AttrGrpNum);
923 break;
924 }
Bill Wendling63b88192013-02-06 06:52:58 +0000925 // Target-dependent attributes:
926 case lltok::StringConstant: {
927 std::string Attr = Lex.getStrVal();
928 Lex.Lex();
929 std::string Val;
930 if (EatIfPresent(lltok::equal) &&
931 ParseStringConstant(Val))
932 return true;
933
934 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000935 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000936 }
937
938 // Target-independent attributes:
939 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000940 // As a hack, we allow function alignment to be initially parsed as an
941 // attribute on a function declaration/definition or added to an attribute
942 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000943 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000944 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000945 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000946 if (ParseToken(lltok::equal, "expected '=' here") ||
947 ParseUInt32(Alignment))
948 return true;
949 } else {
950 if (ParseOptionalAlignment(Alignment))
951 return true;
952 }
Bill Wendling63b88192013-02-06 06:52:58 +0000953 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000954 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000955 }
956 case lltok::kw_alignstack: {
957 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000958 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000959 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000960 if (ParseToken(lltok::equal, "expected '=' here") ||
961 ParseUInt32(Alignment))
962 return true;
963 } else {
964 if (ParseOptionalStackAlignment(Alignment))
965 return true;
966 }
Bill Wendling63b88192013-02-06 06:52:58 +0000967 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000968 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000969 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000970 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000971 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000972 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000973 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000974 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000975 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
976 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
977 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
978 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
979 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
980 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
981 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
982 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
983 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
984 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000985 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000986 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
987 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
988 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
989 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
990 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
991 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
992 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
993 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
994 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
995 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
996 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000997
998 // Error handling.
999 case lltok::kw_inreg:
1000 case lltok::kw_signext:
1001 case lltok::kw_zeroext:
1002 HaveError |=
1003 Error(Lex.getLoc(),
1004 "invalid use of attribute on a function");
1005 break;
1006 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001007 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +00001008 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001009 case lltok::kw_nest:
1010 case lltok::kw_noalias:
1011 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001012 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001013 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001014 case lltok::kw_sret:
1015 HaveError |=
1016 Error(Lex.getLoc(),
1017 "invalid use of parameter-only attribute on a function");
1018 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001019 }
1020
1021 Lex.Lex();
1022 }
1023}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001024
1025//===----------------------------------------------------------------------===//
1026// GlobalValue Reference/Resolution Routines.
1027//===----------------------------------------------------------------------===//
1028
1029/// GetGlobalVal - Get a value with the specified name or ID, creating a
1030/// forward reference record if needed. This can return null if the value
1031/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001032GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001033 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001034 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001035 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001036 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001037 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001039
Chris Lattnerac161bf2009-01-02 07:01:27 +00001040 // Look this name up in the normal function symbol table.
1041 GlobalValue *Val =
1042 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001043
Chris Lattnerac161bf2009-01-02 07:01:27 +00001044 // If this is a forward reference for the value, see if we already created a
1045 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001046 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001047 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1048 I = ForwardRefVals.find(Name);
1049 if (I != ForwardRefVals.end())
1050 Val = I->second.first;
1051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001052
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 // If we have the value in the symbol table or fwd-ref table, return it.
1054 if (Val) {
1055 if (Val->getType() == Ty) return Val;
1056 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001057 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001058 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060
Chris Lattnerac161bf2009-01-02 07:01:27 +00001061 // Otherwise, create a new forward reference for this value and remember it.
1062 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001063 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001064 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001065 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001066 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001067 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1068 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001069 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001070
Chris Lattnerac161bf2009-01-02 07:01:27 +00001071 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1072 return FwdVal;
1073}
1074
Chris Lattner229907c2011-07-18 04:54:35 +00001075GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1076 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001077 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001079 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001081
Craig Topper2617dcc2014-04-15 06:32:26 +00001082 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001083
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 // If this is a forward reference for the value, see if we already created a
1085 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001086 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001087 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1088 I = ForwardRefValIDs.find(ID);
1089 if (I != ForwardRefValIDs.end())
1090 Val = I->second.first;
1091 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001092
Chris Lattnerac161bf2009-01-02 07:01:27 +00001093 // If we have the value in the symbol table or fwd-ref table, return it.
1094 if (Val) {
1095 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001096 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001097 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001098 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001100
Chris Lattnerac161bf2009-01-02 07:01:27 +00001101 // Otherwise, create a new forward reference for this value and remember it.
1102 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001103 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001104 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001105 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001106 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001107 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001108
Chris Lattnerac161bf2009-01-02 07:01:27 +00001109 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1110 return FwdVal;
1111}
1112
1113
1114//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001115// Comdat Reference/Resolution Routines.
1116//===----------------------------------------------------------------------===//
1117
1118Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1119 // Look this name up in the comdat symbol table.
1120 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1121 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1122 if (I != ComdatSymTab.end())
1123 return &I->second;
1124
1125 // Otherwise, create a new forward reference for this value and remember it.
1126 Comdat *C = M->getOrInsertComdat(Name);
1127 ForwardRefComdats[Name] = Loc;
1128 return C;
1129}
1130
1131
1132//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001133// Helper Routines.
1134//===----------------------------------------------------------------------===//
1135
1136/// ParseToken - If the current token has the specified kind, eat it and return
1137/// success. Otherwise, emit the specified error and return failure.
1138bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1139 if (Lex.getKind() != T)
1140 return TokError(ErrMsg);
1141 Lex.Lex();
1142 return false;
1143}
1144
Chris Lattner3822f632009-01-02 08:05:26 +00001145/// ParseStringConstant
1146/// ::= StringConstant
1147bool LLParser::ParseStringConstant(std::string &Result) {
1148 if (Lex.getKind() != lltok::StringConstant)
1149 return TokError("expected string constant");
1150 Result = Lex.getStrVal();
1151 Lex.Lex();
1152 return false;
1153}
1154
1155/// ParseUInt32
1156/// ::= uint32
1157bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1159 return TokError("expected integer");
1160 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1161 if (Val64 != unsigned(Val64))
1162 return TokError("expected 32-bit integer (too large)");
1163 Val = Val64;
1164 Lex.Lex();
1165 return false;
1166}
1167
Hal Finkelb0407ba2014-07-18 15:51:28 +00001168/// ParseUInt64
1169/// ::= uint64
1170bool LLParser::ParseUInt64(uint64_t &Val) {
1171 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1172 return TokError("expected integer");
1173 Val = Lex.getAPSIntVal().getLimitedValue();
1174 Lex.Lex();
1175 return false;
1176}
1177
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001178/// ParseTLSModel
1179/// := 'localdynamic'
1180/// := 'initialexec'
1181/// := 'localexec'
1182bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1183 switch (Lex.getKind()) {
1184 default:
1185 return TokError("expected localdynamic, initialexec or localexec");
1186 case lltok::kw_localdynamic:
1187 TLM = GlobalVariable::LocalDynamicTLSModel;
1188 break;
1189 case lltok::kw_initialexec:
1190 TLM = GlobalVariable::InitialExecTLSModel;
1191 break;
1192 case lltok::kw_localexec:
1193 TLM = GlobalVariable::LocalExecTLSModel;
1194 break;
1195 }
1196
1197 Lex.Lex();
1198 return false;
1199}
1200
1201/// ParseOptionalThreadLocal
1202/// := /*empty*/
1203/// := 'thread_local'
1204/// := 'thread_local' '(' tlsmodel ')'
1205bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1206 TLM = GlobalVariable::NotThreadLocal;
1207 if (!EatIfPresent(lltok::kw_thread_local))
1208 return false;
1209
1210 TLM = GlobalVariable::GeneralDynamicTLSModel;
1211 if (Lex.getKind() == lltok::lparen) {
1212 Lex.Lex();
1213 return ParseTLSModel(TLM) ||
1214 ParseToken(lltok::rparen, "expected ')' after thread local model");
1215 }
1216 return false;
1217}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218
1219/// ParseOptionalAddrSpace
1220/// := /*empty*/
1221/// := 'addrspace' '(' uint32 ')'
1222bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1223 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001224 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001227 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001229}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001230
Bill Wendling34c2eb22012-12-04 23:40:58 +00001231/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1232bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1233 bool HaveError = false;
1234
1235 B.clear();
1236
1237 while (1) {
1238 lltok::Kind Token = Lex.getKind();
1239 switch (Token) {
1240 default: // End of attributes.
1241 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001242 case lltok::kw_align: {
1243 unsigned Alignment;
1244 if (ParseOptionalAlignment(Alignment))
1245 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001246 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001247 continue;
1248 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001249 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001250 case lltok::kw_dereferenceable: {
1251 uint64_t Bytes;
1252 if (ParseOptionalDereferenceableBytes(Bytes))
1253 return true;
1254 B.addDereferenceableAttr(Bytes);
1255 continue;
1256 }
Reid Klecknera534a382013-12-19 02:14:12 +00001257 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001258 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1259 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1260 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1261 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001262 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001263 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1264 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001265 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001266 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1267 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1268 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001269
Stephen Lin7577ed52013-04-20 13:16:13 +00001270 case lltok::kw_alignstack:
1271 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001272 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001273 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001274 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001275 case lltok::kw_minsize:
1276 case lltok::kw_naked:
1277 case lltok::kw_nobuiltin:
1278 case lltok::kw_noduplicate:
1279 case lltok::kw_noimplicitfloat:
1280 case lltok::kw_noinline:
1281 case lltok::kw_nonlazybind:
1282 case lltok::kw_noredzone:
1283 case lltok::kw_noreturn:
1284 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001285 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001286 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001287 case lltok::kw_returns_twice:
1288 case lltok::kw_sanitize_address:
1289 case lltok::kw_sanitize_memory:
1290 case lltok::kw_sanitize_thread:
1291 case lltok::kw_ssp:
1292 case lltok::kw_sspreq:
1293 case lltok::kw_sspstrong:
1294 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001295 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1296 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001297 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001298
Bill Wendling34c2eb22012-12-04 23:40:58 +00001299 Lex.Lex();
1300 }
1301}
1302
1303/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1304bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1305 bool HaveError = false;
1306
1307 B.clear();
1308
1309 while (1) {
1310 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001311 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001312 default: // End of attributes.
1313 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001314 case lltok::kw_dereferenceable: {
1315 uint64_t Bytes;
1316 if (ParseOptionalDereferenceableBytes(Bytes))
1317 return true;
1318 B.addDereferenceableAttr(Bytes);
1319 continue;
1320 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001321 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1322 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001323 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001324 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1325 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001326
Bill Wendling34c2eb22012-12-04 23:40:58 +00001327 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001328 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001329 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001330 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001331 case lltok::kw_nest:
1332 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001333 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001334 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001335 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001336 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001337
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001338 case lltok::kw_alignstack:
1339 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001340 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001341 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001342 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001343 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001344 case lltok::kw_minsize:
1345 case lltok::kw_naked:
1346 case lltok::kw_nobuiltin:
1347 case lltok::kw_noduplicate:
1348 case lltok::kw_noimplicitfloat:
1349 case lltok::kw_noinline:
1350 case lltok::kw_nonlazybind:
1351 case lltok::kw_noredzone:
1352 case lltok::kw_noreturn:
1353 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001354 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001355 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001356 case lltok::kw_returns_twice:
1357 case lltok::kw_sanitize_address:
1358 case lltok::kw_sanitize_memory:
1359 case lltok::kw_sanitize_thread:
1360 case lltok::kw_ssp:
1361 case lltok::kw_sspreq:
1362 case lltok::kw_sspstrong:
1363 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001364 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001365 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001366
1367 case lltok::kw_readnone:
1368 case lltok::kw_readonly:
1369 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001370 }
1371
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372 Lex.Lex();
1373 }
1374}
1375
1376/// ParseOptionalLinkage
1377/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001378/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001379/// ::= 'internal'
1380/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001381/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001383/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001384/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001386/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001387/// ::= 'extern_weak'
1388/// ::= 'external'
1389bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1390 HasLinkage = false;
1391 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001392 default: Res=GlobalValue::ExternalLinkage; return false;
1393 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001394 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1395 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1396 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1397 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1398 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001399 case lltok::kw_available_externally:
1400 Res = GlobalValue::AvailableExternallyLinkage;
1401 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001402 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001403 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001404 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1405 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001406 }
1407 Lex.Lex();
1408 HasLinkage = true;
1409 return false;
1410}
1411
1412/// ParseOptionalVisibility
1413/// ::= /*empty*/
1414/// ::= 'default'
1415/// ::= 'hidden'
1416/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001417///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001418bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1419 switch (Lex.getKind()) {
1420 default: Res = GlobalValue::DefaultVisibility; return false;
1421 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1422 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1423 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1424 }
1425 Lex.Lex();
1426 return false;
1427}
1428
Nico Rieck7157bb72014-01-14 15:22:47 +00001429/// ParseOptionalDLLStorageClass
1430/// ::= /*empty*/
1431/// ::= 'dllimport'
1432/// ::= 'dllexport'
1433///
1434bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1435 switch (Lex.getKind()) {
1436 default: Res = GlobalValue::DefaultStorageClass; return false;
1437 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1438 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1439 }
1440 Lex.Lex();
1441 return false;
1442}
1443
Chris Lattnerac161bf2009-01-02 07:01:27 +00001444/// ParseOptionalCallingConv
1445/// ::= /*empty*/
1446/// ::= 'ccc'
1447/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001448/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001449/// ::= 'coldcc'
1450/// ::= 'x86_stdcallcc'
1451/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001452/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001453/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001454/// ::= 'arm_apcscc'
1455/// ::= 'arm_aapcscc'
1456/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001457/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001458/// ::= 'ptx_kernel'
1459/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001460/// ::= 'spir_func'
1461/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001462/// ::= 'x86_64_sysvcc'
1463/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001464/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001465/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001466/// ::= 'preserve_mostcc'
1467/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001468/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001469/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001470///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001471bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001472 switch (Lex.getKind()) {
1473 default: CC = CallingConv::C; return false;
1474 case lltok::kw_ccc: CC = CallingConv::C; break;
1475 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1476 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1477 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1478 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001479 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001480 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001481 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1482 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1483 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001484 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001485 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1486 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001487 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1488 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001489 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001490 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1491 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001492 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001493 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001494 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1495 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001496 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001497 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001498 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001499 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001500 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001501 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001502
Chris Lattnerac161bf2009-01-02 07:01:27 +00001503 Lex.Lex();
1504 return false;
1505}
1506
Chris Lattner5c427632009-12-30 05:31:19 +00001507/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001508/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001509bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1510 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001511 do {
1512 if (Lex.getKind() != lltok::MetadataVar)
1513 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001514
Chris Lattner596760d2009-12-29 21:25:40 +00001515 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001516 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001517 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001518
Chris Lattner1797fc72009-12-29 21:53:55 +00001519 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001520 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001521
1522 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001523 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001524
Dan Gohmanf0715b12010-08-24 14:35:45 +00001525 // This code is similar to that of ParseMetadataValue, however it needs to
1526 // have special-case code for a forward reference; see the comments on
1527 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1528 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001529 if (Lex.getKind() == lltok::lbrace) {
1530 ValID ID;
1531 if (ParseMetadataListValue(ID, PFS))
1532 return true;
1533 assert(ID.Kind == ValID::t_MDNode);
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00001534 if (ID.MDNodeVal->isFunctionLocal())
Duncan P. N. Exon Smith545a9b02014-12-07 17:56:16 +00001535 return Error(Loc, "unexpected function-local metadata");
Dan Gohmanc828c542010-08-24 02:24:03 +00001536 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001537 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001538 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001539 if (ParseMDNodeID(Node, NodeID))
1540 return true;
1541 if (Node) {
1542 // If we got the node, add it to the instruction.
1543 Inst->setMetadata(MDK, Node);
1544 } else {
1545 MDRef R = { Loc, MDK, NodeID };
1546 // Otherwise, remember that this should be resolved later.
1547 ForwardRefInstMetadata[Inst].push_back(R);
1548 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001549 }
Chris Lattner596760d2009-12-29 21:25:40 +00001550
Manman Ren209b17c2013-09-28 00:22:27 +00001551 if (MDK == LLVMContext::MD_tbaa)
1552 InstsWithTBAATag.push_back(Inst);
1553
Chris Lattner596760d2009-12-29 21:25:40 +00001554 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001555 } while (EatIfPresent(lltok::comma));
1556 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001557}
1558
Chris Lattnerac161bf2009-01-02 07:01:27 +00001559/// ParseOptionalAlignment
1560/// ::= /* empty */
1561/// ::= 'align' 4
1562bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1563 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001564 if (!EatIfPresent(lltok::kw_align))
1565 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001566 LocTy AlignLoc = Lex.getLoc();
1567 if (ParseUInt32(Alignment)) return true;
1568 if (!isPowerOf2_32(Alignment))
1569 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001570 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001571 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001572 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573}
1574
Hal Finkelb0407ba2014-07-18 15:51:28 +00001575/// ParseOptionalDereferenceableBytes
1576/// ::= /* empty */
1577/// ::= 'dereferenceable' '(' 4 ')'
1578bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1579 Bytes = 0;
1580 if (!EatIfPresent(lltok::kw_dereferenceable))
1581 return false;
1582 LocTy ParenLoc = Lex.getLoc();
1583 if (!EatIfPresent(lltok::lparen))
1584 return Error(ParenLoc, "expected '('");
1585 LocTy DerefLoc = Lex.getLoc();
1586 if (ParseUInt64(Bytes)) return true;
1587 ParenLoc = Lex.getLoc();
1588 if (!EatIfPresent(lltok::rparen))
1589 return Error(ParenLoc, "expected ')'");
1590 if (!Bytes)
1591 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1592 return false;
1593}
1594
Chris Lattnerb2f39502009-12-30 05:44:30 +00001595/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001596/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001597/// ::= ',' align 4
1598///
1599/// This returns with AteExtraComma set to true if it ate an excess comma at the
1600/// end.
1601bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1602 bool &AteExtraComma) {
1603 AteExtraComma = false;
1604 while (EatIfPresent(lltok::comma)) {
1605 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001606 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001607 AteExtraComma = true;
1608 return false;
1609 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001610
Chris Lattner95b0ff42010-04-23 00:50:50 +00001611 if (Lex.getKind() != lltok::kw_align)
1612 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001613
Chris Lattner95b0ff42010-04-23 00:50:50 +00001614 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001615 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001616
Devang Patelea8a4b92009-09-17 23:04:48 +00001617 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001618}
1619
Eli Friedmanfee02c62011-07-25 23:16:38 +00001620/// ParseScopeAndOrdering
1621/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1622/// else: ::=
1623///
1624/// This sets Scope and Ordering to the parsed values.
1625bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1626 AtomicOrdering &Ordering) {
1627 if (!isAtomic)
1628 return false;
1629
1630 Scope = CrossThread;
1631 if (EatIfPresent(lltok::kw_singlethread))
1632 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001633
1634 return ParseOrdering(Ordering);
1635}
1636
1637/// ParseOrdering
1638/// ::= AtomicOrdering
1639///
1640/// This sets Ordering to the parsed value.
1641bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001642 switch (Lex.getKind()) {
1643 default: return TokError("Expected ordering on atomic instruction");
1644 case lltok::kw_unordered: Ordering = Unordered; break;
1645 case lltok::kw_monotonic: Ordering = Monotonic; break;
1646 case lltok::kw_acquire: Ordering = Acquire; break;
1647 case lltok::kw_release: Ordering = Release; break;
1648 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1649 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1650 }
1651 Lex.Lex();
1652 return false;
1653}
1654
Charles Davisbe5557e2010-02-12 00:31:15 +00001655/// ParseOptionalStackAlignment
1656/// ::= /* empty */
1657/// ::= 'alignstack' '(' 4 ')'
1658bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1659 Alignment = 0;
1660 if (!EatIfPresent(lltok::kw_alignstack))
1661 return false;
1662 LocTy ParenLoc = Lex.getLoc();
1663 if (!EatIfPresent(lltok::lparen))
1664 return Error(ParenLoc, "expected '('");
1665 LocTy AlignLoc = Lex.getLoc();
1666 if (ParseUInt32(Alignment)) return true;
1667 ParenLoc = Lex.getLoc();
1668 if (!EatIfPresent(lltok::rparen))
1669 return Error(ParenLoc, "expected ')'");
1670 if (!isPowerOf2_32(Alignment))
1671 return Error(AlignLoc, "stack alignment is not a power of two");
1672 return false;
1673}
Devang Patelea8a4b92009-09-17 23:04:48 +00001674
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001675/// ParseIndexList - This parses the index list for an insert/extractvalue
1676/// instruction. This sets AteExtraComma in the case where we eat an extra
1677/// comma at the end of the line and find that it is followed by metadata.
1678/// Clients that don't allow metadata can call the version of this function that
1679/// only takes one argument.
1680///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001681/// ParseIndexList
1682/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001683///
1684bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1685 bool &AteExtraComma) {
1686 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001687
Chris Lattnerac161bf2009-01-02 07:01:27 +00001688 if (Lex.getKind() != lltok::comma)
1689 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001690
Chris Lattner3822f632009-01-02 08:05:26 +00001691 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001692 if (Lex.getKind() == lltok::MetadataVar) {
1693 AteExtraComma = true;
1694 return false;
1695 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001696 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001697 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001698 Indices.push_back(Idx);
1699 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001700
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701 return false;
1702}
1703
1704//===----------------------------------------------------------------------===//
1705// Type Parsing.
1706//===----------------------------------------------------------------------===//
1707
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001708/// ParseType - Parse a type.
1709bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1710 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001711 switch (Lex.getKind()) {
1712 default:
1713 return TokError("expected type");
1714 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001716 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001717 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001718 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001720 // Type ::= StructType
1721 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 return true;
1723 break;
1724 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001725 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001726 Lex.Lex(); // eat the lsquare.
1727 if (ParseArrayVectorType(Result, false))
1728 return true;
1729 break;
1730 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001731 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001732 Lex.Lex();
1733 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001734 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001735 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 } else if (ParseArrayVectorType(Result, true))
1738 return true;
1739 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001740 case lltok::LocalVar: {
1741 // Type ::= %foo
1742 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001743
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001744 // If the type hasn't been defined yet, create a forward definition and
1745 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001746 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001747 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001748 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001749 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001750 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001751 Lex.Lex();
1752 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001754
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001755 case lltok::LocalVarID: {
1756 // Type ::= %4
1757 if (Lex.getUIntVal() >= NumberedTypes.size())
1758 NumberedTypes.resize(Lex.getUIntVal()+1);
1759 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001760
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761 // If the type hasn't been defined yet, create a forward definition and
1762 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001763 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001764 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001765 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001766 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001767 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001768 Lex.Lex();
1769 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001770 }
1771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001772
1773 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001774 while (1) {
1775 switch (Lex.getKind()) {
1776 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001777 default:
1778 if (!AllowVoid && Result->isVoidTy())
1779 return Error(TypeLoc, "void type only allowed for function results");
1780 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001781
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001782 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001783 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001784 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001786 if (Result->isVoidTy())
1787 return TokError("pointers to void are invalid - use i8* instead");
1788 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001789 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001790 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001791 Lex.Lex();
1792 break;
1793
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001794 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001795 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001796 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001798 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001799 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001800 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001801 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001802 unsigned AddrSpace;
1803 if (ParseOptionalAddrSpace(AddrSpace) ||
1804 ParseToken(lltok::star, "expected '*' in address space"))
1805 return true;
1806
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001807 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001808 break;
1809 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001810
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1812 case lltok::lparen:
1813 if (ParseFunctionType(Result))
1814 return true;
1815 break;
1816 }
1817 }
1818}
1819
1820/// ParseParameterList
1821/// ::= '(' ')'
1822/// ::= '(' Arg (',' Arg)* ')'
1823/// Arg
1824/// ::= Type OptionalAttributes Value OptionalAttributes
1825bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001826 PerFunctionState &PFS, bool IsMustTailCall,
1827 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001828 if (ParseToken(lltok::lparen, "expected '(' in call"))
1829 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001830
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001831 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001832 while (Lex.getKind() != lltok::rparen) {
1833 // If this isn't the first argument, we need a comma.
1834 if (!ArgList.empty() &&
1835 ParseToken(lltok::comma, "expected ',' in argument list"))
1836 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001837
Reid Kleckner83498642014-08-26 00:33:28 +00001838 // Parse an ellipsis if this is a musttail call in a variadic function.
1839 if (Lex.getKind() == lltok::dotdotdot) {
1840 const char *Msg = "unexpected ellipsis in argument list for ";
1841 if (!IsMustTailCall)
1842 return TokError(Twine(Msg) + "non-musttail call");
1843 if (!InVarArgsFunc)
1844 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1845 Lex.Lex(); // Lex the '...', it is purely for readability.
1846 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1847 }
1848
Chris Lattnerac161bf2009-01-02 07:01:27 +00001849 // Parse the argument.
1850 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001851 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001852 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001854 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001855 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001856
Chris Lattner5b4a9622009-12-30 02:11:14 +00001857 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001858 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001859 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001860 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1861 AttrIndex++,
1862 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001863 }
1864
Reid Kleckner83498642014-08-26 00:33:28 +00001865 if (IsMustTailCall && InVarArgsFunc)
1866 return TokError("expected '...' at end of argument list for musttail call "
1867 "in varargs function");
1868
Chris Lattnerac161bf2009-01-02 07:01:27 +00001869 Lex.Lex(); // Lex the ')'.
1870 return false;
1871}
1872
1873
1874
Chris Lattner2ed06b42009-01-05 18:34:07 +00001875/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001876/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001877/// ::= '(' ArgTypeListI ')'
1878/// ArgTypeListI
1879/// ::= /*empty*/
1880/// ::= '...'
1881/// ::= ArgTypeList ',' '...'
1882/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001883///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001884bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1885 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001886 isVarArg = false;
1887 assert(Lex.getKind() == lltok::lparen);
1888 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001889
Chris Lattnerac161bf2009-01-02 07:01:27 +00001890 if (Lex.getKind() == lltok::rparen) {
1891 // empty
1892 } else if (Lex.getKind() == lltok::dotdotdot) {
1893 isVarArg = true;
1894 Lex.Lex();
1895 } else {
1896 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001897 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001898 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001899 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001900
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001902 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001903
Chris Lattnerfdd87902009-10-05 05:54:46 +00001904 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001905 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001906
Chris Lattnerdef19492011-06-17 06:36:20 +00001907 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001908 Name = Lex.getStrVal();
1909 Lex.Lex();
1910 }
Chris Lattner3822f632009-01-02 08:05:26 +00001911
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001912 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001913 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001914
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001915 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001916 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001917 AttributeSet::get(ArgTy->getContext(),
1918 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001919
Chris Lattner3822f632009-01-02 08:05:26 +00001920 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001922 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924 break;
1925 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001926
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 // Otherwise must be an argument type.
1928 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001929 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001930
Chris Lattnerfdd87902009-10-05 05:54:46 +00001931 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001932 return Error(TypeLoc, "argument can not have void type");
1933
Chris Lattnerdef19492011-06-17 06:36:20 +00001934 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935 Name = Lex.getStrVal();
1936 Lex.Lex();
1937 } else {
1938 Name = "";
1939 }
Chris Lattner3822f632009-01-02 08:05:26 +00001940
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001941 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001942 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001943
Bill Wendlingd079a442012-10-15 04:46:55 +00001944 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001945 AttributeSet::get(ArgTy->getContext(),
1946 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001947 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001948 }
1949 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001950
Chris Lattner3822f632009-01-02 08:05:26 +00001951 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954/// ParseFunctionType
1955/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001956bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957 assert(Lex.getKind() == lltok::lparen);
1958
Chris Lattnerce473c72009-01-05 08:04:33 +00001959 if (!FunctionType::isValidReturnType(Result))
1960 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001961
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001963 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001964 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001966
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 // Reject names on the arguments lists.
1968 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1969 if (!ArgList[i].Name.empty())
1970 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001971 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001972 return Error(ArgList[i].Loc,
1973 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001974 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001975
Jay Foadb804a2b2011-07-12 14:06:48 +00001976 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001979
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981 return false;
1982}
1983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1985/// other structs.
1986bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1987 SmallVector<Type*, 8> Elts;
1988 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001989
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001990 Result = StructType::get(Context, Elts, Packed);
1991 return false;
1992}
1993
1994/// ParseStructDefinition - Parse a struct in a 'type' definition.
1995bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1996 std::pair<Type*, LocTy> &Entry,
1997 Type *&ResultTy) {
1998 // If the type was already defined, diagnose the redefinition.
1999 if (Entry.first && !Entry.second.isValid())
2000 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002001
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002 // If we have opaque, just return without filling in the definition for the
2003 // struct. This counts as a definition as far as the .ll file goes.
2004 if (EatIfPresent(lltok::kw_opaque)) {
2005 // This type is being defined, so clear the location to indicate this.
2006 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002007
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002009 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002010 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002011 ResultTy = Entry.first;
2012 return false;
2013 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002014
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 // If the type starts with '<', then it is either a packed struct or a vector.
2016 bool isPacked = EatIfPresent(lltok::less);
2017
2018 // If we don't have a struct, then we have a random type alias, which we
2019 // accept for compatibility with old files. These types are not allowed to be
2020 // forward referenced and not allowed to be recursive.
2021 if (Lex.getKind() != lltok::lbrace) {
2022 if (Entry.first)
2023 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002024
Craig Topper2617dcc2014-04-15 06:32:26 +00002025 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 if (isPacked)
2027 return ParseArrayVectorType(ResultTy, true);
2028 return ParseType(ResultTy);
2029 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 // This type is being defined, so clear the location to indicate this.
2032 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002035 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002036 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002037
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002038 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002039
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002040 SmallVector<Type*, 8> Body;
2041 if (ParseStructBody(Body) ||
2042 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2043 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002044
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 STy->setBody(Body, isPacked);
2046 ResultTy = STy;
2047 return false;
2048}
2049
2050
Chris Lattnerac161bf2009-01-02 07:01:27 +00002051/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002053/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002054/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056/// ::= '<' '{' Type (',' Type)* '}' '>'
2057bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 assert(Lex.getKind() == lltok::lbrace);
2059 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002060
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061 // Handle the empty struct.
2062 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002063 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064
Chris Lattnerf880ca22009-03-09 04:49:14 +00002065 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002066 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002067 if (ParseType(Ty)) return true;
2068 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002069
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002071 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002072
Chris Lattner3822f632009-01-02 08:05:26 +00002073 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002074 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002075 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002076
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002078 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002079
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002080 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002082
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084}
2085
2086/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2087/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089/// ::= '[' APSINTVAL 'x' Types ']'
2090/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2093 Lex.getAPSIntVal().getBitWidth() > 64)
2094 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002095
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 LocTy SizeLoc = Lex.getLoc();
2097 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002098 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002099
Chris Lattner3822f632009-01-02 08:05:26 +00002100 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2101 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102
2103 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002104 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002105 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002106
Chris Lattner3822f632009-01-02 08:05:26 +00002107 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2108 "expected end of sequential type"))
2109 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002110
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002112 if (Size == 0)
2113 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 if ((unsigned)Size != Size)
2115 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002116 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002117 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002118 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002120 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002122 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 }
2124 return false;
2125}
2126
2127//===----------------------------------------------------------------------===//
2128// Function Semantic Analysis.
2129//===----------------------------------------------------------------------===//
2130
Chris Lattner3432c622009-10-28 03:39:23 +00002131LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2132 int functionNumber)
2133 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134
2135 // Insert unnamed arguments into the NumberedVals list.
2136 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2137 AI != E; ++AI)
2138 if (!AI->hasName())
2139 NumberedVals.push_back(AI);
2140}
2141
2142LLParser::PerFunctionState::~PerFunctionState() {
2143 // If there were any forward referenced non-basicblock values, delete them.
2144 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2145 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2146 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002147 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002148 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002150 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002152
Chris Lattnerac161bf2009-01-02 07:01:27 +00002153 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2154 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2155 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002156 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002157 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002159 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 }
2161}
2162
Chris Lattner3432c622009-10-28 03:39:23 +00002163bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 if (!ForwardRefVals.empty())
2165 return P.Error(ForwardRefVals.begin()->second.second,
2166 "use of undefined value '%" + ForwardRefVals.begin()->first +
2167 "'");
2168 if (!ForwardRefValIDs.empty())
2169 return P.Error(ForwardRefValIDs.begin()->second.second,
2170 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002171 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 return false;
2173}
2174
2175
2176/// GetVal - Get a value with the specified name or ID, creating a
2177/// forward reference record if needed. This can return null if the value
2178/// exists but does not have the right type.
2179Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002180 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002181 // Look this name up in the normal function symbol table.
2182 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002183
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 // If this is a forward reference for the value, see if we already created a
2185 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002186 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2188 I = ForwardRefVals.find(Name);
2189 if (I != ForwardRefVals.end())
2190 Val = I->second.first;
2191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002192
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 // If we have the value in the symbol table or fwd-ref table, return it.
2194 if (Val) {
2195 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002196 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 P.Error(Loc, "'%" + Name + "' is not a basic block");
2198 else
2199 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002200 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002201 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002203
Chris Lattnerac161bf2009-01-02 07:01:27 +00002204 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002205 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002207 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002209
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 // Otherwise, create a new forward reference for this value and remember it.
2211 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002212 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002213 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 else
2215 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2218 return FwdVal;
2219}
2220
Chris Lattner229907c2011-07-18 04:54:35 +00002221Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 LocTy Loc) {
2223 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002224 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002225
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226 // If this is a forward reference for the value, see if we already created a
2227 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002228 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2230 I = ForwardRefValIDs.find(ID);
2231 if (I != ForwardRefValIDs.end())
2232 Val = I->second.first;
2233 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 // If we have the value in the symbol table or fwd-ref table, return it.
2236 if (Val) {
2237 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002238 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002239 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002240 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002241 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002242 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002243 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002245
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002246 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002248 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 // Otherwise, create a new forward reference for this value and remember it.
2252 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002253 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002254 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 else
2256 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2259 return FwdVal;
2260}
2261
2262/// SetInstName - After an instruction is parsed and inserted into its
2263/// basic block, this installs its name.
2264bool LLParser::PerFunctionState::SetInstName(int NameID,
2265 const std::string &NameStr,
2266 LocTy NameLoc, Instruction *Inst) {
2267 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002268 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269 if (NameID != -1 || !NameStr.empty())
2270 return P.Error(NameLoc, "instructions returning void cannot have a name");
2271 return false;
2272 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002273
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274 // If this was a numbered instruction, verify that the instruction is the
2275 // expected value and resolve any forward references.
2276 if (NameStr.empty()) {
2277 // If neither a name nor an ID was specified, just use the next ID.
2278 if (NameID == -1)
2279 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002280
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 if (unsigned(NameID) != NumberedVals.size())
2282 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002283 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2286 ForwardRefValIDs.find(NameID);
2287 if (FI != ForwardRefValIDs.end()) {
2288 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002289 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002290 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002292 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 ForwardRefValIDs.erase(FI);
2294 }
2295
2296 NumberedVals.push_back(Inst);
2297 return false;
2298 }
2299
2300 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2301 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2302 FI = ForwardRefVals.find(NameStr);
2303 if (FI != ForwardRefVals.end()) {
2304 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002305 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002306 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002307 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002308 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309 ForwardRefVals.erase(FI);
2310 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002311
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 // Set the name on the instruction.
2313 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002315 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002316 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 NameStr + "'");
2318 return false;
2319}
2320
2321/// GetBB - Get a basic block with the specified name or ID, creating a
2322/// forward reference record if needed.
2323BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2324 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002325 return cast_or_null<BasicBlock>(GetVal(Name,
2326 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327}
2328
2329BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002330 return cast_or_null<BasicBlock>(GetVal(ID,
2331 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332}
2333
2334/// DefineBB - Define the specified basic block, which is either named or
2335/// unnamed. If there is an error, this returns null otherwise it returns
2336/// the block being defined.
2337BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2338 LocTy Loc) {
2339 BasicBlock *BB;
2340 if (Name.empty())
2341 BB = GetBB(NumberedVals.size(), Loc);
2342 else
2343 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002344 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 // Move the block to the end of the function. Forward ref'd blocks are
2347 // inserted wherever they happen to be referenced.
2348 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 // Remove the block from forward ref sets.
2351 if (Name.empty()) {
2352 ForwardRefValIDs.erase(NumberedVals.size());
2353 NumberedVals.push_back(BB);
2354 } else {
2355 // BB forward references are already in the function symbol table.
2356 ForwardRefVals.erase(Name);
2357 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002358
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 return BB;
2360}
2361
2362//===----------------------------------------------------------------------===//
2363// Constants.
2364//===----------------------------------------------------------------------===//
2365
2366/// ParseValID - Parse an abstract value that doesn't necessarily have a
2367/// type implied. For example, if we parse "4" we don't know what integer type
2368/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002369/// sanity. PFS is used to convert function-local operands of metadata (since
2370/// metadata operands are not just parsed here but also converted to values).
2371/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002372bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 ID.Loc = Lex.getLoc();
2374 switch (Lex.getKind()) {
2375 default: return TokError("expected value token");
2376 case lltok::GlobalID: // @42
2377 ID.UIntVal = Lex.getUIntVal();
2378 ID.Kind = ValID::t_GlobalID;
2379 break;
2380 case lltok::GlobalVar: // @foo
2381 ID.StrVal = Lex.getStrVal();
2382 ID.Kind = ValID::t_GlobalName;
2383 break;
2384 case lltok::LocalVarID: // %42
2385 ID.UIntVal = Lex.getUIntVal();
2386 ID.Kind = ValID::t_LocalID;
2387 break;
2388 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002389 ID.StrVal = Lex.getStrVal();
2390 ID.Kind = ValID::t_LocalName;
2391 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002392 case lltok::exclaim: // !42, !{...}, or !"foo"
2393 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002395 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002396 ID.Kind = ValID::t_APSInt;
2397 break;
2398 case lltok::APFloat:
2399 ID.APFloatVal = Lex.getAPFloatVal();
2400 ID.Kind = ValID::t_APFloat;
2401 break;
2402 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002403 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002404 ID.Kind = ValID::t_Constant;
2405 break;
2406 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002407 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 ID.Kind = ValID::t_Constant;
2409 break;
2410 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2411 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2412 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002413
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 case lltok::lbrace: {
2415 // ValID ::= '{' ConstVector '}'
2416 Lex.Lex();
2417 SmallVector<Constant*, 16> Elts;
2418 if (ParseGlobalValueVector(Elts) ||
2419 ParseToken(lltok::rbrace, "expected end of struct constant"))
2420 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002421
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002422 ID.ConstantStructElts = new Constant*[Elts.size()];
2423 ID.UIntVal = Elts.size();
2424 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2425 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002426 return false;
2427 }
2428 case lltok::less: {
2429 // ValID ::= '<' ConstVector '>' --> Vector.
2430 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2431 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002432 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434 SmallVector<Constant*, 16> Elts;
2435 LocTy FirstEltLoc = Lex.getLoc();
2436 if (ParseGlobalValueVector(Elts) ||
2437 (isPackedStruct &&
2438 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2439 ParseToken(lltok::greater, "expected end of constant"))
2440 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002441
Chris Lattnerac161bf2009-01-02 07:01:27 +00002442 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002443 ID.ConstantStructElts = new Constant*[Elts.size()];
2444 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2445 ID.UIntVal = Elts.size();
2446 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 return false;
2448 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002449
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 if (Elts.empty())
2451 return Error(ID.Loc, "constant vector must not be empty");
2452
Duncan Sands9dff9be2010-02-15 16:12:20 +00002453 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002454 !Elts[0]->getType()->isFloatingPointTy() &&
2455 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002457 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002458
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 // Verify that all the vector elements have the same type.
2460 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2461 if (Elts[i]->getType() != Elts[0]->getType())
2462 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002463 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002464 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002465
Chris Lattner69229312011-02-15 00:14:00 +00002466 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 ID.Kind = ValID::t_Constant;
2468 return false;
2469 }
2470 case lltok::lsquare: { // Array Constant
2471 Lex.Lex();
2472 SmallVector<Constant*, 16> Elts;
2473 LocTy FirstEltLoc = Lex.getLoc();
2474 if (ParseGlobalValueVector(Elts) ||
2475 ParseToken(lltok::rsquare, "expected end of array constant"))
2476 return true;
2477
2478 // Handle empty element.
2479 if (Elts.empty()) {
2480 // Use undef instead of an array because it's inconvenient to determine
2481 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002482 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 return false;
2484 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002485
Chris Lattnerac161bf2009-01-02 07:01:27 +00002486 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002488 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002489
Owen Anderson4056ca92009-07-29 22:17:13 +00002490 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002493 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494 if (Elts[i]->getType() != Elts[0]->getType())
2495 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002496 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002497 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Jay Foad83be3612011-06-22 09:24:39 +00002500 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 ID.Kind = ValID::t_Constant;
2502 return false;
2503 }
2504 case lltok::kw_c: // c "foo"
2505 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002506 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2507 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2509 ID.Kind = ValID::t_Constant;
2510 return false;
2511
2512 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002513 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2514 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002515 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 Lex.Lex();
2517 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002518 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002519 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002520 ParseStringConstant(ID.StrVal) ||
2521 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 ParseToken(lltok::StringConstant, "expected constraint string"))
2523 return true;
2524 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002525 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002526 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002527 ID.Kind = ValID::t_InlineAsm;
2528 return false;
2529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattner3432c622009-10-28 03:39:23 +00002531 case lltok::kw_blockaddress: {
2532 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2533 Lex.Lex();
2534
2535 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002536
Chris Lattner3432c622009-10-28 03:39:23 +00002537 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2538 ParseValID(Fn) ||
2539 ParseToken(lltok::comma, "expected comma in block address expression")||
2540 ParseValID(Label) ||
2541 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2542 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002543
Chris Lattner3432c622009-10-28 03:39:23 +00002544 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2545 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002546 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002547 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002548
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002549 // Try to find the function (but skip it if it's forward-referenced).
2550 GlobalValue *GV = nullptr;
2551 if (Fn.Kind == ValID::t_GlobalID) {
2552 if (Fn.UIntVal < NumberedVals.size())
2553 GV = NumberedVals[Fn.UIntVal];
2554 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2555 GV = M->getNamedValue(Fn.StrVal);
2556 }
2557 Function *F = nullptr;
2558 if (GV) {
2559 // Confirm that it's actually a function with a definition.
2560 if (!isa<Function>(GV))
2561 return Error(Fn.Loc, "expected function name in blockaddress");
2562 F = cast<Function>(GV);
2563 if (F->isDeclaration())
2564 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2565 }
2566
2567 if (!F) {
2568 // Make a global variable as a placeholder for this reference.
2569 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2570 if (!FwdRef)
2571 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2572 GlobalValue::InternalLinkage, nullptr, "");
2573 ID.ConstantVal = FwdRef;
2574 ID.Kind = ValID::t_Constant;
2575 return false;
2576 }
2577
2578 // We found the function; now find the basic block. Don't use PFS, since we
2579 // might be inside a constant expression.
2580 BasicBlock *BB;
2581 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2582 if (Label.Kind == ValID::t_LocalID)
2583 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2584 else
2585 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2586 if (!BB)
2587 return Error(Label.Loc, "referenced value is not a basic block");
2588 } else {
2589 if (Label.Kind == ValID::t_LocalID)
2590 return Error(Label.Loc, "cannot take address of numeric label after "
2591 "the function is defined");
2592 BB = dyn_cast_or_null<BasicBlock>(
2593 F->getValueSymbolTable().lookup(Label.StrVal));
2594 if (!BB)
2595 return Error(Label.Loc, "referenced value is not a basic block");
2596 }
2597
2598 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002599 ID.Kind = ValID::t_Constant;
2600 return false;
2601 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002602
Chris Lattnerac161bf2009-01-02 07:01:27 +00002603 case lltok::kw_trunc:
2604 case lltok::kw_zext:
2605 case lltok::kw_sext:
2606 case lltok::kw_fptrunc:
2607 case lltok::kw_fpext:
2608 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002609 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002610 case lltok::kw_uitofp:
2611 case lltok::kw_sitofp:
2612 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002613 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002614 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002615 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002616 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002617 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002618 Constant *SrcVal;
2619 Lex.Lex();
2620 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2621 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002622 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 ParseType(DestTy) ||
2624 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2625 return true;
2626 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2627 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002628 getTypeString(SrcVal->getType()) + "' to '" +
2629 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002630 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002631 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 ID.Kind = ValID::t_Constant;
2633 return false;
2634 }
2635 case lltok::kw_extractvalue: {
2636 Lex.Lex();
2637 Constant *Val;
2638 SmallVector<unsigned, 4> Indices;
2639 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2640 ParseGlobalTypeAndValue(Val) ||
2641 ParseIndexList(Indices) ||
2642 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2643 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002644
Chris Lattner392be582010-02-12 20:49:41 +00002645 if (!Val->getType()->isAggregateType())
2646 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002647 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002649 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 ID.Kind = ValID::t_Constant;
2651 return false;
2652 }
2653 case lltok::kw_insertvalue: {
2654 Lex.Lex();
2655 Constant *Val0, *Val1;
2656 SmallVector<unsigned, 4> Indices;
2657 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2658 ParseGlobalTypeAndValue(Val0) ||
2659 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2660 ParseGlobalTypeAndValue(Val1) ||
2661 ParseIndexList(Indices) ||
2662 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2663 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002664 if (!Val0->getType()->isAggregateType())
2665 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002666 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002668 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 ID.Kind = ValID::t_Constant;
2670 return false;
2671 }
2672 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002673 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 unsigned PredVal, Opc = Lex.getUIntVal();
2675 Constant *Val0, *Val1;
2676 Lex.Lex();
2677 if (ParseCmpPredicate(PredVal, Opc) ||
2678 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2679 ParseGlobalTypeAndValue(Val0) ||
2680 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2681 ParseGlobalTypeAndValue(Val1) ||
2682 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2683 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002684
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 if (Val0->getType() != Val1->getType())
2686 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002687
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002689
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002691 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002693 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002694 } else {
2695 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002696 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002697 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002699 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 }
2701 ID.Kind = ValID::t_Constant;
2702 return false;
2703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002704
Chris Lattnerac161bf2009-01-02 07:01:27 +00002705 // Binary Operators.
2706 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002707 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002709 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002711 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002712 case lltok::kw_udiv:
2713 case lltok::kw_sdiv:
2714 case lltok::kw_fdiv:
2715 case lltok::kw_urem:
2716 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002717 case lltok::kw_frem:
2718 case lltok::kw_shl:
2719 case lltok::kw_lshr:
2720 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002721 bool NUW = false;
2722 bool NSW = false;
2723 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002724 unsigned Opc = Lex.getUIntVal();
2725 Constant *Val0, *Val1;
2726 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002727 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002728 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2729 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002730 if (EatIfPresent(lltok::kw_nuw))
2731 NUW = true;
2732 if (EatIfPresent(lltok::kw_nsw)) {
2733 NSW = true;
2734 if (EatIfPresent(lltok::kw_nuw))
2735 NUW = true;
2736 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002737 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2738 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002739 if (EatIfPresent(lltok::kw_exact))
2740 Exact = true;
2741 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2743 ParseGlobalTypeAndValue(Val0) ||
2744 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2745 ParseGlobalTypeAndValue(Val1) ||
2746 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2747 return true;
2748 if (Val0->getType() != Val1->getType())
2749 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002750 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002751 if (NUW)
2752 return Error(ModifierLoc, "nuw only applies to integer operations");
2753 if (NSW)
2754 return Error(ModifierLoc, "nsw only applies to integer operations");
2755 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002756 // Check that the type is valid for the operator.
2757 switch (Opc) {
2758 case Instruction::Add:
2759 case Instruction::Sub:
2760 case Instruction::Mul:
2761 case Instruction::UDiv:
2762 case Instruction::SDiv:
2763 case Instruction::URem:
2764 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002765 case Instruction::Shl:
2766 case Instruction::AShr:
2767 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002768 if (!Val0->getType()->isIntOrIntVectorTy())
2769 return Error(ID.Loc, "constexpr requires integer operands");
2770 break;
2771 case Instruction::FAdd:
2772 case Instruction::FSub:
2773 case Instruction::FMul:
2774 case Instruction::FDiv:
2775 case Instruction::FRem:
2776 if (!Val0->getType()->isFPOrFPVectorTy())
2777 return Error(ID.Loc, "constexpr requires fp operands");
2778 break;
2779 default: llvm_unreachable("Unknown binary operator!");
2780 }
Dan Gohman1b849082009-09-07 23:54:19 +00002781 unsigned Flags = 0;
2782 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2783 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002784 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002785 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002786 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 ID.Kind = ValID::t_Constant;
2788 return false;
2789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 case lltok::kw_and:
2793 case lltok::kw_or:
2794 case lltok::kw_xor: {
2795 unsigned Opc = Lex.getUIntVal();
2796 Constant *Val0, *Val1;
2797 Lex.Lex();
2798 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2799 ParseGlobalTypeAndValue(Val0) ||
2800 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2801 ParseGlobalTypeAndValue(Val1) ||
2802 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2803 return true;
2804 if (Val0->getType() != Val1->getType())
2805 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002806 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002807 return Error(ID.Loc,
2808 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002809 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 ID.Kind = ValID::t_Constant;
2811 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812 }
2813
Chris Lattnerac161bf2009-01-02 07:01:27 +00002814 case lltok::kw_getelementptr:
2815 case lltok::kw_shufflevector:
2816 case lltok::kw_insertelement:
2817 case lltok::kw_extractelement:
2818 case lltok::kw_select: {
2819 unsigned Opc = Lex.getUIntVal();
2820 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002821 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002823 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002824 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2826 ParseGlobalValueVector(Elts) ||
2827 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2828 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002829
Chris Lattnerac161bf2009-01-02 07:01:27 +00002830 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002831 if (Elts.size() == 0 ||
2832 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Jay Foaded8db7d2011-07-21 14:31:17 +00002835 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002836 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002838 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2839 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 } else if (Opc == Instruction::Select) {
2841 if (Elts.size() != 3)
2842 return Error(ID.Loc, "expected three operands to select");
2843 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2844 Elts[2]))
2845 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002846 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 } else if (Opc == Instruction::ShuffleVector) {
2848 if (Elts.size() != 3)
2849 return Error(ID.Loc, "expected three operands to shufflevector");
2850 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2851 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002852 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002853 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002854 } else if (Opc == Instruction::ExtractElement) {
2855 if (Elts.size() != 2)
2856 return Error(ID.Loc, "expected two operands to extractelement");
2857 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2858 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002859 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 } else {
2861 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2862 if (Elts.size() != 3)
2863 return Error(ID.Loc, "expected three operands to insertelement");
2864 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2865 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002866 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002867 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002869
Chris Lattnerac161bf2009-01-02 07:01:27 +00002870 ID.Kind = ValID::t_Constant;
2871 return false;
2872 }
2873 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002874
Chris Lattnerac161bf2009-01-02 07:01:27 +00002875 Lex.Lex();
2876 return false;
2877}
2878
2879/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002880bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002881 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002882 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002883 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002884 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002885 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002886 if (V && !(C = dyn_cast<Constant>(V)))
2887 return Error(ID.Loc, "global values must be constants");
2888 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889}
2890
Victor Hernandez9d75c962010-01-11 22:31:58 +00002891bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002892 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002893 return ParseType(Ty) ||
2894 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002895}
2896
David Majnemerdad0a642014-06-27 18:19:56 +00002897bool LLParser::parseOptionalComdat(Comdat *&C) {
2898 C = nullptr;
2899 if (!EatIfPresent(lltok::kw_comdat))
2900 return false;
2901 if (Lex.getKind() != lltok::ComdatVar)
2902 return TokError("expected comdat variable");
2903 LocTy Loc = Lex.getLoc();
2904 StringRef Name = Lex.getStrVal();
2905 C = getComdat(Name, Loc);
2906 Lex.Lex();
2907 return false;
2908}
2909
Victor Hernandez9d75c962010-01-11 22:31:58 +00002910/// ParseGlobalValueVector
2911/// ::= /*empty*/
2912/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002913bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002914 // Empty list.
2915 if (Lex.getKind() == lltok::rbrace ||
2916 Lex.getKind() == lltok::rsquare ||
2917 Lex.getKind() == lltok::greater ||
2918 Lex.getKind() == lltok::rparen)
2919 return false;
2920
2921 Constant *C;
2922 if (ParseGlobalTypeAndValue(C)) return true;
2923 Elts.push_back(C);
2924
2925 while (EatIfPresent(lltok::comma)) {
2926 if (ParseGlobalTypeAndValue(C)) return true;
2927 Elts.push_back(C);
2928 }
2929
2930 return false;
2931}
2932
Dan Gohmanc828c542010-08-24 02:24:03 +00002933bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2934 assert(Lex.getKind() == lltok::lbrace);
2935 Lex.Lex();
2936
2937 SmallVector<Value*, 16> Elts;
2938 if (ParseMDNodeVector(Elts, PFS) ||
2939 ParseToken(lltok::rbrace, "expected end of metadata node"))
2940 return true;
2941
Jay Foad5514afe2011-04-21 19:59:31 +00002942 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002943 ID.Kind = ValID::t_MDNode;
2944 return false;
2945}
2946
Dan Gohman8939ba332010-07-14 18:26:50 +00002947/// ParseMetadataValue
2948/// ::= !42
2949/// ::= !{...}
2950/// ::= !"string"
2951bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2952 assert(Lex.getKind() == lltok::exclaim);
2953 Lex.Lex();
2954
2955 // MDNode:
2956 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002957 if (Lex.getKind() == lltok::lbrace)
2958 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002959
2960 // Standalone metadata reference
2961 // !42
2962 if (Lex.getKind() == lltok::APSInt) {
2963 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2964 ID.Kind = ValID::t_MDNode;
2965 return false;
2966 }
2967
2968 // MDString:
2969 // ::= '!' STRINGCONSTANT
2970 if (ParseMDString(ID.MDStringVal)) return true;
2971 ID.Kind = ValID::t_MDString;
2972 return false;
2973}
2974
Victor Hernandez9d75c962010-01-11 22:31:58 +00002975
2976//===----------------------------------------------------------------------===//
2977// Function Parsing.
2978//===----------------------------------------------------------------------===//
2979
Chris Lattner229907c2011-07-18 04:54:35 +00002980bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00002981 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002982 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002983 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002984
Chris Lattnerac161bf2009-01-02 07:01:27 +00002985 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002987 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2988 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002989 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002990 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002991 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2992 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002993 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002994 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00002995 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002996 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00002997 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002998 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2999 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003000 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003001 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003002 return false;
3003 }
3004 case ValID::t_MDNode:
3005 if (!Ty->isMetadataTy())
3006 return Error(ID.Loc, "metadata value must have metadata type");
3007 V = ID.MDNodeVal;
3008 return false;
3009 case ValID::t_MDString:
3010 if (!Ty->isMetadataTy())
3011 return Error(ID.Loc, "metadata value must have metadata type");
3012 V = ID.MDStringVal;
3013 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003014 case ValID::t_GlobalName:
3015 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003016 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003017 case ValID::t_GlobalID:
3018 V = GetGlobalVal(ID.UIntVal, 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_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003021 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003023 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003024 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003025 return false;
3026 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003027 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003028 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3029 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003030
Dan Gohman518cda42011-12-17 00:04:22 +00003031 // The lexer has no type info, so builds all half, float, and double FP
3032 // constants as double. Fix this here. Long double does not need this.
3033 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003034 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003035 if (Ty->isHalfTy())
3036 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3037 &Ignored);
3038 else if (Ty->isFloatTy())
3039 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3040 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003042 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003043
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003044 if (V->getType() != Ty)
3045 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003046 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003047
Chris Lattnerac161bf2009-01-02 07:01:27 +00003048 return false;
3049 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003050 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003051 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003052 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 return false;
3054 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003055 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003056 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003057 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003058 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003060 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003061 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003062 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003063 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003064 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003065 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003066 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003067 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003069 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003070 return false;
3071 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003072 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003074
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075 V = ID.ConstantVal;
3076 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003077 case ValID::t_ConstantStruct:
3078 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003079 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003080 if (ST->getNumElements() != ID.UIntVal)
3081 return Error(ID.Loc,
3082 "initializer with struct type has wrong # elements");
3083 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3084 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003086 // Verify that the elements are compatible with the structtype.
3087 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3088 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3089 return Error(ID.Loc, "element " + Twine(i) +
3090 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003091
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003092 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3093 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003094 } else
3095 return Error(ID.Loc, "constant expression type mismatch");
3096 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003098 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003099}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003100
Chris Lattner229907c2011-07-18 04:54:35 +00003101bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003102 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003103 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003104 return ParseValID(ID, PFS) ||
3105 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003106}
3107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003108bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003109 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003110 return ParseType(Ty) ||
3111 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112}
3113
Chris Lattner3ed871f2009-10-27 19:13:16 +00003114bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3115 PerFunctionState &PFS) {
3116 Value *V;
3117 Loc = Lex.getLoc();
3118 if (ParseTypeAndValue(V, PFS)) return true;
3119 if (!isa<BasicBlock>(V))
3120 return Error(Loc, "expected a basic block");
3121 BB = cast<BasicBlock>(V);
3122 return false;
3123}
3124
3125
Chris Lattnerac161bf2009-01-02 07:01:27 +00003126/// FunctionHeader
3127/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003128/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003129/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003130bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3131 // Parse the linkage.
3132 LocTy LinkageLoc = Lex.getLoc();
3133 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003134
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003135 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003136 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003137 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003138 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003139 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003140 LocTy RetTypeLoc = Lex.getLoc();
3141 if (ParseOptionalLinkage(Linkage) ||
3142 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003143 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003145 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003146 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147 return true;
3148
3149 // Verify that the linkage is ok.
3150 switch ((GlobalValue::LinkageTypes)Linkage) {
3151 case GlobalValue::ExternalLinkage:
3152 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003153 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003154 if (isDefine)
3155 return Error(LinkageLoc, "invalid linkage for function definition");
3156 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003157 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003159 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003160 case GlobalValue::LinkOnceAnyLinkage:
3161 case GlobalValue::LinkOnceODRLinkage:
3162 case GlobalValue::WeakAnyLinkage:
3163 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003164 if (!isDefine)
3165 return Error(LinkageLoc, "invalid linkage for function declaration");
3166 break;
3167 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003168 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003169 return Error(LinkageLoc, "invalid function linkage type");
3170 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003171
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003172 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3173 return Error(LinkageLoc,
3174 "symbol with local linkage must have default visibility");
3175
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003176 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003177 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003178
Chris Lattnerac161bf2009-01-02 07:01:27 +00003179 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003180
3181 std::string FunctionName;
3182 if (Lex.getKind() == lltok::GlobalVar) {
3183 FunctionName = Lex.getStrVal();
3184 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3185 unsigned NameID = Lex.getUIntVal();
3186
3187 if (NameID != NumberedVals.size())
3188 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003189 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003190 } else {
3191 return TokError("expected function name");
3192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003193
Chris Lattner3822f632009-01-02 08:05:26 +00003194 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003195
Chris Lattner3822f632009-01-02 08:05:26 +00003196 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003197 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003199 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003201 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003202 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003203 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003204 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003206 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003207 bool UnnamedAddr;
3208 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003209 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003210 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003211 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003212
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003213 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003214 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3215 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003216 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003217 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003218 (EatIfPresent(lltok::kw_section) &&
3219 ParseStringConstant(Section)) ||
David Majnemerdad0a642014-06-27 18:19:56 +00003220 parseOptionalComdat(C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003221 ParseOptionalAlignment(Alignment) ||
3222 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003223 ParseStringConstant(GC)) ||
3224 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003225 ParseGlobalTypeAndValue(Prefix)) ||
3226 (EatIfPresent(lltok::kw_prologue) &&
3227 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003228 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003229
Michael Gottesman41748d72013-06-27 00:25:01 +00003230 if (FuncAttrs.contains(Attribute::Builtin))
3231 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003232
Chris Lattnerac161bf2009-01-02 07:01:27 +00003233 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003234 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003235 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003236 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003237 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003238
Chris Lattnerac161bf2009-01-02 07:01:27 +00003239 // Okay, if we got here, the function is syntactically valid. Convert types
3240 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003241 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003242 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003243
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003244 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003245 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3246 AttributeSet::ReturnIndex,
3247 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003248
Chris Lattnerac161bf2009-01-02 07:01:27 +00003249 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003250 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003251 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3252 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003253 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3254 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 }
3256
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003257 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003258 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3259 AttributeSet::FunctionIndex,
3260 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003261
Bill Wendlinge94d8432012-12-07 23:16:57 +00003262 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003263
Bill Wendling749a43d2012-12-30 13:50:49 +00003264 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003265 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3266
Chris Lattner229907c2011-07-18 04:54:35 +00003267 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003268 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003269 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003270
Craig Topper2617dcc2014-04-15 06:32:26 +00003271 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003272 if (!FunctionName.empty()) {
3273 // If this was a definition of a forward reference, remove the definition
3274 // from the forward reference table and fill in the forward ref.
3275 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3276 ForwardRefVals.find(FunctionName);
3277 if (FRVI != ForwardRefVals.end()) {
3278 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003279 if (!Fn)
3280 return Error(FRVI->second.second, "invalid forward reference to "
3281 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003282 if (Fn->getType() != PFT)
3283 return Error(FRVI->second.second, "invalid forward reference to "
3284 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003285
Chris Lattnerac161bf2009-01-02 07:01:27 +00003286 ForwardRefVals.erase(FRVI);
3287 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003288 // Reject redefinitions.
3289 return Error(NameLoc, "invalid redefinition of function '" +
3290 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003291 } else if (M->getNamedValue(FunctionName)) {
3292 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003293 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003294
Dan Gohman399d6ae2009-08-29 23:37:49 +00003295 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296 // If this is a definition of a forward referenced function, make sure the
3297 // types agree.
3298 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3299 = ForwardRefValIDs.find(NumberedVals.size());
3300 if (I != ForwardRefValIDs.end()) {
3301 Fn = cast<Function>(I->second.first);
3302 if (Fn->getType() != PFT)
3303 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003304 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003305 ForwardRefValIDs.erase(I);
3306 }
3307 }
3308
Craig Topper2617dcc2014-04-15 06:32:26 +00003309 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003310 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3311 else // Move the forward-reference to the correct spot in the module.
3312 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3313
3314 if (FunctionName.empty())
3315 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003316
Chris Lattnerac161bf2009-01-02 07:01:27 +00003317 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3318 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003319 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320 Fn->setCallingConv(CC);
3321 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003322 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 Fn->setAlignment(Alignment);
3324 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003325 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003326 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003327 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003328 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003329 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003330
Chris Lattnerac161bf2009-01-02 07:01:27 +00003331 // Add all of the arguments we parsed to the function.
3332 Function::arg_iterator ArgIt = Fn->arg_begin();
3333 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3334 // If the argument has a name, insert it into the argument symbol table.
3335 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003336
Chris Lattnerac161bf2009-01-02 07:01:27 +00003337 // Set the name, if it conflicted, it will be auto-renamed.
3338 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003339
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003340 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003341 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3342 ArgList[i].Name + "'");
3343 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003344
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003345 if (isDefine)
3346 return false;
3347
Robin Morisset039781e2014-08-29 21:53:01 +00003348 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003349 ValID ID;
3350 if (FunctionName.empty()) {
3351 ID.Kind = ValID::t_GlobalID;
3352 ID.UIntVal = NumberedVals.size() - 1;
3353 } else {
3354 ID.Kind = ValID::t_GlobalName;
3355 ID.StrVal = FunctionName;
3356 }
3357 auto Blocks = ForwardRefBlockAddresses.find(ID);
3358 if (Blocks != ForwardRefBlockAddresses.end())
3359 return Error(Blocks->first.Loc,
3360 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003361 return false;
3362}
3363
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003364bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3365 ValID ID;
3366 if (FunctionNumber == -1) {
3367 ID.Kind = ValID::t_GlobalName;
3368 ID.StrVal = F.getName();
3369 } else {
3370 ID.Kind = ValID::t_GlobalID;
3371 ID.UIntVal = FunctionNumber;
3372 }
3373
3374 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3375 if (Blocks == P.ForwardRefBlockAddresses.end())
3376 return false;
3377
3378 for (const auto &I : Blocks->second) {
3379 const ValID &BBID = I.first;
3380 GlobalValue *GV = I.second;
3381
3382 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3383 "Expected local id or name");
3384 BasicBlock *BB;
3385 if (BBID.Kind == ValID::t_LocalName)
3386 BB = GetBB(BBID.StrVal, BBID.Loc);
3387 else
3388 BB = GetBB(BBID.UIntVal, BBID.Loc);
3389 if (!BB)
3390 return P.Error(BBID.Loc, "referenced value is not a basic block");
3391
3392 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3393 GV->eraseFromParent();
3394 }
3395
3396 P.ForwardRefBlockAddresses.erase(Blocks);
3397 return false;
3398}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003399
3400/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003401/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003402bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003403 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003404 return TokError("expected '{' in function body");
3405 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003406
Chris Lattner3432c622009-10-28 03:39:23 +00003407 int FunctionNumber = -1;
3408 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003409
Chris Lattner3432c622009-10-28 03:39:23 +00003410 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003411
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003412 // Resolve block addresses and allow basic blocks to be forward-declared
3413 // within this function.
3414 if (PFS.resolveForwardRefBlockAddresses())
3415 return true;
3416 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3417
Chris Lattnerbbddd962010-01-09 19:20:07 +00003418 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003419 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003420 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003421
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003422 while (Lex.getKind() != lltok::rbrace &&
3423 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003424 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003425
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003426 while (Lex.getKind() != lltok::rbrace)
3427 if (ParseUseListOrder(&PFS))
3428 return true;
3429
Chris Lattnerac161bf2009-01-02 07:01:27 +00003430 // Eat the }.
3431 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003432
Chris Lattnerac161bf2009-01-02 07:01:27 +00003433 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003434 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003435}
3436
3437/// ParseBasicBlock
3438/// ::= LabelStr? Instruction*
3439bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3440 // If this basic block starts out with a name, remember it.
3441 std::string Name;
3442 LocTy NameLoc = Lex.getLoc();
3443 if (Lex.getKind() == lltok::LabelStr) {
3444 Name = Lex.getStrVal();
3445 Lex.Lex();
3446 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003447
Chris Lattnerac161bf2009-01-02 07:01:27 +00003448 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003449 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003450
Chris Lattnerac161bf2009-01-02 07:01:27 +00003451 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003452
Chris Lattnerac161bf2009-01-02 07:01:27 +00003453 // Parse the instructions in this block until we get a terminator.
3454 Instruction *Inst;
3455 do {
3456 // This instruction may have three possibilities for a name: a) none
3457 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3458 LocTy NameLoc = Lex.getLoc();
3459 int NameID = -1;
3460 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003461
Chris Lattnerac161bf2009-01-02 07:01:27 +00003462 if (Lex.getKind() == lltok::LocalVarID) {
3463 NameID = Lex.getUIntVal();
3464 Lex.Lex();
3465 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3466 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003467 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003468 NameStr = Lex.getStrVal();
3469 Lex.Lex();
3470 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3471 return true;
3472 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003473
Chris Lattner77b89dc2009-12-30 05:23:43 +00003474 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003475 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003476 case InstError: return true;
3477 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003478 BB->getInstList().push_back(Inst);
3479
Chris Lattner77b89dc2009-12-30 05:23:43 +00003480 // With a normal result, we check to see if the instruction is followed by
3481 // a comma and metadata.
3482 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003483 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003484 return true;
3485 break;
3486 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003487 BB->getInstList().push_back(Inst);
3488
Chris Lattner77b89dc2009-12-30 05:23:43 +00003489 // If the instruction parser ate an extra comma at the end of it, it
3490 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003491 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003492 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003493 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003494 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003495
Chris Lattnerac161bf2009-01-02 07:01:27 +00003496 // Set the name on the instruction.
3497 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3498 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003499
Chris Lattnerac161bf2009-01-02 07:01:27 +00003500 return false;
3501}
3502
3503//===----------------------------------------------------------------------===//
3504// Instruction Parsing.
3505//===----------------------------------------------------------------------===//
3506
3507/// ParseInstruction - Parse one of the many different instructions.
3508///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003509int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3510 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003511 lltok::Kind Token = Lex.getKind();
3512 if (Token == lltok::Eof)
3513 return TokError("found end of file when expecting more instructions");
3514 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003515 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003516 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003517
Chris Lattnerac161bf2009-01-02 07:01:27 +00003518 switch (Token) {
3519 default: return Error(Loc, "expected instruction opcode");
3520 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003521 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003522 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3523 case lltok::kw_br: return ParseBr(Inst, PFS);
3524 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003525 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003526 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003527 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003528 // Binary Operators.
3529 case lltok::kw_add:
3530 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003531 case lltok::kw_mul:
3532 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003533 bool NUW = EatIfPresent(lltok::kw_nuw);
3534 bool NSW = EatIfPresent(lltok::kw_nsw);
3535 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003536
Chris Lattnera676c0f2011-02-07 16:40:21 +00003537 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003538
Chris Lattnera676c0f2011-02-07 16:40:21 +00003539 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3540 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3541 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003542 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003543 case lltok::kw_fadd:
3544 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003545 case lltok::kw_fmul:
3546 case lltok::kw_fdiv:
3547 case lltok::kw_frem: {
3548 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3549 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3550 if (Res != 0)
3551 return Res;
3552 if (FMF.any())
3553 Inst->setFastMathFlags(FMF);
3554 return 0;
3555 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003556
Chris Lattner35315d02011-02-06 21:44:57 +00003557 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003558 case lltok::kw_udiv:
3559 case lltok::kw_lshr:
3560 case lltok::kw_ashr: {
3561 bool Exact = EatIfPresent(lltok::kw_exact);
3562
3563 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3564 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3565 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003566 }
3567
Chris Lattnerac161bf2009-01-02 07:01:27 +00003568 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003569 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003570 case lltok::kw_and:
3571 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003572 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003573 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003574 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003575 // Casts.
3576 case lltok::kw_trunc:
3577 case lltok::kw_zext:
3578 case lltok::kw_sext:
3579 case lltok::kw_fptrunc:
3580 case lltok::kw_fpext:
3581 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003582 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003583 case lltok::kw_uitofp:
3584 case lltok::kw_sitofp:
3585 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003586 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003587 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003588 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003589 // Other.
3590 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003591 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003592 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3593 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3594 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3595 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003596 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003597 // Call.
3598 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3599 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3600 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003601 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003602 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003603 case lltok::kw_load: return ParseLoad(Inst, PFS);
3604 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003605 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3606 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003607 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003608 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3609 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3610 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3611 }
3612}
3613
3614/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3615bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003616 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003617 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003618 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003619 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3620 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3621 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3622 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3623 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3624 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3625 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3626 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3627 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3628 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3629 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3630 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3631 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3632 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3633 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3634 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3635 }
3636 } else {
3637 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003638 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003639 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3640 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3641 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3642 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3643 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3644 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3645 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3646 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3647 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3648 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3649 }
3650 }
3651 Lex.Lex();
3652 return false;
3653}
3654
3655//===----------------------------------------------------------------------===//
3656// Terminator Instructions.
3657//===----------------------------------------------------------------------===//
3658
3659/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003660/// ::= 'ret' void (',' !dbg, !1)*
3661/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003662bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003663 PerFunctionState &PFS) {
3664 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003665 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003666 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003667
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003668 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003669
Chris Lattnerfdd87902009-10-05 05:54:46 +00003670 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003671 if (!ResType->isVoidTy())
3672 return Error(TypeLoc, "value doesn't match function result type '" +
3673 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003674
Owen Anderson55f1c092009-08-13 21:58:54 +00003675 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003676 return false;
3677 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003678
Chris Lattnerac161bf2009-01-02 07:01:27 +00003679 Value *RV;
3680 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003681
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003682 if (ResType != RV->getType())
3683 return Error(TypeLoc, "value doesn't match function result type '" +
3684 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003685
Owen Anderson55f1c092009-08-13 21:58:54 +00003686 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003687 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003688}
3689
3690
3691/// ParseBr
3692/// ::= 'br' TypeAndValue
3693/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3694bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3695 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003696 Value *Op0;
3697 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003698 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003699
Chris Lattnerac161bf2009-01-02 07:01:27 +00003700 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3701 Inst = BranchInst::Create(BB);
3702 return false;
3703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003704
Owen Anderson55f1c092009-08-13 21:58:54 +00003705 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003706 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003707
Chris Lattnerac161bf2009-01-02 07:01:27 +00003708 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003709 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003710 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003711 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003712 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003713
Chris Lattner3ed871f2009-10-27 19:13:16 +00003714 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003715 return false;
3716}
3717
3718/// ParseSwitch
3719/// Instruction
3720/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3721/// JumpTable
3722/// ::= (TypeAndValue ',' TypeAndValue)*
3723bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3724 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003725 Value *Cond;
3726 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003727 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3728 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003729 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003730 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3731 return true;
3732
Duncan Sands19d0b472010-02-16 11:11:14 +00003733 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003734 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003735
Chris Lattnerac161bf2009-01-02 07:01:27 +00003736 // Parse the jump table pairs.
3737 SmallPtrSet<Value*, 32> SeenCases;
3738 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3739 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003740 Value *Constant;
3741 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003742
Chris Lattnerac161bf2009-01-02 07:01:27 +00003743 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3744 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003745 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003746 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003747
David Blaikie70573dc2014-11-19 07:49:26 +00003748 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003749 return Error(CondLoc, "duplicate case value in switch");
3750 if (!isa<ConstantInt>(Constant))
3751 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003752
Chris Lattner3ed871f2009-10-27 19:13:16 +00003753 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003754 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003755
Chris Lattnerac161bf2009-01-02 07:01:27 +00003756 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003757
Chris Lattner3ed871f2009-10-27 19:13:16 +00003758 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3760 SI->addCase(Table[i].first, Table[i].second);
3761 Inst = SI;
3762 return false;
3763}
3764
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003765/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003766/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003767/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3768bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003769 LocTy AddrLoc;
3770 Value *Address;
3771 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003772 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3773 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003774 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003775
Duncan Sands19d0b472010-02-16 11:11:14 +00003776 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003777 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003778
Chris Lattner3ed871f2009-10-27 19:13:16 +00003779 // Parse the destination list.
3780 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003781
Chris Lattner3ed871f2009-10-27 19:13:16 +00003782 if (Lex.getKind() != lltok::rsquare) {
3783 BasicBlock *DestBB;
3784 if (ParseTypeAndBasicBlock(DestBB, PFS))
3785 return true;
3786 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003787
Chris Lattner3ed871f2009-10-27 19:13:16 +00003788 while (EatIfPresent(lltok::comma)) {
3789 if (ParseTypeAndBasicBlock(DestBB, PFS))
3790 return true;
3791 DestList.push_back(DestBB);
3792 }
3793 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003794
Chris Lattner3ed871f2009-10-27 19:13:16 +00003795 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3796 return true;
3797
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003798 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003799 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3800 IBI->addDestination(DestList[i]);
3801 Inst = IBI;
3802 return false;
3803}
3804
3805
Chris Lattnerac161bf2009-01-02 07:01:27 +00003806/// ParseInvoke
3807/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3808/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3809bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3810 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003811 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003812 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003813 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003814 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003815 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003816 LocTy RetTypeLoc;
3817 ValID CalleeID;
3818 SmallVector<ParamInfo, 16> ArgList;
3819
Chris Lattner3ed871f2009-10-27 19:13:16 +00003820 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003821 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003822 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003823 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003824 ParseValID(CalleeID) ||
3825 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003826 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3827 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003828 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003829 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003830 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003831 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003832 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003833
Chris Lattnerac161bf2009-01-02 07:01:27 +00003834 // If RetType is a non-function pointer type, then this is the short syntax
3835 // for the call, which means that RetType is just the return type. Infer the
3836 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003837 PointerType *PFTy = nullptr;
3838 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003839 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3840 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3841 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003842 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3844 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003845
Chris Lattnerac161bf2009-01-02 07:01:27 +00003846 if (!FunctionType::isValidReturnType(RetType))
3847 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003848
Owen Anderson4056ca92009-07-29 22:17:13 +00003849 Ty = FunctionType::get(RetType, ParamTypes, false);
3850 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003852
Chris Lattnerac161bf2009-01-02 07:01:27 +00003853 // Look up the callee.
3854 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003855 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003856
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003857 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003858 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003859 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003860 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3861 AttributeSet::ReturnIndex,
3862 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003863
Chris Lattnerac161bf2009-01-02 07:01:27 +00003864 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003865
Chris Lattnerac161bf2009-01-02 07:01:27 +00003866 // Loop through FunctionType's arguments and ensure they are specified
3867 // correctly. Also, gather any parameter attributes.
3868 FunctionType::param_iterator I = Ty->param_begin();
3869 FunctionType::param_iterator E = Ty->param_end();
3870 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003871 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003872 if (I != E) {
3873 ExpectedTy = *I++;
3874 } else if (!Ty->isVarArg()) {
3875 return Error(ArgList[i].Loc, "too many arguments specified");
3876 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003877
Chris Lattnerac161bf2009-01-02 07:01:27 +00003878 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3879 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003880 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003881 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003882 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3883 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003884 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3885 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003886 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003887
Chris Lattnerac161bf2009-01-02 07:01:27 +00003888 if (I != E)
3889 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003890
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003891 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003892 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3893 AttributeSet::FunctionIndex,
3894 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003895
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003896 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003897 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003898
Jay Foad5bd375a2011-07-15 08:37:34 +00003899 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003900 II->setCallingConv(CC);
3901 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003902 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003903 Inst = II;
3904 return false;
3905}
3906
Bill Wendlingf891bf82011-07-31 06:30:59 +00003907/// ParseResume
3908/// ::= 'resume' TypeAndValue
3909bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3910 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003911 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3912 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003913
Bill Wendlingf891bf82011-07-31 06:30:59 +00003914 ResumeInst *RI = ResumeInst::Create(Exn);
3915 Inst = RI;
3916 return false;
3917}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003918
3919//===----------------------------------------------------------------------===//
3920// Binary Operators.
3921//===----------------------------------------------------------------------===//
3922
3923/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003924/// ::= ArithmeticOps TypeAndValue ',' Value
3925///
3926/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3927/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003928bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003929 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003930 LocTy Loc; Value *LHS, *RHS;
3931 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3932 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3933 ParseValue(LHS->getType(), RHS, PFS))
3934 return true;
3935
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003936 bool Valid;
3937 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003938 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003939 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003940 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3941 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003942 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003943 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3944 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003945 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003946
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003947 if (!Valid)
3948 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003949
Chris Lattnerac161bf2009-01-02 07:01:27 +00003950 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3951 return false;
3952}
3953
3954/// ParseLogical
3955/// ::= ArithmeticOps TypeAndValue ',' Value {
3956bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3957 unsigned Opc) {
3958 LocTy Loc; Value *LHS, *RHS;
3959 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3960 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3961 ParseValue(LHS->getType(), RHS, PFS))
3962 return true;
3963
Duncan Sands9dff9be2010-02-15 16:12:20 +00003964 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003965 return Error(Loc,"instruction requires integer or integer vector operands");
3966
3967 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3968 return false;
3969}
3970
3971
3972/// ParseCompare
3973/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3974/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003975bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3976 unsigned Opc) {
3977 // Parse the integer/fp comparison predicate.
3978 LocTy Loc;
3979 unsigned Pred;
3980 Value *LHS, *RHS;
3981 if (ParseCmpPredicate(Pred, Opc) ||
3982 ParseTypeAndValue(LHS, Loc, PFS) ||
3983 ParseToken(lltok::comma, "expected ',' after compare value") ||
3984 ParseValue(LHS->getType(), RHS, PFS))
3985 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003986
Chris Lattnerac161bf2009-01-02 07:01:27 +00003987 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003988 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003989 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003990 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003991 } else {
3992 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003993 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003994 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003995 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003996 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003997 }
3998 return false;
3999}
4000
4001//===----------------------------------------------------------------------===//
4002// Other Instructions.
4003//===----------------------------------------------------------------------===//
4004
4005
4006/// ParseCast
4007/// ::= CastOpc TypeAndValue 'to' Type
4008bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4009 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004010 LocTy Loc;
4011 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004012 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013 if (ParseTypeAndValue(Op, Loc, PFS) ||
4014 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4015 ParseType(DestTy))
4016 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004017
Chris Lattner89d856e2009-03-01 00:53:13 +00004018 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4019 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004020 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004021 getTypeString(Op->getType()) + "' to '" +
4022 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004023 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004024 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4025 return false;
4026}
4027
4028/// ParseSelect
4029/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4030bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4031 LocTy Loc;
4032 Value *Op0, *Op1, *Op2;
4033 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4034 ParseToken(lltok::comma, "expected ',' after select condition") ||
4035 ParseTypeAndValue(Op1, PFS) ||
4036 ParseToken(lltok::comma, "expected ',' after select value") ||
4037 ParseTypeAndValue(Op2, PFS))
4038 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004039
Chris Lattnerac161bf2009-01-02 07:01:27 +00004040 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4041 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004042
Chris Lattnerac161bf2009-01-02 07:01:27 +00004043 Inst = SelectInst::Create(Op0, Op1, Op2);
4044 return false;
4045}
4046
Chris Lattnerb55ab542009-01-05 08:18:44 +00004047/// ParseVA_Arg
4048/// ::= 'va_arg' TypeAndValue ',' Type
4049bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004050 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004051 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004052 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 if (ParseTypeAndValue(Op, PFS) ||
4054 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004055 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004057
Chris Lattnerb55ab542009-01-05 08:18:44 +00004058 if (!EltTy->isFirstClassType())
4059 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004060
4061 Inst = new VAArgInst(Op, EltTy);
4062 return false;
4063}
4064
4065/// ParseExtractElement
4066/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4067bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4068 LocTy Loc;
4069 Value *Op0, *Op1;
4070 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4071 ParseToken(lltok::comma, "expected ',' after extract value") ||
4072 ParseTypeAndValue(Op1, PFS))
4073 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004074
Chris Lattnerac161bf2009-01-02 07:01:27 +00004075 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4076 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004077
Eric Christopherc9742252009-07-25 02:28:41 +00004078 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004079 return false;
4080}
4081
4082/// ParseInsertElement
4083/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4084bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4085 LocTy Loc;
4086 Value *Op0, *Op1, *Op2;
4087 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4088 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4089 ParseTypeAndValue(Op1, PFS) ||
4090 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4091 ParseTypeAndValue(Op2, PFS))
4092 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004093
Chris Lattnerac161bf2009-01-02 07:01:27 +00004094 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004095 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004096
Chris Lattnerac161bf2009-01-02 07:01:27 +00004097 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4098 return false;
4099}
4100
4101/// ParseShuffleVector
4102/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4103bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4104 LocTy Loc;
4105 Value *Op0, *Op1, *Op2;
4106 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4107 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4108 ParseTypeAndValue(Op1, PFS) ||
4109 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4110 ParseTypeAndValue(Op2, PFS))
4111 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004112
Chris Lattnerac161bf2009-01-02 07:01:27 +00004113 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004114 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004115
Chris Lattnerac161bf2009-01-02 07:01:27 +00004116 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4117 return false;
4118}
4119
4120/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004121/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004122int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004123 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004124 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004125
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004126 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004127 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4128 ParseValue(Ty, Op0, PFS) ||
4129 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004130 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004131 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4132 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004133
Chris Lattnerf4f03422009-12-30 05:27:33 +00004134 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004135 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4136 while (1) {
4137 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004138
Chris Lattner3822f632009-01-02 08:05:26 +00004139 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004140 break;
4141
Chris Lattnerf4f03422009-12-30 05:27:33 +00004142 if (Lex.getKind() == lltok::MetadataVar) {
4143 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004144 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004145 }
Devang Patel8f842d32009-10-16 18:45:49 +00004146
Chris Lattner3822f632009-01-02 08:05:26 +00004147 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004148 ParseValue(Ty, Op0, PFS) ||
4149 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004150 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004151 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4152 return true;
4153 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004154
Chris Lattnerac161bf2009-01-02 07:01:27 +00004155 if (!Ty->isFirstClassType())
4156 return Error(TypeLoc, "phi node must have first class type");
4157
Jay Foad52131342011-03-30 11:28:46 +00004158 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004159 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4160 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4161 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004162 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004163}
4164
Bill Wendlingfae14752011-08-12 20:24:12 +00004165/// ParseLandingPad
4166/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4167/// Clause
4168/// ::= 'catch' TypeAndValue
4169/// ::= 'filter'
4170/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4171bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004172 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004173 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004174
4175 if (ParseType(Ty, TyLoc) ||
4176 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4177 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4178 return true;
4179
4180 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4181 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4182
4183 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4184 LandingPadInst::ClauseType CT;
4185 if (EatIfPresent(lltok::kw_catch))
4186 CT = LandingPadInst::Catch;
4187 else if (EatIfPresent(lltok::kw_filter))
4188 CT = LandingPadInst::Filter;
4189 else
4190 return TokError("expected 'catch' or 'filter' clause type");
4191
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004192 Value *V;
4193 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004194 if (ParseTypeAndValue(V, VLoc, PFS)) {
4195 delete LP;
4196 return true;
4197 }
4198
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004199 // A 'catch' type expects a non-array constant. A filter clause expects an
4200 // array constant.
4201 if (CT == LandingPadInst::Catch) {
4202 if (isa<ArrayType>(V->getType()))
4203 Error(VLoc, "'catch' clause has an invalid type");
4204 } else {
4205 if (!isa<ArrayType>(V->getType()))
4206 Error(VLoc, "'filter' clause has an invalid type");
4207 }
4208
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004209 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004210 }
4211
4212 Inst = LP;
4213 return false;
4214}
4215
Chris Lattnerac161bf2009-01-02 07:01:27 +00004216/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004217/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4218/// ParameterList OptionalAttrs
4219/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4220/// ParameterList OptionalAttrs
4221/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222/// ParameterList OptionalAttrs
4223bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004224 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004225 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004226 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004227 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004228 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004229 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004230 LocTy RetTypeLoc;
4231 ValID CalleeID;
4232 SmallVector<ParamInfo, 16> ArgList;
4233 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004234
Reid Kleckner5772b772014-04-24 20:14:34 +00004235 if ((TCK != CallInst::TCK_None &&
4236 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004237 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004238 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004239 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004240 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004241 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4242 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004243 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004244 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004245 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004246
Chris Lattnerac161bf2009-01-02 07:01:27 +00004247 // If RetType is a non-function pointer type, then this is the short syntax
4248 // for the call, which means that RetType is just the return type. Infer the
4249 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004250 PointerType *PFTy = nullptr;
4251 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004252 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4253 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4254 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004255 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004256 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4257 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004258
Chris Lattnerac161bf2009-01-02 07:01:27 +00004259 if (!FunctionType::isValidReturnType(RetType))
4260 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004261
Owen Anderson4056ca92009-07-29 22:17:13 +00004262 Ty = FunctionType::get(RetType, ParamTypes, false);
4263 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004264 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004265
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 // Look up the callee.
4267 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004268 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004269
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004270 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004271 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004272 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004273 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4274 AttributeSet::ReturnIndex,
4275 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004276
Chris Lattnerac161bf2009-01-02 07:01:27 +00004277 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004278
Chris Lattnerac161bf2009-01-02 07:01:27 +00004279 // Loop through FunctionType's arguments and ensure they are specified
4280 // correctly. Also, gather any parameter attributes.
4281 FunctionType::param_iterator I = Ty->param_begin();
4282 FunctionType::param_iterator E = Ty->param_end();
4283 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004284 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004285 if (I != E) {
4286 ExpectedTy = *I++;
4287 } else if (!Ty->isVarArg()) {
4288 return Error(ArgList[i].Loc, "too many arguments specified");
4289 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004290
Chris Lattnerac161bf2009-01-02 07:01:27 +00004291 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4292 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004293 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004294 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004295 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4296 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004297 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4298 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004299 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004300
Chris Lattnerac161bf2009-01-02 07:01:27 +00004301 if (I != E)
4302 return Error(CallLoc, "not enough parameters specified for call");
4303
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004304 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004305 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4306 AttributeSet::FunctionIndex,
4307 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004308
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004309 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004310 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004311
Jay Foad5bd375a2011-07-15 08:37:34 +00004312 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004313 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004314 CI->setCallingConv(CC);
4315 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004316 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004317 Inst = CI;
4318 return false;
4319}
4320
4321//===----------------------------------------------------------------------===//
4322// Memory Instructions.
4323//===----------------------------------------------------------------------===//
4324
4325/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004326/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004327int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004328 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004329 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004330 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004331 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004332
4333 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4334
Chris Lattner3822f632009-01-02 08:05:26 +00004335 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004336
Chris Lattnerb2f39502009-12-30 05:44:30 +00004337 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004338 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004339 if (Lex.getKind() == lltok::kw_align) {
4340 if (ParseOptionalAlignment(Alignment)) return true;
4341 } else if (Lex.getKind() == lltok::MetadataVar) {
4342 AteExtraComma = true;
4343 } else {
4344 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4345 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4346 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004347 }
4348 }
4349
Dan Gohman2140a742010-05-28 01:14:11 +00004350 if (Size && !Size->getType()->isIntegerTy())
4351 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004352
Reid Kleckner436c42e2014-01-17 23:58:17 +00004353 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4354 AI->setUsedWithInAlloca(IsInAlloca);
4355 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004356 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357}
4358
4359/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004360/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004361/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004362/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004363int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004364 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004365 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004366 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004367 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004368 AtomicOrdering Ordering = NotAtomic;
4369 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004370
4371 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004372 isAtomic = true;
4373 Lex.Lex();
4374 }
4375
Chris Lattnerbc639292011-11-27 06:56:53 +00004376 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004377 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004378 isVolatile = true;
4379 Lex.Lex();
4380 }
4381
Chris Lattnerb2f39502009-12-30 05:44:30 +00004382 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004383 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004384 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4385 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386
Duncan Sands19d0b472010-02-16 11:11:14 +00004387 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004388 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4389 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004390 if (isAtomic && !Alignment)
4391 return Error(Loc, "atomic load must have explicit non-zero alignment");
4392 if (Ordering == Release || Ordering == AcquireRelease)
4393 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004394
Eli Friedman59b66882011-08-09 23:02:53 +00004395 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004396 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004397}
4398
4399/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004400
4401/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4402/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004403/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004404int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004405 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004406 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004407 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004408 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004409 AtomicOrdering Ordering = NotAtomic;
4410 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004411
4412 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004413 isAtomic = true;
4414 Lex.Lex();
4415 }
4416
Chris Lattnerbc639292011-11-27 06:56:53 +00004417 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004418 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004419 isVolatile = true;
4420 Lex.Lex();
4421 }
4422
Chris Lattnerac161bf2009-01-02 07:01:27 +00004423 if (ParseTypeAndValue(Val, Loc, PFS) ||
4424 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004425 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004426 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004427 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004428 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004429
Duncan Sands19d0b472010-02-16 11:11:14 +00004430 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004431 return Error(PtrLoc, "store operand must be a pointer");
4432 if (!Val->getType()->isFirstClassType())
4433 return Error(Loc, "store operand must be a first class value");
4434 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4435 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004436 if (isAtomic && !Alignment)
4437 return Error(Loc, "atomic store must have explicit non-zero alignment");
4438 if (Ordering == Acquire || Ordering == AcquireRelease)
4439 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004440
Eli Friedman59b66882011-08-09 23:02:53 +00004441 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004442 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004443}
4444
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004445/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004446/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4447/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004448int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004449 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4450 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004451 AtomicOrdering SuccessOrdering = NotAtomic;
4452 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004453 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004454 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004455 bool isWeak = false;
4456
4457 if (EatIfPresent(lltok::kw_weak))
4458 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004459
4460 if (EatIfPresent(lltok::kw_volatile))
4461 isVolatile = true;
4462
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004463 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4464 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4465 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4466 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4467 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004468 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4469 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004470 return true;
4471
Tim Northovere94a5182014-03-11 10:48:52 +00004472 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004473 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004474 if (SuccessOrdering < FailureOrdering)
4475 return TokError("cmpxchg must be at least as ordered on success as failure");
4476 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4477 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004478 if (!Ptr->getType()->isPointerTy())
4479 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4480 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4481 return Error(CmpLoc, "compare value and pointer type do not match");
4482 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4483 return Error(NewLoc, "new value and pointer type do not match");
4484 if (!New->getType()->isIntegerTy())
4485 return Error(NewLoc, "cmpxchg operand must be an integer");
4486 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4487 if (Size < 8 || (Size & (Size - 1)))
4488 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4489 " integer");
4490
Tim Northover420a2162014-06-13 14:24:07 +00004491 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4492 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004493 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004494 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004495 Inst = CXI;
4496 return AteExtraComma ? InstExtraComma : InstNormal;
4497}
4498
4499/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004500/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4501/// 'singlethread'? AtomicOrdering
4502int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004503 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4504 bool AteExtraComma = false;
4505 AtomicOrdering Ordering = NotAtomic;
4506 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004507 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004508 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004509
4510 if (EatIfPresent(lltok::kw_volatile))
4511 isVolatile = true;
4512
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004513 switch (Lex.getKind()) {
4514 default: return TokError("expected binary operation in atomicrmw");
4515 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4516 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4517 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4518 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4519 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4520 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4521 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4522 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4523 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4524 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4525 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4526 }
4527 Lex.Lex(); // Eat the operation.
4528
4529 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4530 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4531 ParseTypeAndValue(Val, ValLoc, PFS) ||
4532 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4533 return true;
4534
4535 if (Ordering == Unordered)
4536 return TokError("atomicrmw cannot be unordered");
4537 if (!Ptr->getType()->isPointerTy())
4538 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4539 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4540 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4541 if (!Val->getType()->isIntegerTy())
4542 return Error(ValLoc, "atomicrmw operand must be an integer");
4543 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4544 if (Size < 8 || (Size & (Size - 1)))
4545 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4546 " integer");
4547
4548 AtomicRMWInst *RMWI =
4549 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4550 RMWI->setVolatile(isVolatile);
4551 Inst = RMWI;
4552 return AteExtraComma ? InstExtraComma : InstNormal;
4553}
4554
Eli Friedmanfee02c62011-07-25 23:16:38 +00004555/// ParseFence
4556/// ::= 'fence' 'singlethread'? AtomicOrdering
4557int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4558 AtomicOrdering Ordering = NotAtomic;
4559 SynchronizationScope Scope = CrossThread;
4560 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4561 return true;
4562
4563 if (Ordering == Unordered)
4564 return TokError("fence cannot be unordered");
4565 if (Ordering == Monotonic)
4566 return TokError("fence cannot be monotonic");
4567
4568 Inst = new FenceInst(Context, Ordering, Scope);
4569 return InstNormal;
4570}
4571
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004573/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004574int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004575 Value *Ptr = nullptr;
4576 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004577 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004578
Dan Gohman16cbbe42009-07-29 15:58:36 +00004579 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004580
Chris Lattner3822f632009-01-02 08:05:26 +00004581 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004582
Eli Benderskyd9806682013-04-22 17:03:42 +00004583 Type *BaseType = Ptr->getType();
4584 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4585 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004586 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004587
Chris Lattnerac161bf2009-01-02 07:01:27 +00004588 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004589 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004590 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004591 if (Lex.getKind() == lltok::MetadataVar) {
4592 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004593 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004594 }
Chris Lattner3822f632009-01-02 08:05:26 +00004595 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004596 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004598 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4599 return Error(EltLoc, "getelementptr index type missmatch");
4600 if (Val->getType()->isVectorTy()) {
4601 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4602 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4603 if (ValNumEl != PtrNumEl)
4604 return Error(EltLoc,
4605 "getelementptr vector index has a wrong number of elements");
4606 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004607 Indices.push_back(Val);
4608 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004609
Eli Benderskyd9806682013-04-22 17:03:42 +00004610 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4611 return Error(Loc, "base element of getelementptr must be sized");
4612
4613 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004615 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004616 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004617 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004618 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004619}
4620
4621/// ParseExtractValue
4622/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004623int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004624 Value *Val; LocTy Loc;
4625 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004626 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004628 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629 return true;
4630
Chris Lattner392be582010-02-12 20:49:41 +00004631 if (!Val->getType()->isAggregateType())
4632 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004633
Jay Foad57aa6362011-07-13 10:26:04 +00004634 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004635 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004636 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004637 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004638}
4639
4640/// ParseInsertValue
4641/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004642int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 Value *Val0, *Val1; LocTy Loc0, Loc1;
4644 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004645 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4647 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4648 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004649 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004650 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004651
Chris Lattner392be582010-02-12 20:49:41 +00004652 if (!Val0->getType()->isAggregateType())
4653 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004654
Jay Foad57aa6362011-07-13 10:26:04 +00004655 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004657 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004658 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659}
Nick Lewycky49f89192009-04-04 07:22:01 +00004660
4661//===----------------------------------------------------------------------===//
4662// Embedded metadata.
4663//===----------------------------------------------------------------------===//
4664
4665/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004666/// ::= Element (',' Element)*
4667/// Element
4668/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004669bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004670 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004671 // Check for an empty list.
4672 if (Lex.getKind() == lltok::rbrace)
4673 return false;
4674
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004675 bool IsLocal = false;
Nick Lewycky49f89192009-04-04 07:22:01 +00004676 do {
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004677 if (IsLocal)
4678 return TokError("unexpected operand after function-local metadata");
4679
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004680 // Null is a special case since it is typeless.
4681 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004682 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004683 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004684 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004685
Craig Topper2617dcc2014-04-15 06:32:26 +00004686 Value *V = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004687 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004688 Elts.push_back(V);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004689
4690 if (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())
4691 return TokError("unexpected nested function-local metadata");
4692 if (!V->getType()->isMetadataTy() && !isa<Constant>(V)) {
4693 assert(PFS && "Unexpected function-local metadata without PFS");
4694 if (Elts.size() > 1)
4695 return TokError("unexpected function-local metadata");
4696 IsLocal = true;
4697 }
Nick Lewycky49f89192009-04-04 07:22:01 +00004698 } while (EatIfPresent(lltok::comma));
4699
4700 return false;
4701}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004702
4703//===----------------------------------------------------------------------===//
4704// Use-list order directives.
4705//===----------------------------------------------------------------------===//
4706bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4707 SMLoc Loc) {
4708 if (V->use_empty())
4709 return Error(Loc, "value has no uses");
4710
4711 unsigned NumUses = 0;
4712 SmallDenseMap<const Use *, unsigned, 16> Order;
4713 for (const Use &U : V->uses()) {
4714 if (++NumUses > Indexes.size())
4715 break;
4716 Order[&U] = Indexes[NumUses - 1];
4717 }
4718 if (NumUses < 2)
4719 return Error(Loc, "value only has one use");
4720 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4721 return Error(Loc, "wrong number of indexes, expected " +
4722 Twine(std::distance(V->use_begin(), V->use_end())));
4723
4724 V->sortUseList([&](const Use &L, const Use &R) {
4725 return Order.lookup(&L) < Order.lookup(&R);
4726 });
4727 return false;
4728}
4729
4730/// ParseUseListOrderIndexes
4731/// ::= '{' uint32 (',' uint32)+ '}'
4732bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4733 SMLoc Loc = Lex.getLoc();
4734 if (ParseToken(lltok::lbrace, "expected '{' here"))
4735 return true;
4736 if (Lex.getKind() == lltok::rbrace)
4737 return Lex.Error("expected non-empty list of uselistorder indexes");
4738
4739 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4740 // indexes should be distinct numbers in the range [0, size-1], and should
4741 // not be in order.
4742 unsigned Offset = 0;
4743 unsigned Max = 0;
4744 bool IsOrdered = true;
4745 assert(Indexes.empty() && "Expected empty order vector");
4746 do {
4747 unsigned Index;
4748 if (ParseUInt32(Index))
4749 return true;
4750
4751 // Update consistency checks.
4752 Offset += Index - Indexes.size();
4753 Max = std::max(Max, Index);
4754 IsOrdered &= Index == Indexes.size();
4755
4756 Indexes.push_back(Index);
4757 } while (EatIfPresent(lltok::comma));
4758
4759 if (ParseToken(lltok::rbrace, "expected '}' here"))
4760 return true;
4761
4762 if (Indexes.size() < 2)
4763 return Error(Loc, "expected >= 2 uselistorder indexes");
4764 if (Offset != 0 || Max >= Indexes.size())
4765 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4766 if (IsOrdered)
4767 return Error(Loc, "expected uselistorder indexes to change the order");
4768
4769 return false;
4770}
4771
4772/// ParseUseListOrder
4773/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4774bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4775 SMLoc Loc = Lex.getLoc();
4776 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4777 return true;
4778
4779 Value *V;
4780 SmallVector<unsigned, 16> Indexes;
4781 if (ParseTypeAndValue(V, PFS) ||
4782 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4783 ParseUseListOrderIndexes(Indexes))
4784 return true;
4785
4786 return sortUseListOrder(V, Indexes, Loc);
4787}
4788
4789/// ParseUseListOrderBB
4790/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4791bool LLParser::ParseUseListOrderBB() {
4792 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4793 SMLoc Loc = Lex.getLoc();
4794 Lex.Lex();
4795
4796 ValID Fn, Label;
4797 SmallVector<unsigned, 16> Indexes;
4798 if (ParseValID(Fn) ||
4799 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4800 ParseValID(Label) ||
4801 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4802 ParseUseListOrderIndexes(Indexes))
4803 return true;
4804
4805 // Check the function.
4806 GlobalValue *GV;
4807 if (Fn.Kind == ValID::t_GlobalName)
4808 GV = M->getNamedValue(Fn.StrVal);
4809 else if (Fn.Kind == ValID::t_GlobalID)
4810 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4811 else
4812 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4813 if (!GV)
4814 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4815 auto *F = dyn_cast<Function>(GV);
4816 if (!F)
4817 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4818 if (F->isDeclaration())
4819 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4820
4821 // Check the basic block.
4822 if (Label.Kind == ValID::t_LocalID)
4823 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4824 if (Label.Kind != ValID::t_LocalName)
4825 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4826 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4827 if (!V)
4828 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4829 if (!isa<BasicBlock>(V))
4830 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4831
4832 return sortUseListOrder(V, Indexes, Loc);
4833}