blob: ac6e0e512fea987f75e4386985be5a65eddccad5 [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"
Chris Lattnerac161bf2009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner229907c2011-07-18 04:54:35 +000030static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000031 std::string Result;
32 raw_string_ostream Tmp(Result);
33 Tmp << *T;
34 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000035}
36
Chris Lattner3822f632009-01-02 08:05:26 +000037/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000038bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000039 // Prime the lexer.
40 Lex.Lex();
41
Chris Lattnerad6f3352009-01-04 20:44:11 +000042 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000044}
45
46/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47/// module.
48bool LLParser::ValidateEndOfModule() {
Chris Lattner8eff0152010-04-01 05:14:45 +000049 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 I != E; ++I) {
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000056
Chris Lattner8eff0152010-04-01 05:14:45 +000057 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000059
Craig Topper2617dcc2014-04-15 06:32:26 +000060 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +000062 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +000063 Twine(SlotNo) + "'");
Chris Lattner8eff0152010-04-01 05:14:45 +000064 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 }
66 }
67 ForwardRefInstMetadata.clear();
68 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +000069
Manman Ren209b17c2013-09-28 00:22:27 +000070 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
72
Bill Wendlingb32b0412013-02-08 06:32:06 +000073 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
76 I != E; ++I) {
77 Value *V = I->first;
78 std::vector<unsigned> &Vec = I->second;
79 AttrBuilder B;
80
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
82 VI != VE; ++VI)
83 B.merge(NumberedAttrBuilders[*VI]);
84
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
90
91 FnAttrs.merge(B);
92
93 // If the alignment was parsed as an attribute, move to the alignment
94 // field.
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
98 }
99
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
103 FnAttrs));
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000110 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
114 FnAttrs));
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000121 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
125 FnAttrs));
126 II->setAttributes(AS);
127 } else {
128 llvm_unreachable("invalid object with forward attribute group reference");
129 }
130 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000131
Chris Lattner3432c622009-10-28 03:39:23 +0000132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
Craig Topper2617dcc2014-04-15 06:32:26 +0000136 Function *TheFn = nullptr;
Chris Lattner3432c622009-10-28 03:39:23 +0000137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000142
Craig Topper2617dcc2014-04-15 06:32:26 +0000143 if (!TheFn)
Chris Lattner3432c622009-10-28 03:39:23 +0000144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000145
Chris Lattner3432c622009-10-28 03:39:23 +0000146 // Resolve all these references.
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000147 if (ResolveForwardRefBlockAddresses(TheFn,
Chris Lattner3432c622009-10-28 03:39:23 +0000148 ForwardRefBlockAddresses.begin()->second,
Craig Topper2617dcc2014-04-15 06:32:26 +0000149 nullptr))
Chris Lattner3432c622009-10-28 03:39:23 +0000150 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000151
Chris Lattner3432c622009-10-28 03:39:23 +0000152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
153 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000154
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
159
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000165
David Majnemerdad0a642014-06-27 18:19:56 +0000166 if (!ForwardRefComdats.empty())
167 return Error(ForwardRefComdats.begin()->second,
168 "use of undefined comdat '$" +
169 ForwardRefComdats.begin()->first + "'");
170
Chris Lattnerac161bf2009-01-02 07:01:27 +0000171 if (!ForwardRefVals.empty())
172 return Error(ForwardRefVals.begin()->second.second,
173 "use of undefined value '@" + ForwardRefVals.begin()->first +
174 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000175
Chris Lattnerac161bf2009-01-02 07:01:27 +0000176 if (!ForwardRefValIDs.empty())
177 return Error(ForwardRefValIDs.begin()->second.second,
178 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000179 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000180
Devang Pateld2541152009-07-08 19:23:54 +0000181 if (!ForwardRefMDNodes.empty())
182 return Error(ForwardRefMDNodes.begin()->second.second,
183 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000184 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000185
Devang Pateld2541152009-07-08 19:23:54 +0000186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 // Look for intrinsic functions and CallInst that need to be upgraded
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
189 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
Manman Ren8b4306c2013-12-02 21:29:56 +0000191 UpgradeDebugInfo(*M);
192
Chris Lattnerac161bf2009-01-02 07:01:27 +0000193 return false;
194}
195
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000196bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
Chris Lattner3432c622009-10-28 03:39:23 +0000197 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
198 PerFunctionState *PFS) {
199 // Loop over all the references, resolving them.
200 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
201 BasicBlock *Res;
Chris Lattneraa99c942009-11-01 01:27:45 +0000202 if (PFS) {
Chris Lattner3432c622009-10-28 03:39:23 +0000203 if (Refs[i].first.Kind == ValID::t_LocalName)
204 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattneraa99c942009-11-01 01:27:45 +0000205 else
Chris Lattner3432c622009-10-28 03:39:23 +0000206 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
207 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
208 return Error(Refs[i].first.Loc,
Chris Lattnera38a4df2009-11-02 18:28:45 +0000209 "cannot take address of numeric label after the function is defined");
Chris Lattner3432c622009-10-28 03:39:23 +0000210 } else {
211 Res = dyn_cast_or_null<BasicBlock>(
212 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
213 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000214
Craig Topper2617dcc2014-04-15 06:32:26 +0000215 if (!Res)
Chris Lattner3432c622009-10-28 03:39:23 +0000216 return Error(Refs[i].first.Loc,
217 "referenced value is not a basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000218
Chris Lattner3432c622009-10-28 03:39:23 +0000219 // Get the BlockAddress for this and update references to use it.
220 BlockAddress *BA = BlockAddress::get(TheFn, Res);
221 Refs[i].second->replaceAllUsesWith(BA);
222 Refs[i].second->eraseFromParent();
223 }
224 return false;
225}
226
227
Chris Lattnerac161bf2009-01-02 07:01:27 +0000228//===----------------------------------------------------------------------===//
229// Top-Level Entities
230//===----------------------------------------------------------------------===//
231
232bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000233 while (1) {
234 switch (Lex.getKind()) {
235 default: return TokError("expected top-level entity");
236 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000237 case lltok::kw_declare: if (ParseDeclare()) return true; break;
238 case lltok::kw_define: if (ParseDefine()) return true; break;
239 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
240 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000241 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000242 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000243 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000244 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000245 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000246 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000247 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000248 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000249
250 // The Global variable production with no name can have many different
251 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000252 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
253 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000254 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000255 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000256 case lltok::kw_internal: // OptionalLinkage
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +0000257 case lltok::kw_linker_private: // Obsolete OptionalLinkage
258 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000259 case lltok::kw_weak: // OptionalLinkage
260 case lltok::kw_weak_odr: // OptionalLinkage
261 case lltok::kw_linkonce: // OptionalLinkage
262 case lltok::kw_linkonce_odr: // OptionalLinkage
263 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000264 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000265 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000266 case lltok::kw_external: // OptionalLinkage
267 case lltok::kw_default: // OptionalVisibility
268 case lltok::kw_hidden: // OptionalVisibility
269 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000270 case lltok::kw_dllimport: // OptionalDLLStorageClass
271 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000272 case lltok::kw_thread_local: // OptionalThreadLocal
273 case lltok::kw_addrspace: // OptionalAddrSpace
274 case lltok::kw_constant: // GlobalType
275 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000276 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000277 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000278 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000279 bool HasLinkage;
280 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000281 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000282 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000283 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000284 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000285 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000286 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000287 return true;
288 break;
289 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000290
291 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 }
293 }
294}
295
296
297/// toplevelentity
298/// ::= 'module' 'asm' STRINGCONSTANT
299bool LLParser::ParseModuleAsm() {
300 assert(Lex.getKind() == lltok::kw_module);
301 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000302
303 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000304 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
305 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000306
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000307 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000308 return false;
309}
310
311/// toplevelentity
312/// ::= 'target' 'triple' '=' STRINGCONSTANT
313/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
314bool LLParser::ParseTargetDefinition() {
315 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000316 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000317 switch (Lex.Lex()) {
318 default: return TokError("unknown target property");
319 case lltok::kw_triple:
320 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000321 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
322 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000324 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return false;
326 case lltok::kw_datalayout:
327 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000328 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
329 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000330 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000331 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 return false;
333 }
334}
335
Bill Wendling706d3d62012-11-28 08:41:48 +0000336/// toplevelentity
337/// ::= 'deplibs' '=' '[' ']'
338/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
339/// FIXME: Remove in 4.0. Currently parse, but ignore.
340bool LLParser::ParseDepLibs() {
341 assert(Lex.getKind() == lltok::kw_deplibs);
342 Lex.Lex();
343 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
344 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
345 return true;
346
347 if (EatIfPresent(lltok::rsquare))
348 return false;
349
350 do {
351 std::string Str;
352 if (ParseStringConstant(Str)) return true;
353 } while (EatIfPresent(lltok::comma));
354
355 return ParseToken(lltok::rsquare, "expected ']' at end of list");
356}
357
Dan Gohman466876b2009-08-12 23:32:33 +0000358/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000359/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000360bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000361 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000362 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000363 Lex.Lex(); // eat LocalVarID;
364
365 if (ParseToken(lltok::equal, "expected '=' after name") ||
366 ParseToken(lltok::kw_type, "expected 'type' after '='"))
367 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000368
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000369 if (TypeID >= NumberedTypes.size())
370 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000371
Craig Topper2617dcc2014-04-15 06:32:26 +0000372 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000373 if (ParseStructDefinition(TypeLoc, "",
374 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000375
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000376 if (!isa<StructType>(Result)) {
377 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
378 if (Entry.first)
379 return Error(TypeLoc, "non-struct types may not be recursive");
380 Entry.first = Result;
381 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000382 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000383
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 return false;
385}
386
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000387
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388/// toplevelentity
389/// ::= LocalVar '=' 'type' type
390bool LLParser::ParseNamedType() {
391 std::string Name = Lex.getStrVal();
392 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000393 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000394
Chris Lattner3822f632009-01-02 08:05:26 +0000395 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000396 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000397 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000398
Craig Topper2617dcc2014-04-15 06:32:26 +0000399 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000400 if (ParseStructDefinition(NameLoc, Name,
401 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403 if (!isa<StructType>(Result)) {
404 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
405 if (Entry.first)
406 return Error(NameLoc, "non-struct types may not be recursive");
407 Entry.first = Result;
408 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000409 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000411 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000412}
413
414
415/// toplevelentity
416/// ::= 'declare' FunctionHeader
417bool LLParser::ParseDeclare() {
418 assert(Lex.getKind() == lltok::kw_declare);
419 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000420
Chris Lattnerac161bf2009-01-02 07:01:27 +0000421 Function *F;
422 return ParseFunctionHeader(F, false);
423}
424
425/// toplevelentity
426/// ::= 'define' FunctionHeader '{' ...
427bool LLParser::ParseDefine() {
428 assert(Lex.getKind() == lltok::kw_define);
429 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000430
Chris Lattnerac161bf2009-01-02 07:01:27 +0000431 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000432 return ParseFunctionHeader(F, true) ||
433 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434}
435
Chris Lattner3822f632009-01-02 08:05:26 +0000436/// ParseGlobalType
437/// ::= 'constant'
438/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000439bool LLParser::ParseGlobalType(bool &IsConstant) {
440 if (Lex.getKind() == lltok::kw_constant)
441 IsConstant = true;
442 else if (Lex.getKind() == lltok::kw_global)
443 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000444 else {
445 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000446 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000447 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448 Lex.Lex();
449 return false;
450}
451
Dan Gohman466876b2009-08-12 23:32:33 +0000452/// ParseUnnamedGlobal:
453/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000454/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
455/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000456/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000457/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
458/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000459bool LLParser::ParseUnnamedGlobal() {
460 unsigned VarID = NumberedVals.size();
461 std::string Name;
462 LocTy NameLoc = Lex.getLoc();
463
464 // Handle the GlobalID form.
465 if (Lex.getKind() == lltok::GlobalID) {
466 if (Lex.getUIntVal() != VarID)
467 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000468 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000469 Lex.Lex(); // eat GlobalID;
470
471 if (ParseToken(lltok::equal, "expected '=' after name"))
472 return true;
473 }
474
475 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000476 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000477 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000478 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000479 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000480 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000481 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000482 ParseOptionalThreadLocal(TLM) ||
483 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000484 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000485
Dan Gohman466876b2009-08-12 23:32:33 +0000486 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000487 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000488 DLLStorageClass, TLM, UnnamedAddr);
489 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
490 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000491}
492
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493/// ParseNamedGlobal:
494/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000495/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
496/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000497bool LLParser::ParseNamedGlobal() {
498 assert(Lex.getKind() == lltok::GlobalVar);
499 LocTy NameLoc = Lex.getLoc();
500 std::string Name = Lex.getStrVal();
501 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Chris Lattnerac161bf2009-01-02 07:01:27 +0000503 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000504 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000505 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000506 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000507 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
508 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000509 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000510 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000511 ParseOptionalThreadLocal(TLM) ||
512 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000513 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000514
Chris Lattnerac161bf2009-01-02 07:01:27 +0000515 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000516 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000517 DLLStorageClass, TLM, UnnamedAddr);
518 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
519 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000520}
521
David Majnemerdad0a642014-06-27 18:19:56 +0000522bool LLParser::parseComdat() {
523 assert(Lex.getKind() == lltok::ComdatVar);
524 std::string Name = Lex.getStrVal();
525 LocTy NameLoc = Lex.getLoc();
526 Lex.Lex();
527
528 if (ParseToken(lltok::equal, "expected '=' here"))
529 return true;
530
531 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
532 return TokError("expected comdat type");
533
534 Comdat::SelectionKind SK;
535 switch (Lex.getKind()) {
536 default:
537 return TokError("unknown selection kind");
538 case lltok::kw_any:
539 SK = Comdat::Any;
540 break;
541 case lltok::kw_exactmatch:
542 SK = Comdat::ExactMatch;
543 break;
544 case lltok::kw_largest:
545 SK = Comdat::Largest;
546 break;
547 case lltok::kw_noduplicates:
548 SK = Comdat::NoDuplicates;
549 break;
550 case lltok::kw_samesize:
551 SK = Comdat::SameSize;
552 break;
553 }
554 Lex.Lex();
555
556 // See if the comdat was forward referenced, if so, use the comdat.
557 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
558 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
559 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
560 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
561
562 Comdat *C;
563 if (I != ComdatSymTab.end())
564 C = &I->second;
565 else
566 C = M->getOrInsertComdat(Name);
567 C->setSelectionKind(SK);
568
569 return false;
570}
571
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000572// MDString:
573// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000574bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000575 std::string Str;
576 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000577 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000578 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000579 return false;
580}
581
582// MDNode:
583// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000584//
585/// This version of ParseMDNodeID returns the slot number and null in the case
586/// of a forward reference.
587bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
588 // !{ ..., !42, ... }
589 if (ParseUInt32(SlotNo)) return true;
590
591 // Check existing MDNode.
Craig Topper2617dcc2014-04-15 06:32:26 +0000592 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +0000593 Result = NumberedMetadata[SlotNo];
594 else
Craig Topper2617dcc2014-04-15 06:32:26 +0000595 Result = nullptr;
Chris Lattner8eff0152010-04-01 05:14:45 +0000596 return false;
597}
598
Chris Lattner6dac02a2009-12-30 04:15:23 +0000599bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000600 // !{ ..., !42, ... }
601 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000602 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000603
Chris Lattner8eff0152010-04-01 05:14:45 +0000604 // If not a forward reference, just return it now.
605 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000606
Chris Lattner8eff0152010-04-01 05:14:45 +0000607 // Otherwise, create MDNode forward reference.
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000608 MDNode *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000609 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000610
Chris Lattnerfc58af22009-12-30 04:51:58 +0000611 if (NumberedMetadata.size() <= MID)
612 NumberedMetadata.resize(MID+1);
613 NumberedMetadata[MID] = FwdNode;
Chris Lattner1797fc72009-12-29 21:53:55 +0000614 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000616}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000617
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000618/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000619/// !foo = !{ !1, !2 }
620bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000621 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000622 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000623 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000624
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000625 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000626 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000627 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000628 return true;
629
Dan Gohman2637cc12010-07-21 23:38:33 +0000630 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000631 if (Lex.getKind() != lltok::rbrace)
632 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000633 if (ParseToken(lltok::exclaim, "Expected '!' here"))
634 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000635
Craig Topper2617dcc2014-04-15 06:32:26 +0000636 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000637 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000638 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000639 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000640
641 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
642 return true;
643
Devang Patelbe626972009-07-29 00:34:02 +0000644 return false;
645}
646
Devang Patel39e64d42009-07-01 19:21:12 +0000647/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000648/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000649bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000650 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000651 Lex.Lex();
652 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000653
654 LocTy TyLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +0000655 Type *Ty = nullptr;
Devang Patele059ba6e2009-07-23 01:07:34 +0000656 SmallVector<Value *, 16> Elts;
Chris Lattner278bc952009-12-29 22:40:21 +0000657 if (ParseUInt32(MetadataID) ||
658 ParseToken(lltok::equal, "expected '=' here") ||
659 ParseType(Ty, TyLoc) ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000660 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner278bc952009-12-29 22:40:21 +0000661 ParseToken(lltok::lbrace, "Expected '{' here") ||
Craig Topper2617dcc2014-04-15 06:32:26 +0000662 ParseMDNodeVector(Elts, nullptr) ||
Chris Lattner278bc952009-12-29 22:40:21 +0000663 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patele059ba6e2009-07-23 01:07:34 +0000664 return true;
665
Jay Foad5514afe2011-04-21 19:59:31 +0000666 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000667
Chris Lattnerfc58af22009-12-30 04:51:58 +0000668 // See if this was forward referenced, if so, handle it.
Chris Lattner218b22f2009-12-29 21:43:58 +0000669 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Pateld2541152009-07-08 19:23:54 +0000670 FI = ForwardRefMDNodes.find(MetadataID);
671 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman16a5d982010-08-20 22:02:26 +0000672 MDNode *Temp = FI->second.first;
673 Temp->replaceAllUsesWith(Init);
674 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000675 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000676
Chris Lattnerfc58af22009-12-30 04:51:58 +0000677 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
678 } else {
679 if (MetadataID >= NumberedMetadata.size())
680 NumberedMetadata.resize(MetadataID+1);
681
Craig Topper2617dcc2014-04-15 06:32:26 +0000682 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000683 return TokError("Metadata id is already used");
684 NumberedMetadata[MetadataID] = Init;
Devang Pateld2541152009-07-08 19:23:54 +0000685 }
686
Devang Patel39e64d42009-07-01 19:21:12 +0000687 return false;
688}
689
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000690static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
691 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
692 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
693}
694
Chris Lattnerac161bf2009-01-02 07:01:27 +0000695/// ParseAlias:
Rafael Espindola5d92ffb2014-06-03 20:25:26 +0000696/// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000697/// OptionalThreadLocal OptionalUnNammedAddr 'alias'
698/// OptionalLinkage Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000699///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000701/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000702///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000703/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000704///
705bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000706 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000707 GlobalVariable::ThreadLocalMode TLM,
708 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709 assert(Lex.getKind() == lltok::kw_alias);
710 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711 LocTy LinkageLoc = Lex.getLoc();
Rafael Espindola78527052013-10-06 15:10:43 +0000712 unsigned L;
713 if (ParseOptionalLinkage(L))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000714 return true;
715
Rafael Espindola78527052013-10-06 15:10:43 +0000716 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
717
Rafael Espindolacaa43562013-10-09 16:07:32 +0000718 if(!GlobalAlias::isValidLinkage(Linkage))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000720
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000721 if (!isValidVisibilityForLinkage(Visibility, L))
722 return Error(LinkageLoc,
723 "symbol with local linkage must have default visibility");
724
Rafael Espindola64c1e182014-06-03 02:41:57 +0000725 Constant *Aliasee;
726 LocTy AliaseeLoc = Lex.getLoc();
727 if (Lex.getKind() != lltok::kw_bitcast &&
728 Lex.getKind() != lltok::kw_getelementptr &&
729 Lex.getKind() != lltok::kw_addrspacecast &&
730 Lex.getKind() != lltok::kw_inttoptr) {
731 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000732 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000733 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000734 // The bitcast dest type is not present, it is implied by the dest type.
735 ValID ID;
736 if (ParseValID(ID))
737 return true;
738 if (ID.Kind != ValID::t_Constant)
739 return Error(AliaseeLoc, "invalid aliasee");
740 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Rafael Espindola64c1e182014-06-03 02:41:57 +0000743 Type *AliaseeType = Aliasee->getType();
744 auto *PTy = dyn_cast<PointerType>(AliaseeType);
745 if (!PTy)
746 return Error(AliaseeLoc, "An alias must have pointer type");
747 Type *Ty = PTy->getElementType();
748 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000749
750 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000751 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000752 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
753 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000754 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000755 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000756 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000757 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000758
Chris Lattnerac161bf2009-01-02 07:01:27 +0000759 // See if this value already exists in the symbol table. If so, it is either
760 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000761 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000762 // See if this was a redefinition. If so, there is no entry in
763 // ForwardRefVals.
764 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
765 I = ForwardRefVals.find(Name);
766 if (I == ForwardRefVals.end())
767 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
768
769 // Otherwise, this was a definition of forward ref. Verify that types
770 // agree.
771 if (Val->getType() != GA->getType())
772 return Error(NameLoc,
773 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
Chris Lattnerac161bf2009-01-02 07:01:27 +0000775 // If they agree, just RAUW the old value with the alias and remove the
776 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000777 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 Val->eraseFromParent();
779 ForwardRefVals.erase(I);
780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000781
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000783 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000784 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000785
Rafael Espindolaaa273822014-05-09 21:49:17 +0000786 // The module owns this now
787 GA.release();
788
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789 return false;
790}
791
792/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000793/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000794/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000795/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000796/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000797/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000798/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000799///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000800/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000801/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000802///
803bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
804 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000805 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000806 GlobalVariable::ThreadLocalMode TLM,
807 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000808 if (!isValidVisibilityForLinkage(Visibility, Linkage))
809 return Error(NameLoc,
810 "symbol with local linkage must have default visibility");
811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000813 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000814 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000815 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Craig Topper2617dcc2014-04-15 06:32:26 +0000817 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000818 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000819 ParseOptionalToken(lltok::kw_externally_initialized,
820 IsExternallyInitialized,
821 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000822 ParseGlobalType(IsConstant) ||
823 ParseType(Ty, TyLoc))
824 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000825
Chris Lattnerac161bf2009-01-02 07:01:27 +0000826 // If the linkage is specified and is external, then no initializer is
827 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000828 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000829 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000830 Linkage != GlobalValue::ExternalLinkage)) {
831 if (ParseGlobalValue(Ty, Init))
832 return true;
833 }
834
Duncan Sands19d0b472010-02-16 11:11:14 +0000835 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000836 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000837
Craig Topper2617dcc2014-04-15 06:32:26 +0000838 GlobalVariable *GV = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839
840 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000841 if (!Name.empty()) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000842 if (GlobalValue *GVal = M->getNamedValue(Name)) {
843 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
844 return Error(NameLoc, "redefinition of global '@" + Name + "'");
845 GV = cast<GlobalVariable>(GVal);
846 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000847 } else {
848 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
849 I = ForwardRefValIDs.find(NumberedVals.size());
850 if (I != ForwardRefValIDs.end()) {
851 GV = cast<GlobalVariable>(I->second.first);
852 ForwardRefValIDs.erase(I);
853 }
854 }
855
Craig Topper2617dcc2014-04-15 06:32:26 +0000856 if (!GV) {
857 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
858 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000859 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000860 } else {
861 if (GV->getType()->getElementType() != Ty)
862 return Error(TyLoc,
863 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000864
Chris Lattnerac161bf2009-01-02 07:01:27 +0000865 // Move the forward-reference to the correct spot in the module.
866 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
867 }
868
869 if (Name.empty())
870 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000871
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872 // Set the parsed properties on the global.
873 if (Init)
874 GV->setInitializer(Init);
875 GV->setConstant(IsConstant);
876 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
877 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000878 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000879 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000880 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000881 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
Chris Lattnerac161bf2009-01-02 07:01:27 +0000883 // Parse attributes on the global.
884 while (Lex.getKind() == lltok::comma) {
885 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000886
Chris Lattnerac161bf2009-01-02 07:01:27 +0000887 if (Lex.getKind() == lltok::kw_section) {
888 Lex.Lex();
889 GV->setSection(Lex.getStrVal());
890 if (ParseToken(lltok::StringConstant, "expected global section string"))
891 return true;
892 } else if (Lex.getKind() == lltok::kw_align) {
893 unsigned Alignment;
894 if (ParseOptionalAlignment(Alignment)) return true;
895 GV->setAlignment(Alignment);
896 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000897 Comdat *C;
898 if (parseOptionalComdat(C))
899 return true;
900 if (C)
901 GV->setComdat(C);
902 else
903 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000904 }
905 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 return false;
908}
909
Bill Wendling63b88192013-02-06 06:52:58 +0000910/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000911/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000912bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000913 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000914 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000915 Lex.Lex();
916
917 assert(Lex.getKind() == lltok::AttrGrpID);
Bill Wendling63b88192013-02-06 06:52:58 +0000918 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000919 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000920 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000921 Lex.Lex();
922
923 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000924 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000925 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000926 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000927 ParseToken(lltok::rbrace, "expected end of attribute group"))
928 return true;
929
Bill Wendlingb32b0412013-02-08 06:32:06 +0000930 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000931 return Error(AttrGrpLoc, "attribute group has no attributes");
932
933 return false;
934}
935
Bill Wendling8b0321d2013-02-08 00:52:31 +0000936/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000937/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000938bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
939 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000940 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000941 bool HaveError = false;
942
943 B.clear();
944
Bill Wendling63b88192013-02-06 06:52:58 +0000945 while (true) {
946 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000947 if (Token == lltok::kw_builtin)
948 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000949 switch (Token) {
950 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000951 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000952 return Error(Lex.getLoc(), "unterminated attribute group");
953 case lltok::rbrace:
954 // Finished.
955 return false;
956
Bill Wendlingb32b0412013-02-08 06:32:06 +0000957 case lltok::AttrGrpID: {
958 // Allow a function to reference an attribute group:
959 //
960 // define void @foo() #1 { ... }
961 if (inAttrGrp)
962 HaveError |=
963 Error(Lex.getLoc(),
964 "cannot have an attribute group reference in an attribute group");
965
966 unsigned AttrGrpNum = Lex.getUIntVal();
967 if (inAttrGrp) break;
968
969 // Save the reference to the attribute group. We'll fill it in later.
970 FwdRefAttrGrps.push_back(AttrGrpNum);
971 break;
972 }
Bill Wendling63b88192013-02-06 06:52:58 +0000973 // Target-dependent attributes:
974 case lltok::StringConstant: {
975 std::string Attr = Lex.getStrVal();
976 Lex.Lex();
977 std::string Val;
978 if (EatIfPresent(lltok::equal) &&
979 ParseStringConstant(Val))
980 return true;
981
982 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000983 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000984 }
985
986 // Target-independent attributes:
987 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000988 // As a hack, we allow function alignment to be initially parsed as an
989 // attribute on a function declaration/definition or added to an attribute
990 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000991 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000992 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000993 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000994 if (ParseToken(lltok::equal, "expected '=' here") ||
995 ParseUInt32(Alignment))
996 return true;
997 } else {
998 if (ParseOptionalAlignment(Alignment))
999 return true;
1000 }
Bill Wendling63b88192013-02-06 06:52:58 +00001001 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001002 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001003 }
1004 case lltok::kw_alignstack: {
1005 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001006 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001007 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001008 if (ParseToken(lltok::equal, "expected '=' here") ||
1009 ParseUInt32(Alignment))
1010 return true;
1011 } else {
1012 if (ParseOptionalStackAlignment(Alignment))
1013 return true;
1014 }
Bill Wendling63b88192013-02-06 06:52:58 +00001015 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001016 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001017 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001018 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +00001019 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +00001020 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001021 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001022 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001023 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1024 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1025 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1026 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1027 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
1028 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1029 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1030 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1031 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1032 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001033 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001034 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1035 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1036 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1037 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1038 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1039 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1040 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1041 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1042 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1043 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1044 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001045
1046 // Error handling.
1047 case lltok::kw_inreg:
1048 case lltok::kw_signext:
1049 case lltok::kw_zeroext:
1050 HaveError |=
1051 Error(Lex.getLoc(),
1052 "invalid use of attribute on a function");
1053 break;
1054 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001055 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +00001056 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001057 case lltok::kw_nest:
1058 case lltok::kw_noalias:
1059 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001060 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001061 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001062 case lltok::kw_sret:
1063 HaveError |=
1064 Error(Lex.getLoc(),
1065 "invalid use of parameter-only attribute on a function");
1066 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001067 }
1068
1069 Lex.Lex();
1070 }
1071}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072
1073//===----------------------------------------------------------------------===//
1074// GlobalValue Reference/Resolution Routines.
1075//===----------------------------------------------------------------------===//
1076
1077/// GetGlobalVal - Get a value with the specified name or ID, creating a
1078/// forward reference record if needed. This can return null if the value
1079/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001080GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001082 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001083 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001085 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001087
Chris Lattnerac161bf2009-01-02 07:01:27 +00001088 // Look this name up in the normal function symbol table.
1089 GlobalValue *Val =
1090 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001091
Chris Lattnerac161bf2009-01-02 07:01:27 +00001092 // If this is a forward reference for the value, see if we already created a
1093 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001094 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001095 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1096 I = ForwardRefVals.find(Name);
1097 if (I != ForwardRefVals.end())
1098 Val = I->second.first;
1099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001100
Chris Lattnerac161bf2009-01-02 07:01:27 +00001101 // If we have the value in the symbol table or fwd-ref table, return it.
1102 if (Val) {
1103 if (Val->getType() == Ty) return Val;
1104 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001105 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001106 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001108
Chris Lattnerac161bf2009-01-02 07:01:27 +00001109 // Otherwise, create a new forward reference for this value and remember it.
1110 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001111 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001112 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001113 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001114 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001115 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1116 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001117 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001118
Chris Lattnerac161bf2009-01-02 07:01:27 +00001119 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1120 return FwdVal;
1121}
1122
Chris Lattner229907c2011-07-18 04:54:35 +00001123GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1124 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001125 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001126 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001127 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001128 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001129
Craig Topper2617dcc2014-04-15 06:32:26 +00001130 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001131
Chris Lattnerac161bf2009-01-02 07:01:27 +00001132 // If this is a forward reference for the value, see if we already created a
1133 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001134 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1136 I = ForwardRefValIDs.find(ID);
1137 if (I != ForwardRefValIDs.end())
1138 Val = I->second.first;
1139 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001140
Chris Lattnerac161bf2009-01-02 07:01:27 +00001141 // If we have the value in the symbol table or fwd-ref table, return it.
1142 if (Val) {
1143 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001144 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001145 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001146 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001148
Chris Lattnerac161bf2009-01-02 07:01:27 +00001149 // Otherwise, create a new forward reference for this value and remember it.
1150 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001151 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001152 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001153 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001154 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001155 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001156
Chris Lattnerac161bf2009-01-02 07:01:27 +00001157 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1158 return FwdVal;
1159}
1160
1161
1162//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001163// Comdat Reference/Resolution Routines.
1164//===----------------------------------------------------------------------===//
1165
1166Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1167 // Look this name up in the comdat symbol table.
1168 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1169 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1170 if (I != ComdatSymTab.end())
1171 return &I->second;
1172
1173 // Otherwise, create a new forward reference for this value and remember it.
1174 Comdat *C = M->getOrInsertComdat(Name);
1175 ForwardRefComdats[Name] = Loc;
1176 return C;
1177}
1178
1179
1180//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181// Helper Routines.
1182//===----------------------------------------------------------------------===//
1183
1184/// ParseToken - If the current token has the specified kind, eat it and return
1185/// success. Otherwise, emit the specified error and return failure.
1186bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1187 if (Lex.getKind() != T)
1188 return TokError(ErrMsg);
1189 Lex.Lex();
1190 return false;
1191}
1192
Chris Lattner3822f632009-01-02 08:05:26 +00001193/// ParseStringConstant
1194/// ::= StringConstant
1195bool LLParser::ParseStringConstant(std::string &Result) {
1196 if (Lex.getKind() != lltok::StringConstant)
1197 return TokError("expected string constant");
1198 Result = Lex.getStrVal();
1199 Lex.Lex();
1200 return false;
1201}
1202
1203/// ParseUInt32
1204/// ::= uint32
1205bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1207 return TokError("expected integer");
1208 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1209 if (Val64 != unsigned(Val64))
1210 return TokError("expected 32-bit integer (too large)");
1211 Val = Val64;
1212 Lex.Lex();
1213 return false;
1214}
1215
Hal Finkelb0407ba2014-07-18 15:51:28 +00001216/// ParseUInt64
1217/// ::= uint64
1218bool LLParser::ParseUInt64(uint64_t &Val) {
1219 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1220 return TokError("expected integer");
1221 Val = Lex.getAPSIntVal().getLimitedValue();
1222 Lex.Lex();
1223 return false;
1224}
1225
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001226/// ParseTLSModel
1227/// := 'localdynamic'
1228/// := 'initialexec'
1229/// := 'localexec'
1230bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1231 switch (Lex.getKind()) {
1232 default:
1233 return TokError("expected localdynamic, initialexec or localexec");
1234 case lltok::kw_localdynamic:
1235 TLM = GlobalVariable::LocalDynamicTLSModel;
1236 break;
1237 case lltok::kw_initialexec:
1238 TLM = GlobalVariable::InitialExecTLSModel;
1239 break;
1240 case lltok::kw_localexec:
1241 TLM = GlobalVariable::LocalExecTLSModel;
1242 break;
1243 }
1244
1245 Lex.Lex();
1246 return false;
1247}
1248
1249/// ParseOptionalThreadLocal
1250/// := /*empty*/
1251/// := 'thread_local'
1252/// := 'thread_local' '(' tlsmodel ')'
1253bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1254 TLM = GlobalVariable::NotThreadLocal;
1255 if (!EatIfPresent(lltok::kw_thread_local))
1256 return false;
1257
1258 TLM = GlobalVariable::GeneralDynamicTLSModel;
1259 if (Lex.getKind() == lltok::lparen) {
1260 Lex.Lex();
1261 return ParseTLSModel(TLM) ||
1262 ParseToken(lltok::rparen, "expected ')' after thread local model");
1263 }
1264 return false;
1265}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001266
1267/// ParseOptionalAddrSpace
1268/// := /*empty*/
1269/// := 'addrspace' '(' uint32 ')'
1270bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1271 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001272 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001273 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001275 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001276 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001277}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001278
Bill Wendling34c2eb22012-12-04 23:40:58 +00001279/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1280bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1281 bool HaveError = false;
1282
1283 B.clear();
1284
1285 while (1) {
1286 lltok::Kind Token = Lex.getKind();
1287 switch (Token) {
1288 default: // End of attributes.
1289 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001290 case lltok::kw_align: {
1291 unsigned Alignment;
1292 if (ParseOptionalAlignment(Alignment))
1293 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001294 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001295 continue;
1296 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001297 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001298 case lltok::kw_dereferenceable: {
1299 uint64_t Bytes;
1300 if (ParseOptionalDereferenceableBytes(Bytes))
1301 return true;
1302 B.addDereferenceableAttr(Bytes);
1303 continue;
1304 }
Reid Klecknera534a382013-12-19 02:14:12 +00001305 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001306 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1307 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1308 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1309 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001310 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001311 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1312 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001313 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001314 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1315 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1316 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001317
Stephen Lin7577ed52013-04-20 13:16:13 +00001318 case lltok::kw_alignstack:
1319 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001320 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001321 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001322 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001323 case lltok::kw_minsize:
1324 case lltok::kw_naked:
1325 case lltok::kw_nobuiltin:
1326 case lltok::kw_noduplicate:
1327 case lltok::kw_noimplicitfloat:
1328 case lltok::kw_noinline:
1329 case lltok::kw_nonlazybind:
1330 case lltok::kw_noredzone:
1331 case lltok::kw_noreturn:
1332 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001333 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001334 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001335 case lltok::kw_returns_twice:
1336 case lltok::kw_sanitize_address:
1337 case lltok::kw_sanitize_memory:
1338 case lltok::kw_sanitize_thread:
1339 case lltok::kw_ssp:
1340 case lltok::kw_sspreq:
1341 case lltok::kw_sspstrong:
1342 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001343 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1344 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001345 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001346
Bill Wendling34c2eb22012-12-04 23:40:58 +00001347 Lex.Lex();
1348 }
1349}
1350
1351/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1352bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1353 bool HaveError = false;
1354
1355 B.clear();
1356
1357 while (1) {
1358 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001359 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001360 default: // End of attributes.
1361 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001362 case lltok::kw_dereferenceable: {
1363 uint64_t Bytes;
1364 if (ParseOptionalDereferenceableBytes(Bytes))
1365 return true;
1366 B.addDereferenceableAttr(Bytes);
1367 continue;
1368 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001369 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1370 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001371 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001372 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1373 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001374
Bill Wendling34c2eb22012-12-04 23:40:58 +00001375 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001376 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001377 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001378 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001379 case lltok::kw_nest:
1380 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001381 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001382 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001383 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001384 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001385
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001386 case lltok::kw_alignstack:
1387 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001388 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001389 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001390 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001391 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001392 case lltok::kw_minsize:
1393 case lltok::kw_naked:
1394 case lltok::kw_nobuiltin:
1395 case lltok::kw_noduplicate:
1396 case lltok::kw_noimplicitfloat:
1397 case lltok::kw_noinline:
1398 case lltok::kw_nonlazybind:
1399 case lltok::kw_noredzone:
1400 case lltok::kw_noreturn:
1401 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001402 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001403 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001404 case lltok::kw_returns_twice:
1405 case lltok::kw_sanitize_address:
1406 case lltok::kw_sanitize_memory:
1407 case lltok::kw_sanitize_thread:
1408 case lltok::kw_ssp:
1409 case lltok::kw_sspreq:
1410 case lltok::kw_sspstrong:
1411 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001412 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001413 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001414
1415 case lltok::kw_readnone:
1416 case lltok::kw_readonly:
1417 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001418 }
1419
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420 Lex.Lex();
1421 }
1422}
1423
1424/// ParseOptionalLinkage
1425/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001426/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001427/// ::= 'internal'
1428/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001429/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001430/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001431/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001432/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001433/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001434/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001435/// ::= 'extern_weak'
1436/// ::= 'external'
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +00001437///
1438/// Deprecated Values:
1439/// ::= 'linker_private'
1440/// ::= 'linker_private_weak'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001441bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1442 HasLinkage = false;
1443 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001444 default: Res=GlobalValue::ExternalLinkage; return false;
1445 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001446 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1447 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1448 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1449 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1450 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001451 case lltok::kw_available_externally:
1452 Res = GlobalValue::AvailableExternallyLinkage;
1453 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001454 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001455 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001456 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1457 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +00001458
1459 case lltok::kw_linker_private:
1460 case lltok::kw_linker_private_weak:
Saleem Abdulrasoolefa31a92014-04-05 22:42:53 +00001461 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1462 " PrivateLinkage");
Saleem Abdulrasoolc1281352014-04-05 20:51:58 +00001463 Lex.Lex();
1464 // treat linker_private and linker_private_weak as PrivateLinkage
1465 Res = GlobalValue::PrivateLinkage;
1466 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001467 }
1468 Lex.Lex();
1469 HasLinkage = true;
1470 return false;
1471}
1472
1473/// ParseOptionalVisibility
1474/// ::= /*empty*/
1475/// ::= 'default'
1476/// ::= 'hidden'
1477/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001478///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001479bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1480 switch (Lex.getKind()) {
1481 default: Res = GlobalValue::DefaultVisibility; return false;
1482 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1483 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1484 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1485 }
1486 Lex.Lex();
1487 return false;
1488}
1489
Nico Rieck7157bb72014-01-14 15:22:47 +00001490/// ParseOptionalDLLStorageClass
1491/// ::= /*empty*/
1492/// ::= 'dllimport'
1493/// ::= 'dllexport'
1494///
1495bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1496 switch (Lex.getKind()) {
1497 default: Res = GlobalValue::DefaultStorageClass; return false;
1498 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1499 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1500 }
1501 Lex.Lex();
1502 return false;
1503}
1504
Chris Lattnerac161bf2009-01-02 07:01:27 +00001505/// ParseOptionalCallingConv
1506/// ::= /*empty*/
1507/// ::= 'ccc'
1508/// ::= 'fastcc'
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001509/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001510/// ::= 'coldcc'
1511/// ::= 'x86_stdcallcc'
1512/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001513/// ::= 'x86_thiscallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001514/// ::= 'arm_apcscc'
1515/// ::= 'arm_aapcscc'
1516/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001517/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001518/// ::= 'ptx_kernel'
1519/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001520/// ::= 'spir_func'
1521/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001522/// ::= 'x86_64_sysvcc'
1523/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001524/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001525/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001526/// ::= 'preserve_mostcc'
1527/// ::= 'preserve_allcc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001528/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001529///
Sandeep Patel68c5f472009-09-02 08:44:58 +00001530bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001531 switch (Lex.getKind()) {
1532 default: CC = CallingConv::C; return false;
1533 case lltok::kw_ccc: CC = CallingConv::C; break;
1534 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1535 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1536 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1537 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001538 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001539 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1540 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1541 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001542 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001543 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1544 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001545 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1546 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001547 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001548 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1549 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001550 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001551 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001552 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1553 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001554 case lltok::kw_cc: {
1555 unsigned ArbitraryCC;
1556 Lex.Lex();
David Blaikie46a9f012012-01-20 21:51:11 +00001557 if (ParseUInt32(ArbitraryCC))
Sandeep Patel68c5f472009-09-02 08:44:58 +00001558 return true;
David Blaikie46a9f012012-01-20 21:51:11 +00001559 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1560 return false;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001561 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001563
Chris Lattnerac161bf2009-01-02 07:01:27 +00001564 Lex.Lex();
1565 return false;
1566}
1567
Chris Lattner5c427632009-12-30 05:31:19 +00001568/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001569/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001570bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1571 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001572 do {
1573 if (Lex.getKind() != lltok::MetadataVar)
1574 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001575
Chris Lattner596760d2009-12-29 21:25:40 +00001576 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001577 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001578 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001579
Chris Lattner1797fc72009-12-29 21:53:55 +00001580 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001581 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001582
1583 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001584 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001585
Dan Gohmanf0715b12010-08-24 14:35:45 +00001586 // This code is similar to that of ParseMetadataValue, however it needs to
1587 // have special-case code for a forward reference; see the comments on
1588 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1589 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001590 if (Lex.getKind() == lltok::lbrace) {
1591 ValID ID;
1592 if (ParseMetadataListValue(ID, PFS))
1593 return true;
1594 assert(ID.Kind == ValID::t_MDNode);
1595 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001596 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001597 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001598 if (ParseMDNodeID(Node, NodeID))
1599 return true;
1600 if (Node) {
1601 // If we got the node, add it to the instruction.
1602 Inst->setMetadata(MDK, Node);
1603 } else {
1604 MDRef R = { Loc, MDK, NodeID };
1605 // Otherwise, remember that this should be resolved later.
1606 ForwardRefInstMetadata[Inst].push_back(R);
1607 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001608 }
Chris Lattner596760d2009-12-29 21:25:40 +00001609
Manman Ren209b17c2013-09-28 00:22:27 +00001610 if (MDK == LLVMContext::MD_tbaa)
1611 InstsWithTBAATag.push_back(Inst);
1612
Chris Lattner596760d2009-12-29 21:25:40 +00001613 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001614 } while (EatIfPresent(lltok::comma));
1615 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001616}
1617
Chris Lattnerac161bf2009-01-02 07:01:27 +00001618/// ParseOptionalAlignment
1619/// ::= /* empty */
1620/// ::= 'align' 4
1621bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1622 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001623 if (!EatIfPresent(lltok::kw_align))
1624 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001625 LocTy AlignLoc = Lex.getLoc();
1626 if (ParseUInt32(Alignment)) return true;
1627 if (!isPowerOf2_32(Alignment))
1628 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001629 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001630 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001631 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001632}
1633
Hal Finkelb0407ba2014-07-18 15:51:28 +00001634/// ParseOptionalDereferenceableBytes
1635/// ::= /* empty */
1636/// ::= 'dereferenceable' '(' 4 ')'
1637bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1638 Bytes = 0;
1639 if (!EatIfPresent(lltok::kw_dereferenceable))
1640 return false;
1641 LocTy ParenLoc = Lex.getLoc();
1642 if (!EatIfPresent(lltok::lparen))
1643 return Error(ParenLoc, "expected '('");
1644 LocTy DerefLoc = Lex.getLoc();
1645 if (ParseUInt64(Bytes)) return true;
1646 ParenLoc = Lex.getLoc();
1647 if (!EatIfPresent(lltok::rparen))
1648 return Error(ParenLoc, "expected ')'");
1649 if (!Bytes)
1650 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1651 return false;
1652}
1653
Chris Lattnerb2f39502009-12-30 05:44:30 +00001654/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001655/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001656/// ::= ',' align 4
1657///
1658/// This returns with AteExtraComma set to true if it ate an excess comma at the
1659/// end.
1660bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1661 bool &AteExtraComma) {
1662 AteExtraComma = false;
1663 while (EatIfPresent(lltok::comma)) {
1664 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001665 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001666 AteExtraComma = true;
1667 return false;
1668 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001669
Chris Lattner95b0ff42010-04-23 00:50:50 +00001670 if (Lex.getKind() != lltok::kw_align)
1671 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001672
Chris Lattner95b0ff42010-04-23 00:50:50 +00001673 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001674 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001675
Devang Patelea8a4b92009-09-17 23:04:48 +00001676 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001677}
1678
Eli Friedmanfee02c62011-07-25 23:16:38 +00001679/// ParseScopeAndOrdering
1680/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1681/// else: ::=
1682///
1683/// This sets Scope and Ordering to the parsed values.
1684bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1685 AtomicOrdering &Ordering) {
1686 if (!isAtomic)
1687 return false;
1688
1689 Scope = CrossThread;
1690 if (EatIfPresent(lltok::kw_singlethread))
1691 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001692
1693 return ParseOrdering(Ordering);
1694}
1695
1696/// ParseOrdering
1697/// ::= AtomicOrdering
1698///
1699/// This sets Ordering to the parsed value.
1700bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001701 switch (Lex.getKind()) {
1702 default: return TokError("Expected ordering on atomic instruction");
1703 case lltok::kw_unordered: Ordering = Unordered; break;
1704 case lltok::kw_monotonic: Ordering = Monotonic; break;
1705 case lltok::kw_acquire: Ordering = Acquire; break;
1706 case lltok::kw_release: Ordering = Release; break;
1707 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1708 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1709 }
1710 Lex.Lex();
1711 return false;
1712}
1713
Charles Davisbe5557e2010-02-12 00:31:15 +00001714/// ParseOptionalStackAlignment
1715/// ::= /* empty */
1716/// ::= 'alignstack' '(' 4 ')'
1717bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1718 Alignment = 0;
1719 if (!EatIfPresent(lltok::kw_alignstack))
1720 return false;
1721 LocTy ParenLoc = Lex.getLoc();
1722 if (!EatIfPresent(lltok::lparen))
1723 return Error(ParenLoc, "expected '('");
1724 LocTy AlignLoc = Lex.getLoc();
1725 if (ParseUInt32(Alignment)) return true;
1726 ParenLoc = Lex.getLoc();
1727 if (!EatIfPresent(lltok::rparen))
1728 return Error(ParenLoc, "expected ')'");
1729 if (!isPowerOf2_32(Alignment))
1730 return Error(AlignLoc, "stack alignment is not a power of two");
1731 return false;
1732}
Devang Patelea8a4b92009-09-17 23:04:48 +00001733
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001734/// ParseIndexList - This parses the index list for an insert/extractvalue
1735/// instruction. This sets AteExtraComma in the case where we eat an extra
1736/// comma at the end of the line and find that it is followed by metadata.
1737/// Clients that don't allow metadata can call the version of this function that
1738/// only takes one argument.
1739///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740/// ParseIndexList
1741/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001742///
1743bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1744 bool &AteExtraComma) {
1745 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001746
Chris Lattnerac161bf2009-01-02 07:01:27 +00001747 if (Lex.getKind() != lltok::comma)
1748 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001749
Chris Lattner3822f632009-01-02 08:05:26 +00001750 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001751 if (Lex.getKind() == lltok::MetadataVar) {
1752 AteExtraComma = true;
1753 return false;
1754 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001755 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001756 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001757 Indices.push_back(Idx);
1758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001759
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760 return false;
1761}
1762
1763//===----------------------------------------------------------------------===//
1764// Type Parsing.
1765//===----------------------------------------------------------------------===//
1766
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001767/// ParseType - Parse a type.
1768bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1769 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001770 switch (Lex.getKind()) {
1771 default:
1772 return TokError("expected type");
1773 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001774 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001775 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001776 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001777 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001778 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001779 // Type ::= StructType
1780 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001781 return true;
1782 break;
1783 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001784 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785 Lex.Lex(); // eat the lsquare.
1786 if (ParseArrayVectorType(Result, false))
1787 return true;
1788 break;
1789 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001790 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001791 Lex.Lex();
1792 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001794 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001795 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796 } else if (ParseArrayVectorType(Result, true))
1797 return true;
1798 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001799 case lltok::LocalVar: {
1800 // Type ::= %foo
1801 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001802
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001803 // If the type hasn't been defined yet, create a forward definition and
1804 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001805 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001806 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001807 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001808 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001809 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 Lex.Lex();
1811 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001813
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001814 case lltok::LocalVarID: {
1815 // Type ::= %4
1816 if (Lex.getUIntVal() >= NumberedTypes.size())
1817 NumberedTypes.resize(Lex.getUIntVal()+1);
1818 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 // If the type hasn't been defined yet, create a forward definition and
1821 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001822 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001823 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001824 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001825 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001826 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 Lex.Lex();
1828 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001829 }
1830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001831
1832 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833 while (1) {
1834 switch (Lex.getKind()) {
1835 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001836 default:
1837 if (!AllowVoid && Result->isVoidTy())
1838 return Error(TypeLoc, "void type only allowed for function results");
1839 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001840
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001841 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001842 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001843 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001844 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001845 if (Result->isVoidTy())
1846 return TokError("pointers to void are invalid - use i8* instead");
1847 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001848 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001849 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001850 Lex.Lex();
1851 break;
1852
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001853 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001855 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001857 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001858 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001859 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001860 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001861 unsigned AddrSpace;
1862 if (ParseOptionalAddrSpace(AddrSpace) ||
1863 ParseToken(lltok::star, "expected '*' in address space"))
1864 return true;
1865
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001866 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001867 break;
1868 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001869
Chris Lattnerac161bf2009-01-02 07:01:27 +00001870 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1871 case lltok::lparen:
1872 if (ParseFunctionType(Result))
1873 return true;
1874 break;
1875 }
1876 }
1877}
1878
1879/// ParseParameterList
1880/// ::= '(' ')'
1881/// ::= '(' Arg (',' Arg)* ')'
1882/// Arg
1883/// ::= Type OptionalAttributes Value OptionalAttributes
1884bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1885 PerFunctionState &PFS) {
1886 if (ParseToken(lltok::lparen, "expected '(' in call"))
1887 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001888
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001889 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001890 while (Lex.getKind() != lltok::rparen) {
1891 // If this isn't the first argument, we need a comma.
1892 if (!ArgList.empty() &&
1893 ParseToken(lltok::comma, "expected ',' in argument list"))
1894 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001895
Chris Lattnerac161bf2009-01-02 07:01:27 +00001896 // Parse the argument.
1897 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001898 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001899 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001901 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001902 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001903
Chris Lattner5b4a9622009-12-30 02:11:14 +00001904 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001905 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001906 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001907 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1908 AttrIndex++,
1909 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001910 }
1911
1912 Lex.Lex(); // Lex the ')'.
1913 return false;
1914}
1915
1916
1917
Chris Lattner2ed06b42009-01-05 18:34:07 +00001918/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001919/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920/// ::= '(' ArgTypeListI ')'
1921/// ArgTypeListI
1922/// ::= /*empty*/
1923/// ::= '...'
1924/// ::= ArgTypeList ',' '...'
1925/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001926///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001927bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1928 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 isVarArg = false;
1930 assert(Lex.getKind() == lltok::lparen);
1931 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933 if (Lex.getKind() == lltok::rparen) {
1934 // empty
1935 } else if (Lex.getKind() == lltok::dotdotdot) {
1936 isVarArg = true;
1937 Lex.Lex();
1938 } else {
1939 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001940 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001941 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001943
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001944 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001945 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Chris Lattnerfdd87902009-10-05 05:54:46 +00001947 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001948 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949
Chris Lattnerdef19492011-06-17 06:36:20 +00001950 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001951 Name = Lex.getStrVal();
1952 Lex.Lex();
1953 }
Chris Lattner3822f632009-01-02 08:05:26 +00001954
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001955 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001956 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001957
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001958 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001959 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001960 AttributeSet::get(ArgTy->getContext(),
1961 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001962
Chris Lattner3822f632009-01-02 08:05:26 +00001963 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001965 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001966 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 break;
1968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001969
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 // Otherwise must be an argument type.
1971 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001972 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001973
Chris Lattnerfdd87902009-10-05 05:54:46 +00001974 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001975 return Error(TypeLoc, "argument can not have void type");
1976
Chris Lattnerdef19492011-06-17 06:36:20 +00001977 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 Name = Lex.getStrVal();
1979 Lex.Lex();
1980 } else {
1981 Name = "";
1982 }
Chris Lattner3822f632009-01-02 08:05:26 +00001983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001985 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Bill Wendlingd079a442012-10-15 04:46:55 +00001987 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001988 AttributeSet::get(ArgTy->getContext(),
1989 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001990 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 }
1992 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001993
Chris Lattner3822f632009-01-02 08:05:26 +00001994 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001996
Chris Lattnerac161bf2009-01-02 07:01:27 +00001997/// ParseFunctionType
1998/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002000 assert(Lex.getKind() == lltok::lparen);
2001
Chris Lattnerce473c72009-01-05 08:04:33 +00002002 if (!FunctionType::isValidReturnType(Result))
2003 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002004
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002009
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010 // Reject names on the arguments lists.
2011 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2012 if (!ArgList[i].Name.empty())
2013 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002014 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002015 return Error(ArgList[i].Loc,
2016 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002017 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002018
Jay Foadb804a2b2011-07-12 14:06:48 +00002019 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002022
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002024 return false;
2025}
2026
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002027/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2028/// other structs.
2029bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2030 SmallVector<Type*, 8> Elts;
2031 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002033 Result = StructType::get(Context, Elts, Packed);
2034 return false;
2035}
2036
2037/// ParseStructDefinition - Parse a struct in a 'type' definition.
2038bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2039 std::pair<Type*, LocTy> &Entry,
2040 Type *&ResultTy) {
2041 // If the type was already defined, diagnose the redefinition.
2042 if (Entry.first && !Entry.second.isValid())
2043 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002044
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 // If we have opaque, just return without filling in the definition for the
2046 // struct. This counts as a definition as far as the .ll file goes.
2047 if (EatIfPresent(lltok::kw_opaque)) {
2048 // This type is being defined, so clear the location to indicate this.
2049 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002050
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002052 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002053 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002054 ResultTy = Entry.first;
2055 return false;
2056 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002057
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058 // If the type starts with '<', then it is either a packed struct or a vector.
2059 bool isPacked = EatIfPresent(lltok::less);
2060
2061 // If we don't have a struct, then we have a random type alias, which we
2062 // accept for compatibility with old files. These types are not allowed to be
2063 // forward referenced and not allowed to be recursive.
2064 if (Lex.getKind() != lltok::lbrace) {
2065 if (Entry.first)
2066 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002067
Craig Topper2617dcc2014-04-15 06:32:26 +00002068 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 if (isPacked)
2070 return ParseArrayVectorType(ResultTy, true);
2071 return ParseType(ResultTy);
2072 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 // This type is being defined, so clear the location to indicate this.
2075 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002076
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002078 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002079 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002080
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002082
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 SmallVector<Type*, 8> Body;
2084 if (ParseStructBody(Body) ||
2085 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2086 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 STy->setBody(Body, isPacked);
2089 ResultTy = STy;
2090 return false;
2091}
2092
2093
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002095/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002097/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002099/// ::= '<' '{' Type (',' Type)* '}' '>'
2100bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 assert(Lex.getKind() == lltok::lbrace);
2102 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 // Handle the empty struct.
2105 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107
Chris Lattnerf880ca22009-03-09 04:49:14 +00002108 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002109 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002110 if (ParseType(Ty)) return true;
2111 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002112
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002114 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002115
Chris Lattner3822f632009-01-02 08:05:26 +00002116 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002117 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002118 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002119
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002120 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002121 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002123 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002125
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002126 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127}
2128
2129/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2130/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002131/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132/// ::= '[' APSINTVAL 'x' Types ']'
2133/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002134bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2136 Lex.getAPSIntVal().getBitWidth() > 64)
2137 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002138
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 LocTy SizeLoc = Lex.getLoc();
2140 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002141 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002142
Chris Lattner3822f632009-01-02 08:05:26 +00002143 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2144 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002145
2146 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002147 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002148 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002149
Chris Lattner3822f632009-01-02 08:05:26 +00002150 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2151 "expected end of sequential type"))
2152 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002153
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002155 if (Size == 0)
2156 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 if ((unsigned)Size != Size)
2158 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002159 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002160 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002161 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002163 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002165 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002166 }
2167 return false;
2168}
2169
2170//===----------------------------------------------------------------------===//
2171// Function Semantic Analysis.
2172//===----------------------------------------------------------------------===//
2173
Chris Lattner3432c622009-10-28 03:39:23 +00002174LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2175 int functionNumber)
2176 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002177
2178 // Insert unnamed arguments into the NumberedVals list.
2179 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2180 AI != E; ++AI)
2181 if (!AI->hasName())
2182 NumberedVals.push_back(AI);
2183}
2184
2185LLParser::PerFunctionState::~PerFunctionState() {
2186 // If there were any forward referenced non-basicblock values, delete them.
2187 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2188 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2189 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002190 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002191 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002193 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002195
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2197 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2198 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002199 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002200 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002202 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002203 }
2204}
2205
Chris Lattner3432c622009-10-28 03:39:23 +00002206bool LLParser::PerFunctionState::FinishFunction() {
2207 // Check to see if someone took the address of labels in this block.
2208 if (!P.ForwardRefBlockAddresses.empty()) {
2209 ValID FunctionID;
2210 if (!F.getName().empty()) {
2211 FunctionID.Kind = ValID::t_GlobalName;
2212 FunctionID.StrVal = F.getName();
2213 } else {
2214 FunctionID.Kind = ValID::t_GlobalID;
2215 FunctionID.UIntVal = FunctionNumber;
2216 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002217
Chris Lattner3432c622009-10-28 03:39:23 +00002218 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2219 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2220 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2221 // Resolve all these references.
2222 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2223 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002224
Chris Lattner3432c622009-10-28 03:39:23 +00002225 P.ForwardRefBlockAddresses.erase(FRBAI);
2226 }
2227 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002228
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 if (!ForwardRefVals.empty())
2230 return P.Error(ForwardRefVals.begin()->second.second,
2231 "use of undefined value '%" + ForwardRefVals.begin()->first +
2232 "'");
2233 if (!ForwardRefValIDs.empty())
2234 return P.Error(ForwardRefValIDs.begin()->second.second,
2235 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002236 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 return false;
2238}
2239
2240
2241/// GetVal - Get a value with the specified name or ID, creating a
2242/// forward reference record if needed. This can return null if the value
2243/// exists but does not have the right type.
2244Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002245 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 // Look this name up in the normal function symbol table.
2247 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 // If this is a forward reference for the value, see if we already created a
2250 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002251 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002252 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2253 I = ForwardRefVals.find(Name);
2254 if (I != ForwardRefVals.end())
2255 Val = I->second.first;
2256 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 // If we have the value in the symbol table or fwd-ref table, return it.
2259 if (Val) {
2260 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002261 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 P.Error(Loc, "'%" + Name + "' is not a basic block");
2263 else
2264 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002265 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002266 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002268
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269 // Don't make placeholders with invalid type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002270 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002272 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002274
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 // Otherwise, create a new forward reference for this value and remember it.
2276 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002277 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002278 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279 else
2280 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2283 return FwdVal;
2284}
2285
Chris Lattner229907c2011-07-18 04:54:35 +00002286Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287 LocTy Loc) {
2288 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002289 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 // If this is a forward reference for the value, see if we already created a
2292 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002293 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2295 I = ForwardRefValIDs.find(ID);
2296 if (I != ForwardRefValIDs.end())
2297 Val = I->second.first;
2298 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 // If we have the value in the symbol table or fwd-ref table, return it.
2301 if (Val) {
2302 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002303 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002304 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002306 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002307 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002308 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002311 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002313 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 // Otherwise, create a new forward reference for this value and remember it.
2317 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002318 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002319 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 else
2321 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2324 return FwdVal;
2325}
2326
2327/// SetInstName - After an instruction is parsed and inserted into its
2328/// basic block, this installs its name.
2329bool LLParser::PerFunctionState::SetInstName(int NameID,
2330 const std::string &NameStr,
2331 LocTy NameLoc, Instruction *Inst) {
2332 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002333 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 if (NameID != -1 || !NameStr.empty())
2335 return P.Error(NameLoc, "instructions returning void cannot have a name");
2336 return false;
2337 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002338
Chris Lattnerac161bf2009-01-02 07:01:27 +00002339 // If this was a numbered instruction, verify that the instruction is the
2340 // expected value and resolve any forward references.
2341 if (NameStr.empty()) {
2342 // If neither a name nor an ID was specified, just use the next ID.
2343 if (NameID == -1)
2344 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 if (unsigned(NameID) != NumberedVals.size())
2347 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002348 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2351 ForwardRefValIDs.find(NameID);
2352 if (FI != ForwardRefValIDs.end()) {
2353 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002354 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002355 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002357 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 ForwardRefValIDs.erase(FI);
2359 }
2360
2361 NumberedVals.push_back(Inst);
2362 return false;
2363 }
2364
2365 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2366 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2367 FI = ForwardRefVals.find(NameStr);
2368 if (FI != ForwardRefVals.end()) {
2369 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002371 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002373 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 ForwardRefVals.erase(FI);
2375 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002376
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377 // Set the name on the instruction.
2378 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002379
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002380 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 NameStr + "'");
2383 return false;
2384}
2385
2386/// GetBB - Get a basic block with the specified name or ID, creating a
2387/// forward reference record if needed.
2388BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2389 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002390 return cast_or_null<BasicBlock>(GetVal(Name,
2391 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392}
2393
2394BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002395 return cast_or_null<BasicBlock>(GetVal(ID,
2396 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397}
2398
2399/// DefineBB - Define the specified basic block, which is either named or
2400/// unnamed. If there is an error, this returns null otherwise it returns
2401/// the block being defined.
2402BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2403 LocTy Loc) {
2404 BasicBlock *BB;
2405 if (Name.empty())
2406 BB = GetBB(NumberedVals.size(), Loc);
2407 else
2408 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002409 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002410
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411 // Move the block to the end of the function. Forward ref'd blocks are
2412 // inserted wherever they happen to be referenced.
2413 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002414
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 // Remove the block from forward ref sets.
2416 if (Name.empty()) {
2417 ForwardRefValIDs.erase(NumberedVals.size());
2418 NumberedVals.push_back(BB);
2419 } else {
2420 // BB forward references are already in the function symbol table.
2421 ForwardRefVals.erase(Name);
2422 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002423
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424 return BB;
2425}
2426
2427//===----------------------------------------------------------------------===//
2428// Constants.
2429//===----------------------------------------------------------------------===//
2430
2431/// ParseValID - Parse an abstract value that doesn't necessarily have a
2432/// type implied. For example, if we parse "4" we don't know what integer type
2433/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002434/// sanity. PFS is used to convert function-local operands of metadata (since
2435/// metadata operands are not just parsed here but also converted to values).
2436/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002437bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 ID.Loc = Lex.getLoc();
2439 switch (Lex.getKind()) {
2440 default: return TokError("expected value token");
2441 case lltok::GlobalID: // @42
2442 ID.UIntVal = Lex.getUIntVal();
2443 ID.Kind = ValID::t_GlobalID;
2444 break;
2445 case lltok::GlobalVar: // @foo
2446 ID.StrVal = Lex.getStrVal();
2447 ID.Kind = ValID::t_GlobalName;
2448 break;
2449 case lltok::LocalVarID: // %42
2450 ID.UIntVal = Lex.getUIntVal();
2451 ID.Kind = ValID::t_LocalID;
2452 break;
2453 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002454 ID.StrVal = Lex.getStrVal();
2455 ID.Kind = ValID::t_LocalName;
2456 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002457 case lltok::exclaim: // !42, !{...}, or !"foo"
2458 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 ID.Kind = ValID::t_APSInt;
2462 break;
2463 case lltok::APFloat:
2464 ID.APFloatVal = Lex.getAPFloatVal();
2465 ID.Kind = ValID::t_APFloat;
2466 break;
2467 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002468 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 ID.Kind = ValID::t_Constant;
2470 break;
2471 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002472 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 ID.Kind = ValID::t_Constant;
2474 break;
2475 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2476 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2477 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002478
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479 case lltok::lbrace: {
2480 // ValID ::= '{' ConstVector '}'
2481 Lex.Lex();
2482 SmallVector<Constant*, 16> Elts;
2483 if (ParseGlobalValueVector(Elts) ||
2484 ParseToken(lltok::rbrace, "expected end of struct constant"))
2485 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002486
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002487 ID.ConstantStructElts = new Constant*[Elts.size()];
2488 ID.UIntVal = Elts.size();
2489 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2490 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002491 return false;
2492 }
2493 case lltok::less: {
2494 // ValID ::= '<' ConstVector '>' --> Vector.
2495 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2496 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002497 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498
Chris Lattnerac161bf2009-01-02 07:01:27 +00002499 SmallVector<Constant*, 16> Elts;
2500 LocTy FirstEltLoc = Lex.getLoc();
2501 if (ParseGlobalValueVector(Elts) ||
2502 (isPackedStruct &&
2503 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2504 ParseToken(lltok::greater, "expected end of constant"))
2505 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002506
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002508 ID.ConstantStructElts = new Constant*[Elts.size()];
2509 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2510 ID.UIntVal = Elts.size();
2511 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 return false;
2513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 if (Elts.empty())
2516 return Error(ID.Loc, "constant vector must not be empty");
2517
Duncan Sands9dff9be2010-02-15 16:12:20 +00002518 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002519 !Elts[0]->getType()->isFloatingPointTy() &&
2520 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002522 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002523
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 // Verify that all the vector elements have the same type.
2525 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2526 if (Elts[i]->getType() != Elts[0]->getType())
2527 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002528 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002529 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattner69229312011-02-15 00:14:00 +00002531 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002532 ID.Kind = ValID::t_Constant;
2533 return false;
2534 }
2535 case lltok::lsquare: { // Array Constant
2536 Lex.Lex();
2537 SmallVector<Constant*, 16> Elts;
2538 LocTy FirstEltLoc = Lex.getLoc();
2539 if (ParseGlobalValueVector(Elts) ||
2540 ParseToken(lltok::rsquare, "expected end of array constant"))
2541 return true;
2542
2543 // Handle empty element.
2544 if (Elts.empty()) {
2545 // Use undef instead of an array because it's inconvenient to determine
2546 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002547 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 return false;
2549 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002550
Chris Lattnerac161bf2009-01-02 07:01:27 +00002551 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002552 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002553 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002554
Owen Anderson4056ca92009-07-29 22:17:13 +00002555 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002556
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002558 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559 if (Elts[i]->getType() != Elts[0]->getType())
2560 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002561 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002562 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002564
Jay Foad83be3612011-06-22 09:24:39 +00002565 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 ID.Kind = ValID::t_Constant;
2567 return false;
2568 }
2569 case lltok::kw_c: // c "foo"
2570 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002571 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2572 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002573 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2574 ID.Kind = ValID::t_Constant;
2575 return false;
2576
2577 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002578 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2579 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002580 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581 Lex.Lex();
2582 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002583 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002584 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002585 ParseStringConstant(ID.StrVal) ||
2586 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 ParseToken(lltok::StringConstant, "expected constraint string"))
2588 return true;
2589 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002590 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002591 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 ID.Kind = ValID::t_InlineAsm;
2593 return false;
2594 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002595
Chris Lattner3432c622009-10-28 03:39:23 +00002596 case lltok::kw_blockaddress: {
2597 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2598 Lex.Lex();
2599
2600 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002601
Chris Lattner3432c622009-10-28 03:39:23 +00002602 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2603 ParseValID(Fn) ||
2604 ParseToken(lltok::comma, "expected comma in block address expression")||
2605 ParseValID(Label) ||
2606 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2607 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002608
Chris Lattner3432c622009-10-28 03:39:23 +00002609 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2610 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002611 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002612 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002613
Chris Lattner3432c622009-10-28 03:39:23 +00002614 // Make a global variable as a placeholder for this reference.
2615 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2616 false, GlobalValue::InternalLinkage,
Craig Topper2617dcc2014-04-15 06:32:26 +00002617 nullptr, "");
Chris Lattner3432c622009-10-28 03:39:23 +00002618 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2619 ID.ConstantVal = FwdRef;
2620 ID.Kind = ValID::t_Constant;
2621 return false;
2622 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002623
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 case lltok::kw_trunc:
2625 case lltok::kw_zext:
2626 case lltok::kw_sext:
2627 case lltok::kw_fptrunc:
2628 case lltok::kw_fpext:
2629 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002630 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002631 case lltok::kw_uitofp:
2632 case lltok::kw_sitofp:
2633 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002638 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 Constant *SrcVal;
2640 Lex.Lex();
2641 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2642 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002643 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 ParseType(DestTy) ||
2645 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2646 return true;
2647 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2648 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002649 getTypeString(SrcVal->getType()) + "' to '" +
2650 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002651 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002652 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 ID.Kind = ValID::t_Constant;
2654 return false;
2655 }
2656 case lltok::kw_extractvalue: {
2657 Lex.Lex();
2658 Constant *Val;
2659 SmallVector<unsigned, 4> Indices;
2660 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2661 ParseGlobalTypeAndValue(Val) ||
2662 ParseIndexList(Indices) ||
2663 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2664 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002665
Chris Lattner392be582010-02-12 20:49:41 +00002666 if (!Val->getType()->isAggregateType())
2667 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002668 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002670 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 ID.Kind = ValID::t_Constant;
2672 return false;
2673 }
2674 case lltok::kw_insertvalue: {
2675 Lex.Lex();
2676 Constant *Val0, *Val1;
2677 SmallVector<unsigned, 4> Indices;
2678 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2679 ParseGlobalTypeAndValue(Val0) ||
2680 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2681 ParseGlobalTypeAndValue(Val1) ||
2682 ParseIndexList(Indices) ||
2683 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2684 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002685 if (!Val0->getType()->isAggregateType())
2686 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002687 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002689 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 ID.Kind = ValID::t_Constant;
2691 return false;
2692 }
2693 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002694 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 unsigned PredVal, Opc = Lex.getUIntVal();
2696 Constant *Val0, *Val1;
2697 Lex.Lex();
2698 if (ParseCmpPredicate(PredVal, Opc) ||
2699 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2700 ParseGlobalTypeAndValue(Val0) ||
2701 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2702 ParseGlobalTypeAndValue(Val1) ||
2703 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2704 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 if (Val0->getType() != Val1->getType())
2707 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002710
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002712 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002714 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002715 } else {
2716 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002717 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002718 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002720 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002721 }
2722 ID.Kind = ValID::t_Constant;
2723 return false;
2724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002725
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 // Binary Operators.
2727 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002728 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002729 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002730 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002731 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002732 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733 case lltok::kw_udiv:
2734 case lltok::kw_sdiv:
2735 case lltok::kw_fdiv:
2736 case lltok::kw_urem:
2737 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002738 case lltok::kw_frem:
2739 case lltok::kw_shl:
2740 case lltok::kw_lshr:
2741 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002742 bool NUW = false;
2743 bool NSW = false;
2744 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002745 unsigned Opc = Lex.getUIntVal();
2746 Constant *Val0, *Val1;
2747 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002748 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002749 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2750 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002751 if (EatIfPresent(lltok::kw_nuw))
2752 NUW = true;
2753 if (EatIfPresent(lltok::kw_nsw)) {
2754 NSW = true;
2755 if (EatIfPresent(lltok::kw_nuw))
2756 NUW = true;
2757 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002758 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2759 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002760 if (EatIfPresent(lltok::kw_exact))
2761 Exact = true;
2762 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002763 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2764 ParseGlobalTypeAndValue(Val0) ||
2765 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2766 ParseGlobalTypeAndValue(Val1) ||
2767 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2768 return true;
2769 if (Val0->getType() != Val1->getType())
2770 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002771 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002772 if (NUW)
2773 return Error(ModifierLoc, "nuw only applies to integer operations");
2774 if (NSW)
2775 return Error(ModifierLoc, "nsw only applies to integer operations");
2776 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002777 // Check that the type is valid for the operator.
2778 switch (Opc) {
2779 case Instruction::Add:
2780 case Instruction::Sub:
2781 case Instruction::Mul:
2782 case Instruction::UDiv:
2783 case Instruction::SDiv:
2784 case Instruction::URem:
2785 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002786 case Instruction::Shl:
2787 case Instruction::AShr:
2788 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002789 if (!Val0->getType()->isIntOrIntVectorTy())
2790 return Error(ID.Loc, "constexpr requires integer operands");
2791 break;
2792 case Instruction::FAdd:
2793 case Instruction::FSub:
2794 case Instruction::FMul:
2795 case Instruction::FDiv:
2796 case Instruction::FRem:
2797 if (!Val0->getType()->isFPOrFPVectorTy())
2798 return Error(ID.Loc, "constexpr requires fp operands");
2799 break;
2800 default: llvm_unreachable("Unknown binary operator!");
2801 }
Dan Gohman1b849082009-09-07 23:54:19 +00002802 unsigned Flags = 0;
2803 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2804 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002805 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002806 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002807 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 ID.Kind = ValID::t_Constant;
2809 return false;
2810 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811
Chris Lattnerac161bf2009-01-02 07:01:27 +00002812 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 case lltok::kw_and:
2814 case lltok::kw_or:
2815 case lltok::kw_xor: {
2816 unsigned Opc = Lex.getUIntVal();
2817 Constant *Val0, *Val1;
2818 Lex.Lex();
2819 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2820 ParseGlobalTypeAndValue(Val0) ||
2821 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2822 ParseGlobalTypeAndValue(Val1) ||
2823 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2824 return true;
2825 if (Val0->getType() != Val1->getType())
2826 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002827 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 return Error(ID.Loc,
2829 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002830 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 ID.Kind = ValID::t_Constant;
2832 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002833 }
2834
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 case lltok::kw_getelementptr:
2836 case lltok::kw_shufflevector:
2837 case lltok::kw_insertelement:
2838 case lltok::kw_extractelement:
2839 case lltok::kw_select: {
2840 unsigned Opc = Lex.getUIntVal();
2841 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002842 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002844 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002845 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002846 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2847 ParseGlobalValueVector(Elts) ||
2848 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2849 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002850
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002852 if (Elts.size() == 0 ||
2853 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002854 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002855
Jay Foaded8db7d2011-07-21 14:31:17 +00002856 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002857 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002859 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2860 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002861 } else if (Opc == Instruction::Select) {
2862 if (Elts.size() != 3)
2863 return Error(ID.Loc, "expected three operands to select");
2864 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2865 Elts[2]))
2866 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002867 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 } else if (Opc == Instruction::ShuffleVector) {
2869 if (Elts.size() != 3)
2870 return Error(ID.Loc, "expected three operands to shufflevector");
2871 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2872 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002873 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002874 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002875 } else if (Opc == Instruction::ExtractElement) {
2876 if (Elts.size() != 2)
2877 return Error(ID.Loc, "expected two operands to extractelement");
2878 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2879 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002880 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002881 } else {
2882 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2883 if (Elts.size() != 3)
2884 return Error(ID.Loc, "expected three operands to insertelement");
2885 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2886 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002887 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002888 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002890
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 ID.Kind = ValID::t_Constant;
2892 return false;
2893 }
2894 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895
Chris Lattnerac161bf2009-01-02 07:01:27 +00002896 Lex.Lex();
2897 return false;
2898}
2899
2900/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002901bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002902 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002903 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002904 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002905 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002906 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002907 if (V && !(C = dyn_cast<Constant>(V)))
2908 return Error(ID.Loc, "global values must be constants");
2909 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002910}
2911
Victor Hernandez9d75c962010-01-11 22:31:58 +00002912bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002913 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002914 return ParseType(Ty) ||
2915 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002916}
2917
David Majnemerdad0a642014-06-27 18:19:56 +00002918bool LLParser::parseOptionalComdat(Comdat *&C) {
2919 C = nullptr;
2920 if (!EatIfPresent(lltok::kw_comdat))
2921 return false;
2922 if (Lex.getKind() != lltok::ComdatVar)
2923 return TokError("expected comdat variable");
2924 LocTy Loc = Lex.getLoc();
2925 StringRef Name = Lex.getStrVal();
2926 C = getComdat(Name, Loc);
2927 Lex.Lex();
2928 return false;
2929}
2930
Victor Hernandez9d75c962010-01-11 22:31:58 +00002931/// ParseGlobalValueVector
2932/// ::= /*empty*/
2933/// ::= TypeAndValue (',' TypeAndValue)*
2934bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2935 // Empty list.
2936 if (Lex.getKind() == lltok::rbrace ||
2937 Lex.getKind() == lltok::rsquare ||
2938 Lex.getKind() == lltok::greater ||
2939 Lex.getKind() == lltok::rparen)
2940 return false;
2941
2942 Constant *C;
2943 if (ParseGlobalTypeAndValue(C)) return true;
2944 Elts.push_back(C);
2945
2946 while (EatIfPresent(lltok::comma)) {
2947 if (ParseGlobalTypeAndValue(C)) return true;
2948 Elts.push_back(C);
2949 }
2950
2951 return false;
2952}
2953
Dan Gohmanc828c542010-08-24 02:24:03 +00002954bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2955 assert(Lex.getKind() == lltok::lbrace);
2956 Lex.Lex();
2957
2958 SmallVector<Value*, 16> Elts;
2959 if (ParseMDNodeVector(Elts, PFS) ||
2960 ParseToken(lltok::rbrace, "expected end of metadata node"))
2961 return true;
2962
Jay Foad5514afe2011-04-21 19:59:31 +00002963 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002964 ID.Kind = ValID::t_MDNode;
2965 return false;
2966}
2967
Dan Gohman8939ba332010-07-14 18:26:50 +00002968/// ParseMetadataValue
2969/// ::= !42
2970/// ::= !{...}
2971/// ::= !"string"
2972bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2973 assert(Lex.getKind() == lltok::exclaim);
2974 Lex.Lex();
2975
2976 // MDNode:
2977 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002978 if (Lex.getKind() == lltok::lbrace)
2979 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002980
2981 // Standalone metadata reference
2982 // !42
2983 if (Lex.getKind() == lltok::APSInt) {
2984 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2985 ID.Kind = ValID::t_MDNode;
2986 return false;
2987 }
2988
2989 // MDString:
2990 // ::= '!' STRINGCONSTANT
2991 if (ParseMDString(ID.MDStringVal)) return true;
2992 ID.Kind = ValID::t_MDString;
2993 return false;
2994}
2995
Victor Hernandez9d75c962010-01-11 22:31:58 +00002996
2997//===----------------------------------------------------------------------===//
2998// Function Parsing.
2999//===----------------------------------------------------------------------===//
3000
Chris Lattner229907c2011-07-18 04:54:35 +00003001bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003002 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003003 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003005
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003008 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3009 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003010 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003011 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003012 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3013 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003014 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003015 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003016 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003017 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003018 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003019 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3020 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003021 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003022 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003023 return false;
3024 }
3025 case ValID::t_MDNode:
3026 if (!Ty->isMetadataTy())
3027 return Error(ID.Loc, "metadata value must have metadata type");
3028 V = ID.MDNodeVal;
3029 return false;
3030 case ValID::t_MDString:
3031 if (!Ty->isMetadataTy())
3032 return Error(ID.Loc, "metadata value must have metadata type");
3033 V = ID.MDStringVal;
3034 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 case ValID::t_GlobalName:
3036 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003037 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 case ValID::t_GlobalID:
3039 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003040 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003042 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003044 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003045 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 return false;
3047 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003048 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3050 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003051
Dan Gohman518cda42011-12-17 00:04:22 +00003052 // The lexer has no type info, so builds all half, float, and double FP
3053 // constants as double. Fix this here. Long double does not need this.
3054 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003056 if (Ty->isHalfTy())
3057 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3058 &Ignored);
3059 else if (Ty->isFloatTy())
3060 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3061 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003062 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003063 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003064
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003065 if (V->getType() != Ty)
3066 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003067 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003068
Chris Lattnerac161bf2009-01-02 07:01:27 +00003069 return false;
3070 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003071 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003073 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003074 return false;
3075 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003076 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003077 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003078 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003079 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003081 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003082 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003083 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003084 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003085 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003087 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003088 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003089 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003090 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003091 return false;
3092 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003093 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003094 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003095
Chris Lattnerac161bf2009-01-02 07:01:27 +00003096 V = ID.ConstantVal;
3097 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003098 case ValID::t_ConstantStruct:
3099 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003100 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003101 if (ST->getNumElements() != ID.UIntVal)
3102 return Error(ID.Loc,
3103 "initializer with struct type has wrong # elements");
3104 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3105 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003107 // Verify that the elements are compatible with the structtype.
3108 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3109 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3110 return Error(ID.Loc, "element " + Twine(i) +
3111 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003112
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003113 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3114 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003115 } else
3116 return Error(ID.Loc, "constant expression type mismatch");
3117 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003118 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003119 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003120}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003121
Chris Lattner229907c2011-07-18 04:54:35 +00003122bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003123 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003125 return ParseValID(ID, PFS) ||
3126 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003127}
3128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003129bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003130 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003131 return ParseType(Ty) ||
3132 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003133}
3134
Chris Lattner3ed871f2009-10-27 19:13:16 +00003135bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3136 PerFunctionState &PFS) {
3137 Value *V;
3138 Loc = Lex.getLoc();
3139 if (ParseTypeAndValue(V, PFS)) return true;
3140 if (!isa<BasicBlock>(V))
3141 return Error(Loc, "expected a basic block");
3142 BB = cast<BasicBlock>(V);
3143 return false;
3144}
3145
3146
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147/// FunctionHeader
3148/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003149/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003150/// OptionalAlign OptGC OptionalPrefix
Chris Lattnerac161bf2009-01-02 07:01:27 +00003151bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3152 // Parse the linkage.
3153 LocTy LinkageLoc = Lex.getLoc();
3154 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003155
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003156 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003157 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003158 AttrBuilder RetAttrs;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003159 CallingConv::ID CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003160 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003161 LocTy RetTypeLoc = Lex.getLoc();
3162 if (ParseOptionalLinkage(Linkage) ||
3163 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003164 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003166 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003167 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003168 return true;
3169
3170 // Verify that the linkage is ok.
3171 switch ((GlobalValue::LinkageTypes)Linkage) {
3172 case GlobalValue::ExternalLinkage:
3173 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003174 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003175 if (isDefine)
3176 return Error(LinkageLoc, "invalid linkage for function definition");
3177 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003178 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003179 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003180 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003181 case GlobalValue::LinkOnceAnyLinkage:
3182 case GlobalValue::LinkOnceODRLinkage:
3183 case GlobalValue::WeakAnyLinkage:
3184 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003185 if (!isDefine)
3186 return Error(LinkageLoc, "invalid linkage for function declaration");
3187 break;
3188 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003189 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190 return Error(LinkageLoc, "invalid function linkage type");
3191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003192
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003193 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3194 return Error(LinkageLoc,
3195 "symbol with local linkage must have default visibility");
3196
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003197 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003198 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003199
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003201
3202 std::string FunctionName;
3203 if (Lex.getKind() == lltok::GlobalVar) {
3204 FunctionName = Lex.getStrVal();
3205 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3206 unsigned NameID = Lex.getUIntVal();
3207
3208 if (NameID != NumberedVals.size())
3209 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003210 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003211 } else {
3212 return TokError("expected function name");
3213 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003214
Chris Lattner3822f632009-01-02 08:05:26 +00003215 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216
Chris Lattner3822f632009-01-02 08:05:26 +00003217 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003219
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003220 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003221 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003222 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003223 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003224 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003225 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003226 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003227 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003228 bool UnnamedAddr;
3229 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003230 Constant *Prefix = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003231 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003232
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003233 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003234 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3235 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003236 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003237 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003238 (EatIfPresent(lltok::kw_section) &&
3239 ParseStringConstant(Section)) ||
David Majnemerdad0a642014-06-27 18:19:56 +00003240 parseOptionalComdat(C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003241 ParseOptionalAlignment(Alignment) ||
3242 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003243 ParseStringConstant(GC)) ||
3244 (EatIfPresent(lltok::kw_prefix) &&
3245 ParseGlobalTypeAndValue(Prefix)))
Chris Lattner3822f632009-01-02 08:05:26 +00003246 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247
Michael Gottesman41748d72013-06-27 00:25:01 +00003248 if (FuncAttrs.contains(Attribute::Builtin))
3249 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003250
Chris Lattnerac161bf2009-01-02 07:01:27 +00003251 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003252 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003253 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003254 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003256
Chris Lattnerac161bf2009-01-02 07:01:27 +00003257 // Okay, if we got here, the function is syntactically valid. Convert types
3258 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003259 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003260 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003261
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003262 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003263 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3264 AttributeSet::ReturnIndex,
3265 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003266
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003268 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003269 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3270 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003271 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3272 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 }
3274
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003275 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003276 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3277 AttributeSet::FunctionIndex,
3278 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003279
Bill Wendlinge94d8432012-12-07 23:16:57 +00003280 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003281
Bill Wendling749a43d2012-12-30 13:50:49 +00003282 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003283 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3284
Chris Lattner229907c2011-07-18 04:54:35 +00003285 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003286 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003287 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288
Craig Topper2617dcc2014-04-15 06:32:26 +00003289 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 if (!FunctionName.empty()) {
3291 // If this was a definition of a forward reference, remove the definition
3292 // from the forward reference table and fill in the forward ref.
3293 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3294 ForwardRefVals.find(FunctionName);
3295 if (FRVI != ForwardRefVals.end()) {
3296 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003297 if (!Fn)
3298 return Error(FRVI->second.second, "invalid forward reference to "
3299 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003300 if (Fn->getType() != PFT)
3301 return Error(FRVI->second.second, "invalid forward reference to "
3302 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003303
Chris Lattnerac161bf2009-01-02 07:01:27 +00003304 ForwardRefVals.erase(FRVI);
3305 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003306 // Reject redefinitions.
3307 return Error(NameLoc, "invalid redefinition of function '" +
3308 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003309 } else if (M->getNamedValue(FunctionName)) {
3310 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003311 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003312
Dan Gohman399d6ae2009-08-29 23:37:49 +00003313 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003314 // If this is a definition of a forward referenced function, make sure the
3315 // types agree.
3316 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3317 = ForwardRefValIDs.find(NumberedVals.size());
3318 if (I != ForwardRefValIDs.end()) {
3319 Fn = cast<Function>(I->second.first);
3320 if (Fn->getType() != PFT)
3321 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003322 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 ForwardRefValIDs.erase(I);
3324 }
3325 }
3326
Craig Topper2617dcc2014-04-15 06:32:26 +00003327 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003328 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3329 else // Move the forward-reference to the correct spot in the module.
3330 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3331
3332 if (FunctionName.empty())
3333 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003334
Chris Lattnerac161bf2009-01-02 07:01:27 +00003335 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3336 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003337 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003338 Fn->setCallingConv(CC);
3339 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003340 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003341 Fn->setAlignment(Alignment);
3342 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003343 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003344 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003345 Fn->setPrefixData(Prefix);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003346 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003347
Chris Lattnerac161bf2009-01-02 07:01:27 +00003348 // Add all of the arguments we parsed to the function.
3349 Function::arg_iterator ArgIt = Fn->arg_begin();
3350 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3351 // If the argument has a name, insert it into the argument symbol table.
3352 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003353
Chris Lattnerac161bf2009-01-02 07:01:27 +00003354 // Set the name, if it conflicted, it will be auto-renamed.
3355 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003356
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003357 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003358 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3359 ArgList[i].Name + "'");
3360 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003361
Chris Lattnerac161bf2009-01-02 07:01:27 +00003362 return false;
3363}
3364
3365
3366/// ParseFunctionBody
3367/// ::= '{' BasicBlock+ '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003368///
3369bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003370 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003371 return TokError("expected '{' in function body");
3372 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003373
Chris Lattner3432c622009-10-28 03:39:23 +00003374 int FunctionNumber = -1;
3375 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003376
Chris Lattner3432c622009-10-28 03:39:23 +00003377 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003378
Chris Lattnerbbddd962010-01-09 19:20:07 +00003379 // We need at least one basic block.
Chris Lattner4649a732011-06-17 06:42:57 +00003380 if (Lex.getKind() == lltok::rbrace)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003381 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003382
Chris Lattner4649a732011-06-17 06:42:57 +00003383 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003384 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003385
Chris Lattnerac161bf2009-01-02 07:01:27 +00003386 // Eat the }.
3387 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003388
Chris Lattnerac161bf2009-01-02 07:01:27 +00003389 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003390 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003391}
3392
3393/// ParseBasicBlock
3394/// ::= LabelStr? Instruction*
3395bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3396 // If this basic block starts out with a name, remember it.
3397 std::string Name;
3398 LocTy NameLoc = Lex.getLoc();
3399 if (Lex.getKind() == lltok::LabelStr) {
3400 Name = Lex.getStrVal();
3401 Lex.Lex();
3402 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003403
Chris Lattnerac161bf2009-01-02 07:01:27 +00003404 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003405 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003406
Chris Lattnerac161bf2009-01-02 07:01:27 +00003407 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003408
Chris Lattnerac161bf2009-01-02 07:01:27 +00003409 // Parse the instructions in this block until we get a terminator.
3410 Instruction *Inst;
3411 do {
3412 // This instruction may have three possibilities for a name: a) none
3413 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3414 LocTy NameLoc = Lex.getLoc();
3415 int NameID = -1;
3416 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003417
Chris Lattnerac161bf2009-01-02 07:01:27 +00003418 if (Lex.getKind() == lltok::LocalVarID) {
3419 NameID = Lex.getUIntVal();
3420 Lex.Lex();
3421 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3422 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003423 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003424 NameStr = Lex.getStrVal();
3425 Lex.Lex();
3426 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3427 return true;
3428 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003429
Chris Lattner77b89dc2009-12-30 05:23:43 +00003430 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003431 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003432 case InstError: return true;
3433 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003434 BB->getInstList().push_back(Inst);
3435
Chris Lattner77b89dc2009-12-30 05:23:43 +00003436 // With a normal result, we check to see if the instruction is followed by
3437 // a comma and metadata.
3438 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003439 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003440 return true;
3441 break;
3442 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003443 BB->getInstList().push_back(Inst);
3444
Chris Lattner77b89dc2009-12-30 05:23:43 +00003445 // If the instruction parser ate an extra comma at the end of it, it
3446 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003447 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003448 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003449 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003450 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003451
Chris Lattnerac161bf2009-01-02 07:01:27 +00003452 // Set the name on the instruction.
3453 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3454 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003455
Chris Lattnerac161bf2009-01-02 07:01:27 +00003456 return false;
3457}
3458
3459//===----------------------------------------------------------------------===//
3460// Instruction Parsing.
3461//===----------------------------------------------------------------------===//
3462
3463/// ParseInstruction - Parse one of the many different instructions.
3464///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003465int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3466 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003467 lltok::Kind Token = Lex.getKind();
3468 if (Token == lltok::Eof)
3469 return TokError("found end of file when expecting more instructions");
3470 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003471 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003472 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003473
Chris Lattnerac161bf2009-01-02 07:01:27 +00003474 switch (Token) {
3475 default: return Error(Loc, "expected instruction opcode");
3476 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003477 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003478 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3479 case lltok::kw_br: return ParseBr(Inst, PFS);
3480 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003481 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003482 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003483 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003484 // Binary Operators.
3485 case lltok::kw_add:
3486 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003487 case lltok::kw_mul:
3488 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003489 bool NUW = EatIfPresent(lltok::kw_nuw);
3490 bool NSW = EatIfPresent(lltok::kw_nsw);
3491 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003492
Chris Lattnera676c0f2011-02-07 16:40:21 +00003493 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003494
Chris Lattnera676c0f2011-02-07 16:40:21 +00003495 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3496 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3497 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003498 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003499 case lltok::kw_fadd:
3500 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003501 case lltok::kw_fmul:
3502 case lltok::kw_fdiv:
3503 case lltok::kw_frem: {
3504 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3505 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3506 if (Res != 0)
3507 return Res;
3508 if (FMF.any())
3509 Inst->setFastMathFlags(FMF);
3510 return 0;
3511 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003512
Chris Lattner35315d02011-02-06 21:44:57 +00003513 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003514 case lltok::kw_udiv:
3515 case lltok::kw_lshr:
3516 case lltok::kw_ashr: {
3517 bool Exact = EatIfPresent(lltok::kw_exact);
3518
3519 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3520 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3521 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003522 }
3523
Chris Lattnerac161bf2009-01-02 07:01:27 +00003524 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003525 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003526 case lltok::kw_and:
3527 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003528 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003530 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003531 // Casts.
3532 case lltok::kw_trunc:
3533 case lltok::kw_zext:
3534 case lltok::kw_sext:
3535 case lltok::kw_fptrunc:
3536 case lltok::kw_fpext:
3537 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003538 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003539 case lltok::kw_uitofp:
3540 case lltok::kw_sitofp:
3541 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003542 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003543 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003544 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003545 // Other.
3546 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003547 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003548 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3549 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3550 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3551 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003552 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003553 // Call.
3554 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3555 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3556 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003557 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003558 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003559 case lltok::kw_load: return ParseLoad(Inst, PFS);
3560 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003561 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3562 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003563 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003564 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3565 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3566 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3567 }
3568}
3569
3570/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3571bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003572 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003573 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003574 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003575 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3576 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3577 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3578 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3579 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3580 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3581 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3582 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3583 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3584 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3585 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3586 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3587 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3588 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3589 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3590 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3591 }
3592 } else {
3593 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003594 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003595 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3596 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3597 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3598 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3599 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3600 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3601 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3602 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3603 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3604 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3605 }
3606 }
3607 Lex.Lex();
3608 return false;
3609}
3610
3611//===----------------------------------------------------------------------===//
3612// Terminator Instructions.
3613//===----------------------------------------------------------------------===//
3614
3615/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003616/// ::= 'ret' void (',' !dbg, !1)*
3617/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003618bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003619 PerFunctionState &PFS) {
3620 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003621 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003622 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003623
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003624 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003625
Chris Lattnerfdd87902009-10-05 05:54:46 +00003626 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003627 if (!ResType->isVoidTy())
3628 return Error(TypeLoc, "value doesn't match function result type '" +
3629 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003630
Owen Anderson55f1c092009-08-13 21:58:54 +00003631 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003632 return false;
3633 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003634
Chris Lattnerac161bf2009-01-02 07:01:27 +00003635 Value *RV;
3636 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003637
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003638 if (ResType != RV->getType())
3639 return Error(TypeLoc, "value doesn't match function result type '" +
3640 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003641
Owen Anderson55f1c092009-08-13 21:58:54 +00003642 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003643 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003644}
3645
3646
3647/// ParseBr
3648/// ::= 'br' TypeAndValue
3649/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3650bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3651 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003652 Value *Op0;
3653 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003654 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003655
Chris Lattnerac161bf2009-01-02 07:01:27 +00003656 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3657 Inst = BranchInst::Create(BB);
3658 return false;
3659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003660
Owen Anderson55f1c092009-08-13 21:58:54 +00003661 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003662 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003663
Chris Lattnerac161bf2009-01-02 07:01:27 +00003664 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003665 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003666 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003667 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003668 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003669
Chris Lattner3ed871f2009-10-27 19:13:16 +00003670 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003671 return false;
3672}
3673
3674/// ParseSwitch
3675/// Instruction
3676/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3677/// JumpTable
3678/// ::= (TypeAndValue ',' TypeAndValue)*
3679bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3680 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003681 Value *Cond;
3682 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003683 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3684 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003685 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003686 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3687 return true;
3688
Duncan Sands19d0b472010-02-16 11:11:14 +00003689 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003690 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003691
Chris Lattnerac161bf2009-01-02 07:01:27 +00003692 // Parse the jump table pairs.
3693 SmallPtrSet<Value*, 32> SeenCases;
3694 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3695 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003696 Value *Constant;
3697 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003698
Chris Lattnerac161bf2009-01-02 07:01:27 +00003699 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3700 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003701 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003702 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003703
Chris Lattnerac161bf2009-01-02 07:01:27 +00003704 if (!SeenCases.insert(Constant))
3705 return Error(CondLoc, "duplicate case value in switch");
3706 if (!isa<ConstantInt>(Constant))
3707 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003708
Chris Lattner3ed871f2009-10-27 19:13:16 +00003709 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003710 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003711
Chris Lattnerac161bf2009-01-02 07:01:27 +00003712 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003713
Chris Lattner3ed871f2009-10-27 19:13:16 +00003714 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003715 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3716 SI->addCase(Table[i].first, Table[i].second);
3717 Inst = SI;
3718 return false;
3719}
3720
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003721/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003722/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003723/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3724bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003725 LocTy AddrLoc;
3726 Value *Address;
3727 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003728 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3729 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003730 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003731
Duncan Sands19d0b472010-02-16 11:11:14 +00003732 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003733 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003734
Chris Lattner3ed871f2009-10-27 19:13:16 +00003735 // Parse the destination list.
3736 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003737
Chris Lattner3ed871f2009-10-27 19:13:16 +00003738 if (Lex.getKind() != lltok::rsquare) {
3739 BasicBlock *DestBB;
3740 if (ParseTypeAndBasicBlock(DestBB, PFS))
3741 return true;
3742 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003743
Chris Lattner3ed871f2009-10-27 19:13:16 +00003744 while (EatIfPresent(lltok::comma)) {
3745 if (ParseTypeAndBasicBlock(DestBB, PFS))
3746 return true;
3747 DestList.push_back(DestBB);
3748 }
3749 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003750
Chris Lattner3ed871f2009-10-27 19:13:16 +00003751 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3752 return true;
3753
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003754 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003755 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3756 IBI->addDestination(DestList[i]);
3757 Inst = IBI;
3758 return false;
3759}
3760
3761
Chris Lattnerac161bf2009-01-02 07:01:27 +00003762/// ParseInvoke
3763/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3764/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3765bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3766 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003767 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003768 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003769 LocTy NoBuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003770 CallingConv::ID CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003771 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003772 LocTy RetTypeLoc;
3773 ValID CalleeID;
3774 SmallVector<ParamInfo, 16> ArgList;
3775
Chris Lattner3ed871f2009-10-27 19:13:16 +00003776 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003777 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003778 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003779 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003780 ParseValID(CalleeID) ||
3781 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003782 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3783 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003784 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003785 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003786 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003787 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003788 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003789
Chris Lattnerac161bf2009-01-02 07:01:27 +00003790 // If RetType is a non-function pointer type, then this is the short syntax
3791 // for the call, which means that RetType is just the return type. Infer the
3792 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003793 PointerType *PFTy = nullptr;
3794 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003795 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3796 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3797 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003798 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003799 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3800 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003801
Chris Lattnerac161bf2009-01-02 07:01:27 +00003802 if (!FunctionType::isValidReturnType(RetType))
3803 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003804
Owen Anderson4056ca92009-07-29 22:17:13 +00003805 Ty = FunctionType::get(RetType, ParamTypes, false);
3806 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003807 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003808
Chris Lattnerac161bf2009-01-02 07:01:27 +00003809 // Look up the callee.
3810 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003811 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003812
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003813 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003814 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003815 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003816 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3817 AttributeSet::ReturnIndex,
3818 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003819
Chris Lattnerac161bf2009-01-02 07:01:27 +00003820 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003821
Chris Lattnerac161bf2009-01-02 07:01:27 +00003822 // Loop through FunctionType's arguments and ensure they are specified
3823 // correctly. Also, gather any parameter attributes.
3824 FunctionType::param_iterator I = Ty->param_begin();
3825 FunctionType::param_iterator E = Ty->param_end();
3826 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003827 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003828 if (I != E) {
3829 ExpectedTy = *I++;
3830 } else if (!Ty->isVarArg()) {
3831 return Error(ArgList[i].Loc, "too many arguments specified");
3832 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003833
Chris Lattnerac161bf2009-01-02 07:01:27 +00003834 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3835 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003836 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003837 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003838 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3839 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003840 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3841 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003842 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003843
Chris Lattnerac161bf2009-01-02 07:01:27 +00003844 if (I != E)
3845 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003846
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003847 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003848 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3849 AttributeSet::FunctionIndex,
3850 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003851
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003852 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003853 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003854
Jay Foad5bd375a2011-07-15 08:37:34 +00003855 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003856 II->setCallingConv(CC);
3857 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003858 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003859 Inst = II;
3860 return false;
3861}
3862
Bill Wendlingf891bf82011-07-31 06:30:59 +00003863/// ParseResume
3864/// ::= 'resume' TypeAndValue
3865bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3866 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003867 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3868 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003869
Bill Wendlingf891bf82011-07-31 06:30:59 +00003870 ResumeInst *RI = ResumeInst::Create(Exn);
3871 Inst = RI;
3872 return false;
3873}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003874
3875//===----------------------------------------------------------------------===//
3876// Binary Operators.
3877//===----------------------------------------------------------------------===//
3878
3879/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003880/// ::= ArithmeticOps TypeAndValue ',' Value
3881///
3882/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3883/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003885 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003886 LocTy Loc; Value *LHS, *RHS;
3887 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3888 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3889 ParseValue(LHS->getType(), RHS, PFS))
3890 return true;
3891
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003892 bool Valid;
3893 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003894 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003895 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003896 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3897 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003898 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003899 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3900 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003902
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003903 if (!Valid)
3904 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003905
Chris Lattnerac161bf2009-01-02 07:01:27 +00003906 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3907 return false;
3908}
3909
3910/// ParseLogical
3911/// ::= ArithmeticOps TypeAndValue ',' Value {
3912bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3913 unsigned Opc) {
3914 LocTy Loc; Value *LHS, *RHS;
3915 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3916 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3917 ParseValue(LHS->getType(), RHS, PFS))
3918 return true;
3919
Duncan Sands9dff9be2010-02-15 16:12:20 +00003920 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921 return Error(Loc,"instruction requires integer or integer vector operands");
3922
3923 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3924 return false;
3925}
3926
3927
3928/// ParseCompare
3929/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3930/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3932 unsigned Opc) {
3933 // Parse the integer/fp comparison predicate.
3934 LocTy Loc;
3935 unsigned Pred;
3936 Value *LHS, *RHS;
3937 if (ParseCmpPredicate(Pred, Opc) ||
3938 ParseTypeAndValue(LHS, Loc, PFS) ||
3939 ParseToken(lltok::comma, "expected ',' after compare value") ||
3940 ParseValue(LHS->getType(), RHS, PFS))
3941 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003942
Chris Lattnerac161bf2009-01-02 07:01:27 +00003943 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003944 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003945 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003946 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003947 } else {
3948 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003949 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003950 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003951 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003952 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003953 }
3954 return false;
3955}
3956
3957//===----------------------------------------------------------------------===//
3958// Other Instructions.
3959//===----------------------------------------------------------------------===//
3960
3961
3962/// ParseCast
3963/// ::= CastOpc TypeAndValue 'to' Type
3964bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3965 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003966 LocTy Loc;
3967 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00003968 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003969 if (ParseTypeAndValue(Op, Loc, PFS) ||
3970 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3971 ParseType(DestTy))
3972 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003973
Chris Lattner89d856e2009-03-01 00:53:13 +00003974 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3975 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003976 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003977 getTypeString(Op->getType()) + "' to '" +
3978 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00003979 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003980 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3981 return false;
3982}
3983
3984/// ParseSelect
3985/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3986bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3987 LocTy Loc;
3988 Value *Op0, *Op1, *Op2;
3989 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3990 ParseToken(lltok::comma, "expected ',' after select condition") ||
3991 ParseTypeAndValue(Op1, PFS) ||
3992 ParseToken(lltok::comma, "expected ',' after select value") ||
3993 ParseTypeAndValue(Op2, PFS))
3994 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003995
Chris Lattnerac161bf2009-01-02 07:01:27 +00003996 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3997 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003998
Chris Lattnerac161bf2009-01-02 07:01:27 +00003999 Inst = SelectInst::Create(Op0, Op1, Op2);
4000 return false;
4001}
4002
Chris Lattnerb55ab542009-01-05 08:18:44 +00004003/// ParseVA_Arg
4004/// ::= 'va_arg' TypeAndValue ',' Type
4005bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004007 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004008 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004009 if (ParseTypeAndValue(Op, PFS) ||
4010 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004011 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004012 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004013
Chris Lattnerb55ab542009-01-05 08:18:44 +00004014 if (!EltTy->isFirstClassType())
4015 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004016
4017 Inst = new VAArgInst(Op, EltTy);
4018 return false;
4019}
4020
4021/// ParseExtractElement
4022/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4023bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4024 LocTy Loc;
4025 Value *Op0, *Op1;
4026 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4027 ParseToken(lltok::comma, "expected ',' after extract value") ||
4028 ParseTypeAndValue(Op1, PFS))
4029 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004030
Chris Lattnerac161bf2009-01-02 07:01:27 +00004031 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4032 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004033
Eric Christopherc9742252009-07-25 02:28:41 +00004034 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004035 return false;
4036}
4037
4038/// ParseInsertElement
4039/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4040bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4041 LocTy Loc;
4042 Value *Op0, *Op1, *Op2;
4043 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4044 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4045 ParseTypeAndValue(Op1, PFS) ||
4046 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4047 ParseTypeAndValue(Op2, PFS))
4048 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004049
Chris Lattnerac161bf2009-01-02 07:01:27 +00004050 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004051 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004052
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4054 return false;
4055}
4056
4057/// ParseShuffleVector
4058/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4059bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4060 LocTy Loc;
4061 Value *Op0, *Op1, *Op2;
4062 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4063 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4064 ParseTypeAndValue(Op1, PFS) ||
4065 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4066 ParseTypeAndValue(Op2, PFS))
4067 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004068
Chris Lattnerac161bf2009-01-02 07:01:27 +00004069 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004070 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004071
Chris Lattnerac161bf2009-01-02 07:01:27 +00004072 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4073 return false;
4074}
4075
4076/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004077/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004078int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004079 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004081
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004082 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004083 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4084 ParseValue(Ty, Op0, PFS) ||
4085 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004086 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004087 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4088 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004089
Chris Lattnerf4f03422009-12-30 05:27:33 +00004090 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004091 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4092 while (1) {
4093 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004094
Chris Lattner3822f632009-01-02 08:05:26 +00004095 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004096 break;
4097
Chris Lattnerf4f03422009-12-30 05:27:33 +00004098 if (Lex.getKind() == lltok::MetadataVar) {
4099 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004100 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004101 }
Devang Patel8f842d32009-10-16 18:45:49 +00004102
Chris Lattner3822f632009-01-02 08:05:26 +00004103 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004104 ParseValue(Ty, Op0, PFS) ||
4105 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004106 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004107 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4108 return true;
4109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004110
Chris Lattnerac161bf2009-01-02 07:01:27 +00004111 if (!Ty->isFirstClassType())
4112 return Error(TypeLoc, "phi node must have first class type");
4113
Jay Foad52131342011-03-30 11:28:46 +00004114 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004115 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4116 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4117 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004118 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004119}
4120
Bill Wendlingfae14752011-08-12 20:24:12 +00004121/// ParseLandingPad
4122/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4123/// Clause
4124/// ::= 'catch' TypeAndValue
4125/// ::= 'filter'
4126/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4127bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004128 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004129 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004130
4131 if (ParseType(Ty, TyLoc) ||
4132 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4133 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4134 return true;
4135
4136 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4137 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4138
4139 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4140 LandingPadInst::ClauseType CT;
4141 if (EatIfPresent(lltok::kw_catch))
4142 CT = LandingPadInst::Catch;
4143 else if (EatIfPresent(lltok::kw_filter))
4144 CT = LandingPadInst::Filter;
4145 else
4146 return TokError("expected 'catch' or 'filter' clause type");
4147
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004148 Value *V;
4149 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004150 if (ParseTypeAndValue(V, VLoc, PFS)) {
4151 delete LP;
4152 return true;
4153 }
4154
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004155 // A 'catch' type expects a non-array constant. A filter clause expects an
4156 // array constant.
4157 if (CT == LandingPadInst::Catch) {
4158 if (isa<ArrayType>(V->getType()))
4159 Error(VLoc, "'catch' clause has an invalid type");
4160 } else {
4161 if (!isa<ArrayType>(V->getType()))
4162 Error(VLoc, "'filter' clause has an invalid type");
4163 }
4164
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004165 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004166 }
4167
4168 Inst = LP;
4169 return false;
4170}
4171
Chris Lattnerac161bf2009-01-02 07:01:27 +00004172/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004173/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4174/// ParameterList OptionalAttrs
4175/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4176/// ParameterList OptionalAttrs
4177/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004178/// ParameterList OptionalAttrs
4179bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004180 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004181 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004182 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004183 LocTy BuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00004184 CallingConv::ID CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004185 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004186 LocTy RetTypeLoc;
4187 ValID CalleeID;
4188 SmallVector<ParamInfo, 16> ArgList;
4189 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004190
Reid Kleckner5772b772014-04-24 20:14:34 +00004191 if ((TCK != CallInst::TCK_None &&
4192 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004193 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004194 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004195 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004196 ParseValID(CalleeID) ||
4197 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004198 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004199 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004200 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004201
Chris Lattnerac161bf2009-01-02 07:01:27 +00004202 // If RetType is a non-function pointer type, then this is the short syntax
4203 // for the call, which means that RetType is just the return type. Infer the
4204 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004205 PointerType *PFTy = nullptr;
4206 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004207 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4208 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4209 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004210 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004211 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4212 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004213
Chris Lattnerac161bf2009-01-02 07:01:27 +00004214 if (!FunctionType::isValidReturnType(RetType))
4215 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004216
Owen Anderson4056ca92009-07-29 22:17:13 +00004217 Ty = FunctionType::get(RetType, ParamTypes, false);
4218 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004219 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004220
Chris Lattnerac161bf2009-01-02 07:01:27 +00004221 // Look up the callee.
4222 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004223 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004224
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004225 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004226 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004227 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004228 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4229 AttributeSet::ReturnIndex,
4230 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004231
Chris Lattnerac161bf2009-01-02 07:01:27 +00004232 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004233
Chris Lattnerac161bf2009-01-02 07:01:27 +00004234 // Loop through FunctionType's arguments and ensure they are specified
4235 // correctly. Also, gather any parameter attributes.
4236 FunctionType::param_iterator I = Ty->param_begin();
4237 FunctionType::param_iterator E = Ty->param_end();
4238 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004239 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004240 if (I != E) {
4241 ExpectedTy = *I++;
4242 } else if (!Ty->isVarArg()) {
4243 return Error(ArgList[i].Loc, "too many arguments specified");
4244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004245
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4247 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004248 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004249 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004250 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4251 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004252 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4253 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004254 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004255
Chris Lattnerac161bf2009-01-02 07:01:27 +00004256 if (I != E)
4257 return Error(CallLoc, "not enough parameters specified for call");
4258
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004259 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004260 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4261 AttributeSet::FunctionIndex,
4262 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004263
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004264 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004265 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004266
Jay Foad5bd375a2011-07-15 08:37:34 +00004267 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004268 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004269 CI->setCallingConv(CC);
4270 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004271 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004272 Inst = CI;
4273 return false;
4274}
4275
4276//===----------------------------------------------------------------------===//
4277// Memory Instructions.
4278//===----------------------------------------------------------------------===//
4279
4280/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004281/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004282int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004283 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004284 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004285 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004286 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004287
4288 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4289
Chris Lattner3822f632009-01-02 08:05:26 +00004290 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004291
Chris Lattnerb2f39502009-12-30 05:44:30 +00004292 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004293 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004294 if (Lex.getKind() == lltok::kw_align) {
4295 if (ParseOptionalAlignment(Alignment)) return true;
4296 } else if (Lex.getKind() == lltok::MetadataVar) {
4297 AteExtraComma = true;
4298 } else {
4299 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4300 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4301 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004302 }
4303 }
4304
Dan Gohman2140a742010-05-28 01:14:11 +00004305 if (Size && !Size->getType()->isIntegerTy())
4306 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004307
Reid Kleckner436c42e2014-01-17 23:58:17 +00004308 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4309 AI->setUsedWithInAlloca(IsInAlloca);
4310 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004311 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312}
4313
4314/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004315/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004316/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004317/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004318int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004319 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004320 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004321 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004322 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004323 AtomicOrdering Ordering = NotAtomic;
4324 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004325
4326 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004327 isAtomic = true;
4328 Lex.Lex();
4329 }
4330
Chris Lattnerbc639292011-11-27 06:56:53 +00004331 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004332 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004333 isVolatile = true;
4334 Lex.Lex();
4335 }
4336
Chris Lattnerb2f39502009-12-30 05:44:30 +00004337 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004338 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004339 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4340 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004341
Duncan Sands19d0b472010-02-16 11:11:14 +00004342 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4344 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004345 if (isAtomic && !Alignment)
4346 return Error(Loc, "atomic load must have explicit non-zero alignment");
4347 if (Ordering == Release || Ordering == AcquireRelease)
4348 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004349
Eli Friedman59b66882011-08-09 23:02:53 +00004350 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004351 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004352}
4353
4354/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004355
4356/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4357/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004358/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004359int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004360 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004361 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004362 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004363 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004364 AtomicOrdering Ordering = NotAtomic;
4365 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004366
4367 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004368 isAtomic = true;
4369 Lex.Lex();
4370 }
4371
Chris Lattnerbc639292011-11-27 06:56:53 +00004372 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004373 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004374 isVolatile = true;
4375 Lex.Lex();
4376 }
4377
Chris Lattnerac161bf2009-01-02 07:01:27 +00004378 if (ParseTypeAndValue(Val, Loc, PFS) ||
4379 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004380 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004381 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004382 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004383 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004384
Duncan Sands19d0b472010-02-16 11:11:14 +00004385 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386 return Error(PtrLoc, "store operand must be a pointer");
4387 if (!Val->getType()->isFirstClassType())
4388 return Error(Loc, "store operand must be a first class value");
4389 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4390 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004391 if (isAtomic && !Alignment)
4392 return Error(Loc, "atomic store must have explicit non-zero alignment");
4393 if (Ordering == Acquire || Ordering == AcquireRelease)
4394 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004395
Eli Friedman59b66882011-08-09 23:02:53 +00004396 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004397 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004398}
4399
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004400/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004401/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4402/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004403int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004404 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4405 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004406 AtomicOrdering SuccessOrdering = NotAtomic;
4407 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004408 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004409 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004410 bool isWeak = false;
4411
4412 if (EatIfPresent(lltok::kw_weak))
4413 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004414
4415 if (EatIfPresent(lltok::kw_volatile))
4416 isVolatile = true;
4417
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004418 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4419 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4420 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4421 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4422 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004423 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4424 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004425 return true;
4426
Tim Northovere94a5182014-03-11 10:48:52 +00004427 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004428 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004429 if (SuccessOrdering < FailureOrdering)
4430 return TokError("cmpxchg must be at least as ordered on success as failure");
4431 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4432 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004433 if (!Ptr->getType()->isPointerTy())
4434 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4435 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4436 return Error(CmpLoc, "compare value and pointer type do not match");
4437 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4438 return Error(NewLoc, "new value and pointer type do not match");
4439 if (!New->getType()->isIntegerTy())
4440 return Error(NewLoc, "cmpxchg operand must be an integer");
4441 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4442 if (Size < 8 || (Size & (Size - 1)))
4443 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4444 " integer");
4445
Tim Northover420a2162014-06-13 14:24:07 +00004446 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4447 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004448 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004449 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004450 Inst = CXI;
4451 return AteExtraComma ? InstExtraComma : InstNormal;
4452}
4453
4454/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004455/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4456/// 'singlethread'? AtomicOrdering
4457int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004458 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4459 bool AteExtraComma = false;
4460 AtomicOrdering Ordering = NotAtomic;
4461 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004462 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004463 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004464
4465 if (EatIfPresent(lltok::kw_volatile))
4466 isVolatile = true;
4467
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004468 switch (Lex.getKind()) {
4469 default: return TokError("expected binary operation in atomicrmw");
4470 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4471 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4472 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4473 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4474 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4475 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4476 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4477 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4478 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4479 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4480 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4481 }
4482 Lex.Lex(); // Eat the operation.
4483
4484 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4485 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4486 ParseTypeAndValue(Val, ValLoc, PFS) ||
4487 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4488 return true;
4489
4490 if (Ordering == Unordered)
4491 return TokError("atomicrmw cannot be unordered");
4492 if (!Ptr->getType()->isPointerTy())
4493 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4494 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4495 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4496 if (!Val->getType()->isIntegerTy())
4497 return Error(ValLoc, "atomicrmw operand must be an integer");
4498 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4499 if (Size < 8 || (Size & (Size - 1)))
4500 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4501 " integer");
4502
4503 AtomicRMWInst *RMWI =
4504 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4505 RMWI->setVolatile(isVolatile);
4506 Inst = RMWI;
4507 return AteExtraComma ? InstExtraComma : InstNormal;
4508}
4509
Eli Friedmanfee02c62011-07-25 23:16:38 +00004510/// ParseFence
4511/// ::= 'fence' 'singlethread'? AtomicOrdering
4512int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4513 AtomicOrdering Ordering = NotAtomic;
4514 SynchronizationScope Scope = CrossThread;
4515 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4516 return true;
4517
4518 if (Ordering == Unordered)
4519 return TokError("fence cannot be unordered");
4520 if (Ordering == Monotonic)
4521 return TokError("fence cannot be monotonic");
4522
4523 Inst = new FenceInst(Context, Ordering, Scope);
4524 return InstNormal;
4525}
4526
Chris Lattnerac161bf2009-01-02 07:01:27 +00004527/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004528/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004529int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004530 Value *Ptr = nullptr;
4531 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004532 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004533
Dan Gohman16cbbe42009-07-29 15:58:36 +00004534 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004535
Chris Lattner3822f632009-01-02 08:05:26 +00004536 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004537
Eli Benderskyd9806682013-04-22 17:03:42 +00004538 Type *BaseType = Ptr->getType();
4539 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4540 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004542
Chris Lattnerac161bf2009-01-02 07:01:27 +00004543 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004544 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004545 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004546 if (Lex.getKind() == lltok::MetadataVar) {
4547 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004548 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004549 }
Chris Lattner3822f632009-01-02 08:05:26 +00004550 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004551 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004552 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004553 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4554 return Error(EltLoc, "getelementptr index type missmatch");
4555 if (Val->getType()->isVectorTy()) {
4556 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4557 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4558 if (ValNumEl != PtrNumEl)
4559 return Error(EltLoc,
4560 "getelementptr vector index has a wrong number of elements");
4561 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004562 Indices.push_back(Val);
4563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004564
Eli Benderskyd9806682013-04-22 17:03:42 +00004565 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4566 return Error(Loc, "base element of getelementptr must be sized");
4567
4568 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004570 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004571 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004572 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004573 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004574}
4575
4576/// ParseExtractValue
4577/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004578int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004579 Value *Val; LocTy Loc;
4580 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004581 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004582 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004583 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 return true;
4585
Chris Lattner392be582010-02-12 20:49:41 +00004586 if (!Val->getType()->isAggregateType())
4587 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004588
Jay Foad57aa6362011-07-13 10:26:04 +00004589 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004591 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004592 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593}
4594
4595/// ParseInsertValue
4596/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004597int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004598 Value *Val0, *Val1; LocTy Loc0, Loc1;
4599 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004600 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4602 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4603 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004604 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004606
Chris Lattner392be582010-02-12 20:49:41 +00004607 if (!Val0->getType()->isAggregateType())
4608 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004609
Jay Foad57aa6362011-07-13 10:26:04 +00004610 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004611 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004612 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004613 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614}
Nick Lewycky49f89192009-04-04 07:22:01 +00004615
4616//===----------------------------------------------------------------------===//
4617// Embedded metadata.
4618//===----------------------------------------------------------------------===//
4619
4620/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004621/// ::= Element (',' Element)*
4622/// Element
4623/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004624bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004625 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004626 // Check for an empty list.
4627 if (Lex.getKind() == lltok::rbrace)
4628 return false;
4629
Nick Lewycky49f89192009-04-04 07:22:01 +00004630 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004631 // Null is a special case since it is typeless.
4632 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004633 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004634 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004635 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004636
Craig Topper2617dcc2014-04-15 06:32:26 +00004637 Value *V = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004638 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004639 Elts.push_back(V);
Nick Lewycky49f89192009-04-04 07:22:01 +00004640 } while (EatIfPresent(lltok::comma));
4641
4642 return false;
4643}