blob: a5b2aa586e46ce08e839d5b402dda40982182e29 [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"
Chris Lattnerac161bf2009-01-02 07:01:27 +000016#include "llvm/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) {
Chris Lattner0f214eb2011-06-18 21:18:23 +000031 std::string Result;
32 raw_string_ostream Tmp(Result);
33 Tmp << *T;
34 return Tmp.str();
35}
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
Chris Lattner8eff0152010-04-01 05:14:45 +000060 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
61 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +000062 Twine(SlotNo) + "'");
Chris Lattner8eff0152010-04-01 05:14:45 +000063 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
64 }
65 }
66 ForwardRefInstMetadata.clear();
67 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +000068
Manman Ren209b17c2013-09-28 00:22:27 +000069 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
70 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
71
Bill Wendlingb32b0412013-02-08 06:32:06 +000072 // Handle any function attribute group forward references.
73 for (std::map<Value*, std::vector<unsigned> >::iterator
74 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
75 I != E; ++I) {
76 Value *V = I->first;
77 std::vector<unsigned> &Vec = I->second;
78 AttrBuilder B;
79
80 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
81 VI != VE; ++VI)
82 B.merge(NumberedAttrBuilders[*VI]);
83
84 if (Function *Fn = dyn_cast<Function>(V)) {
85 AttributeSet AS = Fn->getAttributes();
86 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
87 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
88 AS.getFnAttributes());
89
90 FnAttrs.merge(B);
91
92 // If the alignment was parsed as an attribute, move to the alignment
93 // field.
94 if (FnAttrs.hasAlignmentAttr()) {
95 Fn->setAlignment(FnAttrs.getAlignment());
96 FnAttrs.removeAttribute(Attribute::Alignment);
97 }
98
99 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
100 AttributeSet::get(Context,
101 AttributeSet::FunctionIndex,
102 FnAttrs));
103 Fn->setAttributes(AS);
104 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
105 AttributeSet AS = CI->getAttributes();
106 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
107 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
108 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000109 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000110 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
111 AttributeSet::get(Context,
112 AttributeSet::FunctionIndex,
113 FnAttrs));
114 CI->setAttributes(AS);
115 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
116 AttributeSet AS = II->getAttributes();
117 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
118 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
119 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000120 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000121 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
122 AttributeSet::get(Context,
123 AttributeSet::FunctionIndex,
124 FnAttrs));
125 II->setAttributes(AS);
126 } else {
127 llvm_unreachable("invalid object with forward attribute group reference");
128 }
129 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000130
Chris Lattner3432c622009-10-28 03:39:23 +0000131 // If there are entries in ForwardRefBlockAddresses at this point, they are
132 // references after the function was defined. Resolve those now.
133 while (!ForwardRefBlockAddresses.empty()) {
134 // Okay, we are referencing an already-parsed function, resolve them now.
135 Function *TheFn = 0;
136 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
137 if (Fn.Kind == ValID::t_GlobalName)
138 TheFn = M->getFunction(Fn.StrVal);
139 else if (Fn.UIntVal < NumberedVals.size())
140 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000141
Chris Lattner3432c622009-10-28 03:39:23 +0000142 if (TheFn == 0)
143 return Error(Fn.Loc, "unknown function referenced by blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000144
Chris Lattner3432c622009-10-28 03:39:23 +0000145 // Resolve all these references.
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000146 if (ResolveForwardRefBlockAddresses(TheFn,
Chris Lattner3432c622009-10-28 03:39:23 +0000147 ForwardRefBlockAddresses.begin()->second,
148 0))
149 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000150
Chris Lattner3432c622009-10-28 03:39:23 +0000151 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
152 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000153
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000154 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
155 if (NumberedTypes[i].second.isValid())
156 return Error(NumberedTypes[i].second,
157 "use of undefined type '%" + Twine(i) + "'");
158
159 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
160 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
161 if (I->second.second.isValid())
162 return Error(I->second.second,
163 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000164
Chris Lattnerac161bf2009-01-02 07:01:27 +0000165 if (!ForwardRefVals.empty())
166 return Error(ForwardRefVals.begin()->second.second,
167 "use of undefined value '@" + ForwardRefVals.begin()->first +
168 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000169
Chris Lattnerac161bf2009-01-02 07:01:27 +0000170 if (!ForwardRefValIDs.empty())
171 return Error(ForwardRefValIDs.begin()->second.second,
172 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000173 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000174
Devang Pateld2541152009-07-08 19:23:54 +0000175 if (!ForwardRefMDNodes.empty())
176 return Error(ForwardRefMDNodes.begin()->second.second,
177 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000178 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000179
Devang Pateld2541152009-07-08 19:23:54 +0000180
Chris Lattnerac161bf2009-01-02 07:01:27 +0000181 // Look for intrinsic functions and CallInst that need to be upgraded
182 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
183 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000184
Manman Ren8b4306c2013-12-02 21:29:56 +0000185 UpgradeDebugInfo(*M);
186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 return false;
188}
189
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000190bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
Chris Lattner3432c622009-10-28 03:39:23 +0000191 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
192 PerFunctionState *PFS) {
193 // Loop over all the references, resolving them.
194 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
195 BasicBlock *Res;
Chris Lattneraa99c942009-11-01 01:27:45 +0000196 if (PFS) {
Chris Lattner3432c622009-10-28 03:39:23 +0000197 if (Refs[i].first.Kind == ValID::t_LocalName)
198 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattneraa99c942009-11-01 01:27:45 +0000199 else
Chris Lattner3432c622009-10-28 03:39:23 +0000200 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
201 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
202 return Error(Refs[i].first.Loc,
Chris Lattnera38a4df2009-11-02 18:28:45 +0000203 "cannot take address of numeric label after the function is defined");
Chris Lattner3432c622009-10-28 03:39:23 +0000204 } else {
205 Res = dyn_cast_or_null<BasicBlock>(
206 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
207 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000208
Chris Lattneraa99c942009-11-01 01:27:45 +0000209 if (Res == 0)
Chris Lattner3432c622009-10-28 03:39:23 +0000210 return Error(Refs[i].first.Loc,
211 "referenced value is not a basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000212
Chris Lattner3432c622009-10-28 03:39:23 +0000213 // Get the BlockAddress for this and update references to use it.
214 BlockAddress *BA = BlockAddress::get(TheFn, Res);
215 Refs[i].second->replaceAllUsesWith(BA);
216 Refs[i].second->eraseFromParent();
217 }
218 return false;
219}
220
221
Chris Lattnerac161bf2009-01-02 07:01:27 +0000222//===----------------------------------------------------------------------===//
223// Top-Level Entities
224//===----------------------------------------------------------------------===//
225
226bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 while (1) {
228 switch (Lex.getKind()) {
229 default: return TokError("expected top-level entity");
230 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000231 case lltok::kw_declare: if (ParseDeclare()) return true; break;
232 case lltok::kw_define: if (ParseDefine()) return true; break;
233 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
234 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000235 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000236 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000237 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000238 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000240 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000241 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000242
243 // The Global variable production with no name can have many different
244 // optional leading prefixes, the production is:
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000245 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
246 // OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000247 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000248 case lltok::kw_private: // OptionalLinkage
249 case lltok::kw_linker_private: // OptionalLinkage
250 case lltok::kw_linker_private_weak: // OptionalLinkage
251 case lltok::kw_internal: // OptionalLinkage
252 case lltok::kw_weak: // OptionalLinkage
253 case lltok::kw_weak_odr: // OptionalLinkage
254 case lltok::kw_linkonce: // OptionalLinkage
255 case lltok::kw_linkonce_odr: // OptionalLinkage
256 case lltok::kw_appending: // OptionalLinkage
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000257 case lltok::kw_dllexport: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000258 case lltok::kw_common: // OptionalLinkage
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000259 case lltok::kw_dllimport: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000260 case lltok::kw_extern_weak: // OptionalLinkage
261 case lltok::kw_external: { // OptionalLinkage
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000262 unsigned Linkage, Visibility;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000263 if (ParseOptionalLinkage(Linkage) ||
264 ParseOptionalVisibility(Visibility) ||
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000265 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 return true;
267 break;
268 }
269 case lltok::kw_default: // OptionalVisibility
270 case lltok::kw_hidden: // OptionalVisibility
271 case lltok::kw_protected: { // OptionalVisibility
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000272 unsigned Visibility;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000273 if (ParseOptionalVisibility(Visibility) ||
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000274 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000275 return true;
276 break;
277 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000278
Chris Lattnerac161bf2009-01-02 07:01:27 +0000279 case lltok::kw_thread_local: // OptionalThreadLocal
280 case lltok::kw_addrspace: // OptionalAddrSpace
281 case lltok::kw_constant: // GlobalType
282 case lltok::kw_global: // GlobalType
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000283 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000284 break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000285
286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000287 }
288 }
289}
290
291
292/// toplevelentity
293/// ::= 'module' 'asm' STRINGCONSTANT
294bool LLParser::ParseModuleAsm() {
295 assert(Lex.getKind() == lltok::kw_module);
296 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000297
298 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000299 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
300 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000301
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000302 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000303 return false;
304}
305
306/// toplevelentity
307/// ::= 'target' 'triple' '=' STRINGCONSTANT
308/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
309bool LLParser::ParseTargetDefinition() {
310 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000311 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 switch (Lex.Lex()) {
313 default: return TokError("unknown target property");
314 case lltok::kw_triple:
315 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000316 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
317 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000319 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return false;
321 case lltok::kw_datalayout:
322 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000323 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
324 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000326 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return false;
328 }
329}
330
Bill Wendling706d3d62012-11-28 08:41:48 +0000331/// toplevelentity
332/// ::= 'deplibs' '=' '[' ']'
333/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334/// FIXME: Remove in 4.0. Currently parse, but ignore.
335bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
337 Lex.Lex();
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
340 return true;
341
342 if (EatIfPresent(lltok::rsquare))
343 return false;
344
345 do {
346 std::string Str;
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
349
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
351}
352
Dan Gohman466876b2009-08-12 23:32:33 +0000353/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000354/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000355bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000356 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000358 Lex.Lex(); // eat LocalVarID;
359
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
362 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000363
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000364 if (TypeID >= NumberedTypes.size())
365 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000366
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000367 Type *Result = 0;
368 if (ParseStructDefinition(TypeLoc, "",
369 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000370
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000371 if (!isa<StructType>(Result)) {
372 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
373 if (Entry.first)
374 return Error(TypeLoc, "non-struct types may not be recursive");
375 Entry.first = Result;
376 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000378
Chris Lattnerac161bf2009-01-02 07:01:27 +0000379 return false;
380}
381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383/// toplevelentity
384/// ::= LocalVar '=' 'type' type
385bool LLParser::ParseNamedType() {
386 std::string Name = Lex.getStrVal();
387 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000388 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000389
Chris Lattner3822f632009-01-02 08:05:26 +0000390 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000391 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000392 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000393
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000394 Type *Result = 0;
395 if (ParseStructDefinition(NameLoc, Name,
396 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000397
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000398 if (!isa<StructType>(Result)) {
399 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
400 if (Entry.first)
401 return Error(NameLoc, "non-struct types may not be recursive");
402 Entry.first = Result;
403 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000407}
408
409
410/// toplevelentity
411/// ::= 'declare' FunctionHeader
412bool LLParser::ParseDeclare() {
413 assert(Lex.getKind() == lltok::kw_declare);
414 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000415
Chris Lattnerac161bf2009-01-02 07:01:27 +0000416 Function *F;
417 return ParseFunctionHeader(F, false);
418}
419
420/// toplevelentity
421/// ::= 'define' FunctionHeader '{' ...
422bool LLParser::ParseDefine() {
423 assert(Lex.getKind() == lltok::kw_define);
424 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000425
Chris Lattnerac161bf2009-01-02 07:01:27 +0000426 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000427 return ParseFunctionHeader(F, true) ||
428 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429}
430
Chris Lattner3822f632009-01-02 08:05:26 +0000431/// ParseGlobalType
432/// ::= 'constant'
433/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434bool LLParser::ParseGlobalType(bool &IsConstant) {
435 if (Lex.getKind() == lltok::kw_constant)
436 IsConstant = true;
437 else if (Lex.getKind() == lltok::kw_global)
438 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000439 else {
440 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000442 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 Lex.Lex();
444 return false;
445}
446
Dan Gohman466876b2009-08-12 23:32:33 +0000447/// ParseUnnamedGlobal:
448/// OptionalVisibility ALIAS ...
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000449/// OptionalLinkage OptionalVisibility ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000450/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000451/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000452bool LLParser::ParseUnnamedGlobal() {
453 unsigned VarID = NumberedVals.size();
454 std::string Name;
455 LocTy NameLoc = Lex.getLoc();
456
457 // Handle the GlobalID form.
458 if (Lex.getKind() == lltok::GlobalID) {
459 if (Lex.getUIntVal() != VarID)
460 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000461 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000462 Lex.Lex(); // eat GlobalID;
463
464 if (ParseToken(lltok::equal, "expected '=' after name"))
465 return true;
466 }
467
468 bool HasLinkage;
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000469 unsigned Linkage, Visibility;
Dan Gohman466876b2009-08-12 23:32:33 +0000470 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000471 ParseOptionalVisibility(Visibility))
Dan Gohman466876b2009-08-12 23:32:33 +0000472 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000473
Dan Gohman466876b2009-08-12 23:32:33 +0000474 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000475 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
476 return ParseAlias(Name, NameLoc, Visibility);
Dan Gohman466876b2009-08-12 23:32:33 +0000477}
478
Chris Lattnerac161bf2009-01-02 07:01:27 +0000479/// ParseNamedGlobal:
480/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000481/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000482bool LLParser::ParseNamedGlobal() {
483 assert(Lex.getKind() == lltok::GlobalVar);
484 LocTy NameLoc = Lex.getLoc();
485 std::string Name = Lex.getStrVal();
486 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000487
Chris Lattnerac161bf2009-01-02 07:01:27 +0000488 bool HasLinkage;
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000489 unsigned Linkage, Visibility;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000490 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
491 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000492 ParseOptionalVisibility(Visibility))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000494
Chris Lattnerac161bf2009-01-02 07:01:27 +0000495 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000496 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
497 return ParseAlias(Name, NameLoc, Visibility);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000498}
499
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000500// MDString:
501// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000502bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000503 std::string Str;
504 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000505 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000506 return false;
507}
508
509// MDNode:
510// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000511//
512/// This version of ParseMDNodeID returns the slot number and null in the case
513/// of a forward reference.
514bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
515 // !{ ..., !42, ... }
516 if (ParseUInt32(SlotNo)) return true;
517
518 // Check existing MDNode.
519 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
520 Result = NumberedMetadata[SlotNo];
521 else
522 Result = 0;
523 return false;
524}
525
Chris Lattner6dac02a2009-12-30 04:15:23 +0000526bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000527 // !{ ..., !42, ... }
528 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000529 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000530
Chris Lattner8eff0152010-04-01 05:14:45 +0000531 // If not a forward reference, just return it now.
532 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000533
Chris Lattner8eff0152010-04-01 05:14:45 +0000534 // Otherwise, create MDNode forward reference.
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000535 MDNode *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000536 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000537
Chris Lattnerfc58af22009-12-30 04:51:58 +0000538 if (NumberedMetadata.size() <= MID)
539 NumberedMetadata.resize(MID+1);
540 NumberedMetadata[MID] = FwdNode;
Chris Lattner1797fc72009-12-29 21:53:55 +0000541 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000542 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000543}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000544
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000545/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000546/// !foo = !{ !1, !2 }
547bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000548 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000549 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000550 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000551
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000552 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000553 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000554 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000555 return true;
556
Dan Gohman2637cc12010-07-21 23:38:33 +0000557 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000558 if (Lex.getKind() != lltok::rbrace)
559 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000560 if (ParseToken(lltok::exclaim, "Expected '!' here"))
561 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000562
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000563 MDNode *N = 0;
564 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000565 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000566 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000567
568 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
569 return true;
570
Devang Patelbe626972009-07-29 00:34:02 +0000571 return false;
572}
573
Devang Patel39e64d42009-07-01 19:21:12 +0000574/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000575/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000576bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000577 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000578 Lex.Lex();
579 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000580
581 LocTy TyLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000582 Type *Ty = 0;
Devang Patele059ba6e2009-07-23 01:07:34 +0000583 SmallVector<Value *, 16> Elts;
Chris Lattner278bc952009-12-29 22:40:21 +0000584 if (ParseUInt32(MetadataID) ||
585 ParseToken(lltok::equal, "expected '=' here") ||
586 ParseType(Ty, TyLoc) ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000587 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner278bc952009-12-29 22:40:21 +0000588 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandezb8fd1522010-01-10 07:14:18 +0000589 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner278bc952009-12-29 22:40:21 +0000590 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patele059ba6e2009-07-23 01:07:34 +0000591 return true;
592
Jay Foad5514afe2011-04-21 19:59:31 +0000593 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000594
Chris Lattnerfc58af22009-12-30 04:51:58 +0000595 // See if this was forward referenced, if so, handle it.
Chris Lattner218b22f2009-12-29 21:43:58 +0000596 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Pateld2541152009-07-08 19:23:54 +0000597 FI = ForwardRefMDNodes.find(MetadataID);
598 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman16a5d982010-08-20 22:02:26 +0000599 MDNode *Temp = FI->second.first;
600 Temp->replaceAllUsesWith(Init);
601 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000602 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000603
Chris Lattnerfc58af22009-12-30 04:51:58 +0000604 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
605 } else {
606 if (MetadataID >= NumberedMetadata.size())
607 NumberedMetadata.resize(MetadataID+1);
608
609 if (NumberedMetadata[MetadataID] != 0)
610 return TokError("Metadata id is already used");
611 NumberedMetadata[MetadataID] = Init;
Devang Pateld2541152009-07-08 19:23:54 +0000612 }
613
Devang Patel39e64d42009-07-01 19:21:12 +0000614 return false;
615}
616
Chris Lattnerac161bf2009-01-02 07:01:27 +0000617/// ParseAlias:
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000618/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
Chris Lattnerac161bf2009-01-02 07:01:27 +0000619/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000620/// ::= TypeAndValue
621/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohman1639c392009-07-27 21:53:46 +0000622/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000623///
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000624/// Everything through visibility has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000625///
626bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000627 unsigned Visibility) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000628 assert(Lex.getKind() == lltok::kw_alias);
629 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000630 LocTy LinkageLoc = Lex.getLoc();
Rafael Espindola78527052013-10-06 15:10:43 +0000631 unsigned L;
632 if (ParseOptionalLinkage(L))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000633 return true;
634
Rafael Espindola78527052013-10-06 15:10:43 +0000635 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
636
Rafael Espindolacaa43562013-10-09 16:07:32 +0000637 if(!GlobalAlias::isValidLinkage(Linkage))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000638 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000639
Chris Lattnerac161bf2009-01-02 07:01:27 +0000640 Constant *Aliasee;
641 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000642 if (Lex.getKind() != lltok::kw_bitcast &&
643 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000644 if (ParseGlobalTypeAndValue(Aliasee)) return true;
645 } else {
646 // The bitcast dest type is not present, it is implied by the dest type.
647 ValID ID;
648 if (ParseValID(ID)) return true;
649 if (ID.Kind != ValID::t_Constant)
650 return Error(AliaseeLoc, "invalid aliasee");
651 Aliasee = ID.ConstantVal;
652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000653
Duncan Sands19d0b472010-02-16 11:11:14 +0000654 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +0000655 return Error(AliaseeLoc, "alias must have pointer type");
656
657 // Okay, create the alias but do not insert it into the module yet.
658 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
659 (GlobalValue::LinkageTypes)Linkage, Name,
660 Aliasee);
661 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000662
Chris Lattnerac161bf2009-01-02 07:01:27 +0000663 // See if this value already exists in the symbol table. If so, it is either
664 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000665 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000666 // See if this was a redefinition. If so, there is no entry in
667 // ForwardRefVals.
668 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
669 I = ForwardRefVals.find(Name);
670 if (I == ForwardRefVals.end())
671 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
672
673 // Otherwise, this was a definition of forward ref. Verify that types
674 // agree.
675 if (Val->getType() != GA->getType())
676 return Error(NameLoc,
677 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678
Chris Lattnerac161bf2009-01-02 07:01:27 +0000679 // If they agree, just RAUW the old value with the alias and remove the
680 // forward ref info.
681 Val->replaceAllUsesWith(GA);
682 Val->eraseFromParent();
683 ForwardRefVals.erase(I);
684 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000685
Chris Lattnerac161bf2009-01-02 07:01:27 +0000686 // Insert into the module, we know its name won't collide now.
687 M->getAliasList().push_back(GA);
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000688 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000689
Chris Lattnerac161bf2009-01-02 07:01:27 +0000690 return false;
691}
692
693/// ParseGlobal
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000694/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
695/// OptionalAddrSpace OptionalUnNammedAddr
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000696/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000697/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
698/// OptionalAddrSpace OptionalUnNammedAddr
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000699/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700///
701/// Everything through visibility has been parsed already.
702///
703bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
704 unsigned Linkage, bool HasLinkage,
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000705 unsigned Visibility) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000706 unsigned AddrSpace;
Shuxin Yang2e1890e2013-10-27 03:08:44 +0000707 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000708 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola026d1522011-01-13 01:30:30 +0000709 LocTy UnnamedAddrLoc;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000710 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000712
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000713 Type *Ty = 0;
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000714 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindola026d1522011-01-13 01:30:30 +0000716 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
717 &UnnamedAddrLoc) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000718 ParseOptionalToken(lltok::kw_externally_initialized,
719 IsExternallyInitialized,
720 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000721 ParseGlobalType(IsConstant) ||
722 ParseType(Ty, TyLoc))
723 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000724
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725 // If the linkage is specified and is external, then no initializer is
726 // present.
727 Constant *Init = 0;
Nico Rieck9d2e0df2014-01-14 12:38:32 +0000728 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
729 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000730 Linkage != GlobalValue::ExternalLinkage)) {
731 if (ParseGlobalValue(Ty, Init))
732 return true;
733 }
734
Duncan Sands19d0b472010-02-16 11:11:14 +0000735 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000736 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
Chris Lattnerac161bf2009-01-02 07:01:27 +0000738 GlobalVariable *GV = 0;
739
740 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000741 if (!Name.empty()) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000742 if (GlobalValue *GVal = M->getNamedValue(Name)) {
743 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
744 return Error(NameLoc, "redefinition of global '@" + Name + "'");
745 GV = cast<GlobalVariable>(GVal);
746 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 } else {
748 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
749 I = ForwardRefValIDs.find(NumberedVals.size());
750 if (I != ForwardRefValIDs.end()) {
751 GV = cast<GlobalVariable>(I->second.first);
752 ForwardRefValIDs.erase(I);
753 }
754 }
755
756 if (GV == 0) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000758 Name, 0, GlobalVariable::NotThreadLocal,
759 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000760 } else {
761 if (GV->getType()->getElementType() != Ty)
762 return Error(TyLoc,
763 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000764
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765 // Move the forward-reference to the correct spot in the module.
766 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
767 }
768
769 if (Name.empty())
770 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
Chris Lattnerac161bf2009-01-02 07:01:27 +0000772 // Set the parsed properties on the global.
773 if (Init)
774 GV->setInitializer(Init);
775 GV->setConstant(IsConstant);
776 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
777 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000778 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000779 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000780 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000781
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 // Parse attributes on the global.
783 while (Lex.getKind() == lltok::comma) {
784 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000785
Chris Lattnerac161bf2009-01-02 07:01:27 +0000786 if (Lex.getKind() == lltok::kw_section) {
787 Lex.Lex();
788 GV->setSection(Lex.getStrVal());
789 if (ParseToken(lltok::StringConstant, "expected global section string"))
790 return true;
791 } else if (Lex.getKind() == lltok::kw_align) {
792 unsigned Alignment;
793 if (ParseOptionalAlignment(Alignment)) return true;
794 GV->setAlignment(Alignment);
795 } else {
796 TokError("unknown global variable property!");
797 }
798 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000799
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 return false;
801}
802
Bill Wendling63b88192013-02-06 06:52:58 +0000803/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000804/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000805bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000806 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000807 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000808 Lex.Lex();
809
810 assert(Lex.getKind() == lltok::AttrGrpID);
Bill Wendling63b88192013-02-06 06:52:58 +0000811 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000812 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000813 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000814 Lex.Lex();
815
816 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000817 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000818 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000819 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000820 ParseToken(lltok::rbrace, "expected end of attribute group"))
821 return true;
822
Bill Wendlingb32b0412013-02-08 06:32:06 +0000823 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000824 return Error(AttrGrpLoc, "attribute group has no attributes");
825
826 return false;
827}
828
Bill Wendling8b0321d2013-02-08 00:52:31 +0000829/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000830/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000831bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
832 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000833 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000834 bool HaveError = false;
835
836 B.clear();
837
Bill Wendling63b88192013-02-06 06:52:58 +0000838 while (true) {
839 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000840 if (Token == lltok::kw_builtin)
841 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000842 switch (Token) {
843 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000844 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000845 return Error(Lex.getLoc(), "unterminated attribute group");
846 case lltok::rbrace:
847 // Finished.
848 return false;
849
Bill Wendlingb32b0412013-02-08 06:32:06 +0000850 case lltok::AttrGrpID: {
851 // Allow a function to reference an attribute group:
852 //
853 // define void @foo() #1 { ... }
854 if (inAttrGrp)
855 HaveError |=
856 Error(Lex.getLoc(),
857 "cannot have an attribute group reference in an attribute group");
858
859 unsigned AttrGrpNum = Lex.getUIntVal();
860 if (inAttrGrp) break;
861
862 // Save the reference to the attribute group. We'll fill it in later.
863 FwdRefAttrGrps.push_back(AttrGrpNum);
864 break;
865 }
Bill Wendling63b88192013-02-06 06:52:58 +0000866 // Target-dependent attributes:
867 case lltok::StringConstant: {
868 std::string Attr = Lex.getStrVal();
869 Lex.Lex();
870 std::string Val;
871 if (EatIfPresent(lltok::equal) &&
872 ParseStringConstant(Val))
873 return true;
874
875 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000876 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000877 }
878
879 // Target-independent attributes:
880 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000881 // As a hack, we allow function alignment to be initially parsed as an
882 // attribute on a function declaration/definition or added to an attribute
883 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000884 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000885 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000886 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000887 if (ParseToken(lltok::equal, "expected '=' here") ||
888 ParseUInt32(Alignment))
889 return true;
890 } else {
891 if (ParseOptionalAlignment(Alignment))
892 return true;
893 }
Bill Wendling63b88192013-02-06 06:52:58 +0000894 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000895 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000896 }
897 case lltok::kw_alignstack: {
898 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000899 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000900 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000901 if (ParseToken(lltok::equal, "expected '=' here") ||
902 ParseUInt32(Alignment))
903 return true;
904 } else {
905 if (ParseOptionalStackAlignment(Alignment))
906 return true;
907 }
Bill Wendling63b88192013-02-06 06:52:58 +0000908 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000909 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000910 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000911 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000912 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000913 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000914 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
915 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
916 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
917 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
918 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
919 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
920 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
921 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
922 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
923 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
924 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000925 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000926 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
927 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
928 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
929 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
930 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
931 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
932 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
933 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
934 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
935 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
936 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000937
938 // Error handling.
939 case lltok::kw_inreg:
940 case lltok::kw_signext:
941 case lltok::kw_zeroext:
942 HaveError |=
943 Error(Lex.getLoc(),
944 "invalid use of attribute on a function");
945 break;
946 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +0000947 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000948 case lltok::kw_nest:
949 case lltok::kw_noalias:
950 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +0000951 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000952 case lltok::kw_sret:
953 HaveError |=
954 Error(Lex.getLoc(),
955 "invalid use of parameter-only attribute on a function");
956 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000957 }
958
959 Lex.Lex();
960 }
961}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000962
963//===----------------------------------------------------------------------===//
964// GlobalValue Reference/Resolution Routines.
965//===----------------------------------------------------------------------===//
966
967/// GetGlobalVal - Get a value with the specified name or ID, creating a
968/// forward reference record if needed. This can return null if the value
969/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +0000970GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +0000971 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +0000972 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000973 if (PTy == 0) {
974 Error(Loc, "global variable reference must have pointer type");
975 return 0;
976 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000977
Chris Lattnerac161bf2009-01-02 07:01:27 +0000978 // Look this name up in the normal function symbol table.
979 GlobalValue *Val =
980 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000981
Chris Lattnerac161bf2009-01-02 07:01:27 +0000982 // If this is a forward reference for the value, see if we already created a
983 // forward ref record.
984 if (Val == 0) {
985 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
986 I = ForwardRefVals.find(Name);
987 if (I != ForwardRefVals.end())
988 Val = I->second.first;
989 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000990
Chris Lattnerac161bf2009-01-02 07:01:27 +0000991 // If we have the value in the symbol table or fwd-ref table, return it.
992 if (Val) {
993 if (Val->getType() == Ty) return Val;
994 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +0000995 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000996 return 0;
997 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000998
Chris Lattnerac161bf2009-01-02 07:01:27 +0000999 // Otherwise, create a new forward reference for this value and remember it.
1000 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001001 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001002 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001003 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001004 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001005 GlobalValue::ExternalWeakLinkage, 0, Name,
1006 0, GlobalVariable::NotThreadLocal,
1007 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001008
Chris Lattnerac161bf2009-01-02 07:01:27 +00001009 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1010 return FwdVal;
1011}
1012
Chris Lattner229907c2011-07-18 04:54:35 +00001013GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1014 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001015 if (PTy == 0) {
1016 Error(Loc, "global variable reference must have pointer type");
1017 return 0;
1018 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001019
Chris Lattnerac161bf2009-01-02 07:01:27 +00001020 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001021
Chris Lattnerac161bf2009-01-02 07:01:27 +00001022 // If this is a forward reference for the value, see if we already created a
1023 // forward ref record.
1024 if (Val == 0) {
1025 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1026 I = ForwardRefValIDs.find(ID);
1027 if (I != ForwardRefValIDs.end())
1028 Val = I->second.first;
1029 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001030
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031 // If we have the value in the symbol table or fwd-ref table, return it.
1032 if (Val) {
1033 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001034 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001035 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001036 return 0;
1037 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001038
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 // Otherwise, create a new forward reference for this value and remember it.
1040 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001041 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001042 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001043 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001044 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1045 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001046
Chris Lattnerac161bf2009-01-02 07:01:27 +00001047 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1048 return FwdVal;
1049}
1050
1051
1052//===----------------------------------------------------------------------===//
1053// Helper Routines.
1054//===----------------------------------------------------------------------===//
1055
1056/// ParseToken - If the current token has the specified kind, eat it and return
1057/// success. Otherwise, emit the specified error and return failure.
1058bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1059 if (Lex.getKind() != T)
1060 return TokError(ErrMsg);
1061 Lex.Lex();
1062 return false;
1063}
1064
Chris Lattner3822f632009-01-02 08:05:26 +00001065/// ParseStringConstant
1066/// ::= StringConstant
1067bool LLParser::ParseStringConstant(std::string &Result) {
1068 if (Lex.getKind() != lltok::StringConstant)
1069 return TokError("expected string constant");
1070 Result = Lex.getStrVal();
1071 Lex.Lex();
1072 return false;
1073}
1074
1075/// ParseUInt32
1076/// ::= uint32
1077bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1079 return TokError("expected integer");
1080 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1081 if (Val64 != unsigned(Val64))
1082 return TokError("expected 32-bit integer (too large)");
1083 Val = Val64;
1084 Lex.Lex();
1085 return false;
1086}
1087
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001088/// ParseTLSModel
1089/// := 'localdynamic'
1090/// := 'initialexec'
1091/// := 'localexec'
1092bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1093 switch (Lex.getKind()) {
1094 default:
1095 return TokError("expected localdynamic, initialexec or localexec");
1096 case lltok::kw_localdynamic:
1097 TLM = GlobalVariable::LocalDynamicTLSModel;
1098 break;
1099 case lltok::kw_initialexec:
1100 TLM = GlobalVariable::InitialExecTLSModel;
1101 break;
1102 case lltok::kw_localexec:
1103 TLM = GlobalVariable::LocalExecTLSModel;
1104 break;
1105 }
1106
1107 Lex.Lex();
1108 return false;
1109}
1110
1111/// ParseOptionalThreadLocal
1112/// := /*empty*/
1113/// := 'thread_local'
1114/// := 'thread_local' '(' tlsmodel ')'
1115bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1116 TLM = GlobalVariable::NotThreadLocal;
1117 if (!EatIfPresent(lltok::kw_thread_local))
1118 return false;
1119
1120 TLM = GlobalVariable::GeneralDynamicTLSModel;
1121 if (Lex.getKind() == lltok::lparen) {
1122 Lex.Lex();
1123 return ParseTLSModel(TLM) ||
1124 ParseToken(lltok::rparen, "expected ')' after thread local model");
1125 }
1126 return false;
1127}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001128
1129/// ParseOptionalAddrSpace
1130/// := /*empty*/
1131/// := 'addrspace' '(' uint32 ')'
1132bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1133 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001134 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001136 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001137 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001138 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001139}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001140
Bill Wendling34c2eb22012-12-04 23:40:58 +00001141/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1142bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1143 bool HaveError = false;
1144
1145 B.clear();
1146
1147 while (1) {
1148 lltok::Kind Token = Lex.getKind();
1149 switch (Token) {
1150 default: // End of attributes.
1151 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 case lltok::kw_align: {
1153 unsigned Alignment;
1154 if (ParseOptionalAlignment(Alignment))
1155 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001156 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001157 continue;
1158 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001159 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Reid Klecknera534a382013-12-19 02:14:12 +00001160 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001161 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1162 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1163 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1164 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001165 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1166 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001167 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001168 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1169 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1170 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001171
Stephen Lin7577ed52013-04-20 13:16:13 +00001172 case lltok::kw_alignstack:
1173 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001174 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001175 case lltok::kw_inlinehint:
1176 case lltok::kw_minsize:
1177 case lltok::kw_naked:
1178 case lltok::kw_nobuiltin:
1179 case lltok::kw_noduplicate:
1180 case lltok::kw_noimplicitfloat:
1181 case lltok::kw_noinline:
1182 case lltok::kw_nonlazybind:
1183 case lltok::kw_noredzone:
1184 case lltok::kw_noreturn:
1185 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001186 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001187 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001188 case lltok::kw_returns_twice:
1189 case lltok::kw_sanitize_address:
1190 case lltok::kw_sanitize_memory:
1191 case lltok::kw_sanitize_thread:
1192 case lltok::kw_ssp:
1193 case lltok::kw_sspreq:
1194 case lltok::kw_sspstrong:
1195 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001196 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1197 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001198 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001199
Bill Wendling34c2eb22012-12-04 23:40:58 +00001200 Lex.Lex();
1201 }
1202}
1203
1204/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1205bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1206 bool HaveError = false;
1207
1208 B.clear();
1209
1210 while (1) {
1211 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001212 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001213 default: // End of attributes.
1214 return HaveError;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001215 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1216 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1217 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1218 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001219
Bill Wendling34c2eb22012-12-04 23:40:58 +00001220 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001221 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001222 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001223 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001224 case lltok::kw_nest:
1225 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001226 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001227 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001228 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001229 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001230
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001231 case lltok::kw_alignstack:
1232 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001233 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001234 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001235 case lltok::kw_inlinehint:
1236 case lltok::kw_minsize:
1237 case lltok::kw_naked:
1238 case lltok::kw_nobuiltin:
1239 case lltok::kw_noduplicate:
1240 case lltok::kw_noimplicitfloat:
1241 case lltok::kw_noinline:
1242 case lltok::kw_nonlazybind:
1243 case lltok::kw_noredzone:
1244 case lltok::kw_noreturn:
1245 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001246 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001247 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001248 case lltok::kw_returns_twice:
1249 case lltok::kw_sanitize_address:
1250 case lltok::kw_sanitize_memory:
1251 case lltok::kw_sanitize_thread:
1252 case lltok::kw_ssp:
1253 case lltok::kw_sspreq:
1254 case lltok::kw_sspstrong:
1255 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001256 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001257 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001258
1259 case lltok::kw_readnone:
1260 case lltok::kw_readonly:
1261 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001262 }
1263
Chris Lattnerac161bf2009-01-02 07:01:27 +00001264 Lex.Lex();
1265 }
1266}
1267
1268/// ParseOptionalLinkage
1269/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001270/// ::= 'private'
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001271/// ::= 'linker_private'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001272/// ::= 'linker_private_weak'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001273/// ::= 'internal'
1274/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001275/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001276/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001277/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001278/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001279/// ::= 'appending'
Nico Rieck9d2e0df2014-01-14 12:38:32 +00001280/// ::= 'dllexport'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001281/// ::= 'common'
Nico Rieck9d2e0df2014-01-14 12:38:32 +00001282/// ::= 'dllimport'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001283/// ::= 'extern_weak'
1284/// ::= 'external'
1285bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1286 HasLinkage = false;
1287 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001288 default: Res=GlobalValue::ExternalLinkage; return false;
1289 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1290 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001291 case lltok::kw_linker_private_weak:
1292 Res = GlobalValue::LinkerPrivateWeakLinkage;
1293 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001294 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1295 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1296 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1297 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1298 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001299 case lltok::kw_available_externally:
1300 Res = GlobalValue::AvailableExternallyLinkage;
1301 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001302 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Nico Rieck9d2e0df2014-01-14 12:38:32 +00001303 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001304 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Nico Rieck9d2e0df2014-01-14 12:38:32 +00001305 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001306 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1307 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001308 }
1309 Lex.Lex();
1310 HasLinkage = true;
1311 return false;
1312}
1313
1314/// ParseOptionalVisibility
1315/// ::= /*empty*/
1316/// ::= 'default'
1317/// ::= 'hidden'
1318/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001319///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001320bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1321 switch (Lex.getKind()) {
1322 default: Res = GlobalValue::DefaultVisibility; return false;
1323 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1324 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1325 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1326 }
1327 Lex.Lex();
1328 return false;
1329}
1330
1331/// ParseOptionalCallingConv
1332/// ::= /*empty*/
1333/// ::= 'ccc'
1334/// ::= 'fastcc'
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001335/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001336/// ::= 'coldcc'
1337/// ::= 'x86_stdcallcc'
1338/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001339/// ::= 'x86_thiscallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001340/// ::= 'arm_apcscc'
1341/// ::= 'arm_aapcscc'
1342/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001343/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001344/// ::= 'ptx_kernel'
1345/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001346/// ::= 'spir_func'
1347/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001348/// ::= 'x86_64_sysvcc'
1349/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001350/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001351/// ::= 'anyregcc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001352/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001353///
Sandeep Patel68c5f472009-09-02 08:44:58 +00001354bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001355 switch (Lex.getKind()) {
1356 default: CC = CallingConv::C; return false;
1357 case lltok::kw_ccc: CC = CallingConv::C; break;
1358 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1359 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1360 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1361 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001362 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001363 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1364 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1365 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001366 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001367 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1368 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001369 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1370 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001371 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001372 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1373 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001374 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001375 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001376 case lltok::kw_cc: {
1377 unsigned ArbitraryCC;
1378 Lex.Lex();
David Blaikie46a9f012012-01-20 21:51:11 +00001379 if (ParseUInt32(ArbitraryCC))
Sandeep Patel68c5f472009-09-02 08:44:58 +00001380 return true;
David Blaikie46a9f012012-01-20 21:51:11 +00001381 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1382 return false;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001383 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001385
Chris Lattnerac161bf2009-01-02 07:01:27 +00001386 Lex.Lex();
1387 return false;
1388}
1389
Chris Lattner5c427632009-12-30 05:31:19 +00001390/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001391/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001392bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1393 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001394 do {
1395 if (Lex.getKind() != lltok::MetadataVar)
1396 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001397
Chris Lattner596760d2009-12-29 21:25:40 +00001398 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001399 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001400 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001401
Chris Lattner1797fc72009-12-29 21:53:55 +00001402 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001403 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001404
1405 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001406 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001407
Dan Gohmanf0715b12010-08-24 14:35:45 +00001408 // This code is similar to that of ParseMetadataValue, however it needs to
1409 // have special-case code for a forward reference; see the comments on
1410 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1411 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001412 if (Lex.getKind() == lltok::lbrace) {
1413 ValID ID;
1414 if (ParseMetadataListValue(ID, PFS))
1415 return true;
1416 assert(ID.Kind == ValID::t_MDNode);
1417 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001418 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001419 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001420 if (ParseMDNodeID(Node, NodeID))
1421 return true;
1422 if (Node) {
1423 // If we got the node, add it to the instruction.
1424 Inst->setMetadata(MDK, Node);
1425 } else {
1426 MDRef R = { Loc, MDK, NodeID };
1427 // Otherwise, remember that this should be resolved later.
1428 ForwardRefInstMetadata[Inst].push_back(R);
1429 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001430 }
Chris Lattner596760d2009-12-29 21:25:40 +00001431
Manman Ren209b17c2013-09-28 00:22:27 +00001432 if (MDK == LLVMContext::MD_tbaa)
1433 InstsWithTBAATag.push_back(Inst);
1434
Chris Lattner596760d2009-12-29 21:25:40 +00001435 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001436 } while (EatIfPresent(lltok::comma));
1437 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001438}
1439
Chris Lattnerac161bf2009-01-02 07:01:27 +00001440/// ParseOptionalAlignment
1441/// ::= /* empty */
1442/// ::= 'align' 4
1443bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1444 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001445 if (!EatIfPresent(lltok::kw_align))
1446 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001447 LocTy AlignLoc = Lex.getLoc();
1448 if (ParseUInt32(Alignment)) return true;
1449 if (!isPowerOf2_32(Alignment))
1450 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001451 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001452 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001453 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001454}
1455
Chris Lattnerb2f39502009-12-30 05:44:30 +00001456/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001457/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001458/// ::= ',' align 4
1459///
1460/// This returns with AteExtraComma set to true if it ate an excess comma at the
1461/// end.
1462bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1463 bool &AteExtraComma) {
1464 AteExtraComma = false;
1465 while (EatIfPresent(lltok::comma)) {
1466 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001467 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001468 AteExtraComma = true;
1469 return false;
1470 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001471
Chris Lattner95b0ff42010-04-23 00:50:50 +00001472 if (Lex.getKind() != lltok::kw_align)
1473 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001474
Chris Lattner95b0ff42010-04-23 00:50:50 +00001475 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001476 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001477
Devang Patelea8a4b92009-09-17 23:04:48 +00001478 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001479}
1480
Eli Friedmanfee02c62011-07-25 23:16:38 +00001481/// ParseScopeAndOrdering
1482/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1483/// else: ::=
1484///
1485/// This sets Scope and Ordering to the parsed values.
1486bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1487 AtomicOrdering &Ordering) {
1488 if (!isAtomic)
1489 return false;
1490
1491 Scope = CrossThread;
1492 if (EatIfPresent(lltok::kw_singlethread))
1493 Scope = SingleThread;
1494 switch (Lex.getKind()) {
1495 default: return TokError("Expected ordering on atomic instruction");
1496 case lltok::kw_unordered: Ordering = Unordered; break;
1497 case lltok::kw_monotonic: Ordering = Monotonic; break;
1498 case lltok::kw_acquire: Ordering = Acquire; break;
1499 case lltok::kw_release: Ordering = Release; break;
1500 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1501 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1502 }
1503 Lex.Lex();
1504 return false;
1505}
1506
Charles Davisbe5557e2010-02-12 00:31:15 +00001507/// ParseOptionalStackAlignment
1508/// ::= /* empty */
1509/// ::= 'alignstack' '(' 4 ')'
1510bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1511 Alignment = 0;
1512 if (!EatIfPresent(lltok::kw_alignstack))
1513 return false;
1514 LocTy ParenLoc = Lex.getLoc();
1515 if (!EatIfPresent(lltok::lparen))
1516 return Error(ParenLoc, "expected '('");
1517 LocTy AlignLoc = Lex.getLoc();
1518 if (ParseUInt32(Alignment)) return true;
1519 ParenLoc = Lex.getLoc();
1520 if (!EatIfPresent(lltok::rparen))
1521 return Error(ParenLoc, "expected ')'");
1522 if (!isPowerOf2_32(Alignment))
1523 return Error(AlignLoc, "stack alignment is not a power of two");
1524 return false;
1525}
Devang Patelea8a4b92009-09-17 23:04:48 +00001526
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001527/// ParseIndexList - This parses the index list for an insert/extractvalue
1528/// instruction. This sets AteExtraComma in the case where we eat an extra
1529/// comma at the end of the line and find that it is followed by metadata.
1530/// Clients that don't allow metadata can call the version of this function that
1531/// only takes one argument.
1532///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001533/// ParseIndexList
1534/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001535///
1536bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1537 bool &AteExtraComma) {
1538 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001539
Chris Lattnerac161bf2009-01-02 07:01:27 +00001540 if (Lex.getKind() != lltok::comma)
1541 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001542
Chris Lattner3822f632009-01-02 08:05:26 +00001543 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001544 if (Lex.getKind() == lltok::MetadataVar) {
1545 AteExtraComma = true;
1546 return false;
1547 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001548 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001549 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001550 Indices.push_back(Idx);
1551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001552
Chris Lattnerac161bf2009-01-02 07:01:27 +00001553 return false;
1554}
1555
1556//===----------------------------------------------------------------------===//
1557// Type Parsing.
1558//===----------------------------------------------------------------------===//
1559
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001560/// ParseType - Parse a type.
1561bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1562 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001563 switch (Lex.getKind()) {
1564 default:
1565 return TokError("expected type");
1566 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001567 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001568 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001569 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001570 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001571 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001572 // Type ::= StructType
1573 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001574 return true;
1575 break;
1576 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001577 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578 Lex.Lex(); // eat the lsquare.
1579 if (ParseArrayVectorType(Result, false))
1580 return true;
1581 break;
1582 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001583 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001584 Lex.Lex();
1585 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001586 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001587 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001588 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001589 } else if (ParseArrayVectorType(Result, true))
1590 return true;
1591 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001592 case lltok::LocalVar: {
1593 // Type ::= %foo
1594 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001595
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001596 // If the type hasn't been defined yet, create a forward definition and
1597 // remember where that forward def'n was seen (in case it never is defined).
1598 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001599 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001600 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001601 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001602 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001603 Lex.Lex();
1604 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001605 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001606
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001607 case lltok::LocalVarID: {
1608 // Type ::= %4
1609 if (Lex.getUIntVal() >= NumberedTypes.size())
1610 NumberedTypes.resize(Lex.getUIntVal()+1);
1611 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001612
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001613 // If the type hasn't been defined yet, create a forward definition and
1614 // remember where that forward def'n was seen (in case it never is defined).
1615 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001616 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001617 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001618 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001619 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001620 Lex.Lex();
1621 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001622 }
1623 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001624
1625 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001626 while (1) {
1627 switch (Lex.getKind()) {
1628 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001629 default:
1630 if (!AllowVoid && Result->isVoidTy())
1631 return Error(TypeLoc, "void type only allowed for function results");
1632 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001634 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001635 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001636 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001637 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001638 if (Result->isVoidTy())
1639 return TokError("pointers to void are invalid - use i8* instead");
1640 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001641 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001642 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643 Lex.Lex();
1644 break;
1645
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001646 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001647 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001648 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001649 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001650 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001651 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001652 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001653 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001654 unsigned AddrSpace;
1655 if (ParseOptionalAddrSpace(AddrSpace) ||
1656 ParseToken(lltok::star, "expected '*' in address space"))
1657 return true;
1658
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001659 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001660 break;
1661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001662
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1664 case lltok::lparen:
1665 if (ParseFunctionType(Result))
1666 return true;
1667 break;
1668 }
1669 }
1670}
1671
1672/// ParseParameterList
1673/// ::= '(' ')'
1674/// ::= '(' Arg (',' Arg)* ')'
1675/// Arg
1676/// ::= Type OptionalAttributes Value OptionalAttributes
1677bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1678 PerFunctionState &PFS) {
1679 if (ParseToken(lltok::lparen, "expected '(' in call"))
1680 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001681
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001682 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001683 while (Lex.getKind() != lltok::rparen) {
1684 // If this isn't the first argument, we need a comma.
1685 if (!ArgList.empty() &&
1686 ParseToken(lltok::comma, "expected ',' in argument list"))
1687 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001688
Chris Lattnerac161bf2009-01-02 07:01:27 +00001689 // Parse the argument.
1690 LocTy ArgLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001691 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001692 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001693 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001694 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001695 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001696
Chris Lattner5b4a9622009-12-30 02:11:14 +00001697 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001698 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001699 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001700 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1701 AttrIndex++,
1702 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001703 }
1704
1705 Lex.Lex(); // Lex the ')'.
1706 return false;
1707}
1708
1709
1710
Chris Lattner2ed06b42009-01-05 18:34:07 +00001711/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001712/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713/// ::= '(' ArgTypeListI ')'
1714/// ArgTypeListI
1715/// ::= /*empty*/
1716/// ::= '...'
1717/// ::= ArgTypeList ',' '...'
1718/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001719///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001720bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1721 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 isVarArg = false;
1723 assert(Lex.getKind() == lltok::lparen);
1724 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001725
Chris Lattnerac161bf2009-01-02 07:01:27 +00001726 if (Lex.getKind() == lltok::rparen) {
1727 // empty
1728 } else if (Lex.getKind() == lltok::dotdotdot) {
1729 isVarArg = true;
1730 Lex.Lex();
1731 } else {
1732 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001733 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001734 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001735 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001736
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001737 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001738 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001739
Chris Lattnerfdd87902009-10-05 05:54:46 +00001740 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001741 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001742
Chris Lattnerdef19492011-06-17 06:36:20 +00001743 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001744 Name = Lex.getStrVal();
1745 Lex.Lex();
1746 }
Chris Lattner3822f632009-01-02 08:05:26 +00001747
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001748 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001749 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001750
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001751 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001752 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001753 AttributeSet::get(ArgTy->getContext(),
1754 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001755
Chris Lattner3822f632009-01-02 08:05:26 +00001756 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001757 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001758 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001759 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760 break;
1761 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001762
Chris Lattnerac161bf2009-01-02 07:01:27 +00001763 // Otherwise must be an argument type.
1764 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001765 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001766
Chris Lattnerfdd87902009-10-05 05:54:46 +00001767 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001768 return Error(TypeLoc, "argument can not have void type");
1769
Chris Lattnerdef19492011-06-17 06:36:20 +00001770 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 Name = Lex.getStrVal();
1772 Lex.Lex();
1773 } else {
1774 Name = "";
1775 }
Chris Lattner3822f632009-01-02 08:05:26 +00001776
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001777 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001778 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001779
Bill Wendlingd079a442012-10-15 04:46:55 +00001780 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001781 AttributeSet::get(ArgTy->getContext(),
1782 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001783 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784 }
1785 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001786
Chris Lattner3822f632009-01-02 08:05:26 +00001787 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001788}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001789
Chris Lattnerac161bf2009-01-02 07:01:27 +00001790/// ParseFunctionType
1791/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001792bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001793 assert(Lex.getKind() == lltok::lparen);
1794
Chris Lattnerce473c72009-01-05 08:04:33 +00001795 if (!FunctionType::isValidReturnType(Result))
1796 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001797
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001798 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001799 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001800 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001802
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803 // Reject names on the arguments lists.
1804 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1805 if (!ArgList[i].Name.empty())
1806 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001807 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001808 return Error(ArgList[i].Loc,
1809 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001811
Jay Foadb804a2b2011-07-12 14:06:48 +00001812 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001813 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001814 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001815
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001816 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001817 return false;
1818}
1819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1821/// other structs.
1822bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1823 SmallVector<Type*, 8> Elts;
1824 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001825
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001826 Result = StructType::get(Context, Elts, Packed);
1827 return false;
1828}
1829
1830/// ParseStructDefinition - Parse a struct in a 'type' definition.
1831bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1832 std::pair<Type*, LocTy> &Entry,
1833 Type *&ResultTy) {
1834 // If the type was already defined, diagnose the redefinition.
1835 if (Entry.first && !Entry.second.isValid())
1836 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001837
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001838 // If we have opaque, just return without filling in the definition for the
1839 // struct. This counts as a definition as far as the .ll file goes.
1840 if (EatIfPresent(lltok::kw_opaque)) {
1841 // This type is being defined, so clear the location to indicate this.
1842 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001843
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001844 // If this type number has never been uttered, create it.
1845 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001846 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001847 ResultTy = Entry.first;
1848 return false;
1849 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001850
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001851 // If the type starts with '<', then it is either a packed struct or a vector.
1852 bool isPacked = EatIfPresent(lltok::less);
1853
1854 // If we don't have a struct, then we have a random type alias, which we
1855 // accept for compatibility with old files. These types are not allowed to be
1856 // forward referenced and not allowed to be recursive.
1857 if (Lex.getKind() != lltok::lbrace) {
1858 if (Entry.first)
1859 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001860
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001861 ResultTy = 0;
1862 if (isPacked)
1863 return ParseArrayVectorType(ResultTy, true);
1864 return ParseType(ResultTy);
1865 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001866
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 // This type is being defined, so clear the location to indicate this.
1868 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001869
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001870 // If this type number has never been uttered, create it.
1871 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001872 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001873
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001874 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001875
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001876 SmallVector<Type*, 8> Body;
1877 if (ParseStructBody(Body) ||
1878 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1879 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001880
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001881 STy->setBody(Body, isPacked);
1882 ResultTy = STy;
1883 return false;
1884}
1885
1886
Chris Lattnerac161bf2009-01-02 07:01:27 +00001887/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001890/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001891/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892/// ::= '<' '{' Type (',' Type)* '}' '>'
1893bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 assert(Lex.getKind() == lltok::lbrace);
1895 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001896
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001897 // Handle the empty struct.
1898 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001899 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900
Chris Lattnerf880ca22009-03-09 04:49:14 +00001901 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001902 Type *Ty = 0;
1903 if (ParseType(Ty)) return true;
1904 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001906 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001907 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Chris Lattner3822f632009-01-02 08:05:26 +00001909 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00001910 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001911 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001912
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001913 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001914 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001915
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001916 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001919 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920}
1921
1922/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1923/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001924/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00001925/// ::= '[' APSINTVAL 'x' Types ']'
1926/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001927bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1929 Lex.getAPSIntVal().getBitWidth() > 64)
1930 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 LocTy SizeLoc = Lex.getLoc();
1933 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00001934 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001935
Chris Lattner3822f632009-01-02 08:05:26 +00001936 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1937 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938
1939 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001940 Type *EltTy = 0;
1941 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00001942
Chris Lattner3822f632009-01-02 08:05:26 +00001943 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1944 "expected end of sequential type"))
1945 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Chris Lattnerac161bf2009-01-02 07:01:27 +00001947 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00001948 if (Size == 0)
1949 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001950 if ((unsigned)Size != Size)
1951 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001952 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00001953 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00001954 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001955 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001956 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 }
1960 return false;
1961}
1962
1963//===----------------------------------------------------------------------===//
1964// Function Semantic Analysis.
1965//===----------------------------------------------------------------------===//
1966
Chris Lattner3432c622009-10-28 03:39:23 +00001967LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1968 int functionNumber)
1969 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970
1971 // Insert unnamed arguments into the NumberedVals list.
1972 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1973 AI != E; ++AI)
1974 if (!AI->hasName())
1975 NumberedVals.push_back(AI);
1976}
1977
1978LLParser::PerFunctionState::~PerFunctionState() {
1979 // If there were any forward referenced non-basicblock values, delete them.
1980 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1981 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1982 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00001983 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00001984 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 delete I->second.first;
1986 I->second.first = 0;
1987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001988
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1990 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1991 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00001992 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00001993 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001994 delete I->second.first;
1995 I->second.first = 0;
1996 }
1997}
1998
Chris Lattner3432c622009-10-28 03:39:23 +00001999bool LLParser::PerFunctionState::FinishFunction() {
2000 // Check to see if someone took the address of labels in this block.
2001 if (!P.ForwardRefBlockAddresses.empty()) {
2002 ValID FunctionID;
2003 if (!F.getName().empty()) {
2004 FunctionID.Kind = ValID::t_GlobalName;
2005 FunctionID.StrVal = F.getName();
2006 } else {
2007 FunctionID.Kind = ValID::t_GlobalID;
2008 FunctionID.UIntVal = FunctionNumber;
2009 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002010
Chris Lattner3432c622009-10-28 03:39:23 +00002011 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2012 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2013 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2014 // Resolve all these references.
2015 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2016 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002017
Chris Lattner3432c622009-10-28 03:39:23 +00002018 P.ForwardRefBlockAddresses.erase(FRBAI);
2019 }
2020 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002021
Chris Lattnerac161bf2009-01-02 07:01:27 +00002022 if (!ForwardRefVals.empty())
2023 return P.Error(ForwardRefVals.begin()->second.second,
2024 "use of undefined value '%" + ForwardRefVals.begin()->first +
2025 "'");
2026 if (!ForwardRefValIDs.empty())
2027 return P.Error(ForwardRefValIDs.begin()->second.second,
2028 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002029 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002030 return false;
2031}
2032
2033
2034/// GetVal - Get a value with the specified name or ID, creating a
2035/// forward reference record if needed. This can return null if the value
2036/// exists but does not have the right type.
2037Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002038 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002039 // Look this name up in the normal function symbol table.
2040 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002041
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 // If this is a forward reference for the value, see if we already created a
2043 // forward ref record.
2044 if (Val == 0) {
2045 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2046 I = ForwardRefVals.find(Name);
2047 if (I != ForwardRefVals.end())
2048 Val = I->second.first;
2049 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002050
Chris Lattnerac161bf2009-01-02 07:01:27 +00002051 // If we have the value in the symbol table or fwd-ref table, return it.
2052 if (Val) {
2053 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002054 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055 P.Error(Loc, "'%" + Name + "' is not a basic block");
2056 else
2057 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002058 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059 return 0;
2060 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002061
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 // Don't make placeholders with invalid type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064 P.Error(Loc, "invalid use of a non-first-class type");
2065 return 0;
2066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002067
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068 // Otherwise, create a new forward reference for this value and remember it.
2069 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002070 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002071 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 else
2073 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002074
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2076 return FwdVal;
2077}
2078
Chris Lattner229907c2011-07-18 04:54:35 +00002079Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 LocTy Loc) {
2081 // Look this name up in the normal function symbol table.
2082 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002083
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084 // If this is a forward reference for the value, see if we already created a
2085 // forward ref record.
2086 if (Val == 0) {
2087 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2088 I = ForwardRefValIDs.find(ID);
2089 if (I != ForwardRefValIDs.end())
2090 Val = I->second.first;
2091 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002092
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 // If we have the value in the symbol table or fwd-ref table, return it.
2094 if (Val) {
2095 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002096 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002097 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002099 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002100 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 return 0;
2102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 P.Error(Loc, "invalid use of a non-first-class type");
2106 return 0;
2107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002108
Chris Lattnerac161bf2009-01-02 07:01:27 +00002109 // Otherwise, create a new forward reference for this value and remember it.
2110 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002111 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002112 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 else
2114 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002115
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2117 return FwdVal;
2118}
2119
2120/// SetInstName - After an instruction is parsed and inserted into its
2121/// basic block, this installs its name.
2122bool LLParser::PerFunctionState::SetInstName(int NameID,
2123 const std::string &NameStr,
2124 LocTy NameLoc, Instruction *Inst) {
2125 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002126 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 if (NameID != -1 || !NameStr.empty())
2128 return P.Error(NameLoc, "instructions returning void cannot have a name");
2129 return false;
2130 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002131
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132 // If this was a numbered instruction, verify that the instruction is the
2133 // expected value and resolve any forward references.
2134 if (NameStr.empty()) {
2135 // If neither a name nor an ID was specified, just use the next ID.
2136 if (NameID == -1)
2137 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002138
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 if (unsigned(NameID) != NumberedVals.size())
2140 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002141 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002142
Chris Lattnerac161bf2009-01-02 07:01:27 +00002143 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2144 ForwardRefValIDs.find(NameID);
2145 if (FI != ForwardRefValIDs.end()) {
2146 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002147 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002148 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002150 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 ForwardRefValIDs.erase(FI);
2152 }
2153
2154 NumberedVals.push_back(Inst);
2155 return false;
2156 }
2157
2158 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2159 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2160 FI = ForwardRefVals.find(NameStr);
2161 if (FI != ForwardRefVals.end()) {
2162 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002164 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002165 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002166 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 ForwardRefVals.erase(FI);
2168 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002169
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 // Set the name on the instruction.
2171 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002172
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002173 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002174 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 NameStr + "'");
2176 return false;
2177}
2178
2179/// GetBB - Get a basic block with the specified name or ID, creating a
2180/// forward reference record if needed.
2181BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2182 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002183 return cast_or_null<BasicBlock>(GetVal(Name,
2184 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185}
2186
2187BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002188 return cast_or_null<BasicBlock>(GetVal(ID,
2189 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190}
2191
2192/// DefineBB - Define the specified basic block, which is either named or
2193/// unnamed. If there is an error, this returns null otherwise it returns
2194/// the block being defined.
2195BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2196 LocTy Loc) {
2197 BasicBlock *BB;
2198 if (Name.empty())
2199 BB = GetBB(NumberedVals.size(), Loc);
2200 else
2201 BB = GetBB(Name, Loc);
2202 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002203
Chris Lattnerac161bf2009-01-02 07:01:27 +00002204 // Move the block to the end of the function. Forward ref'd blocks are
2205 // inserted wherever they happen to be referenced.
2206 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002207
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 // Remove the block from forward ref sets.
2209 if (Name.empty()) {
2210 ForwardRefValIDs.erase(NumberedVals.size());
2211 NumberedVals.push_back(BB);
2212 } else {
2213 // BB forward references are already in the function symbol table.
2214 ForwardRefVals.erase(Name);
2215 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 return BB;
2218}
2219
2220//===----------------------------------------------------------------------===//
2221// Constants.
2222//===----------------------------------------------------------------------===//
2223
2224/// ParseValID - Parse an abstract value that doesn't necessarily have a
2225/// type implied. For example, if we parse "4" we don't know what integer type
2226/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002227/// sanity. PFS is used to convert function-local operands of metadata (since
2228/// metadata operands are not just parsed here but also converted to values).
2229/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002230bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 ID.Loc = Lex.getLoc();
2232 switch (Lex.getKind()) {
2233 default: return TokError("expected value token");
2234 case lltok::GlobalID: // @42
2235 ID.UIntVal = Lex.getUIntVal();
2236 ID.Kind = ValID::t_GlobalID;
2237 break;
2238 case lltok::GlobalVar: // @foo
2239 ID.StrVal = Lex.getStrVal();
2240 ID.Kind = ValID::t_GlobalName;
2241 break;
2242 case lltok::LocalVarID: // %42
2243 ID.UIntVal = Lex.getUIntVal();
2244 ID.Kind = ValID::t_LocalID;
2245 break;
2246 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 ID.StrVal = Lex.getStrVal();
2248 ID.Kind = ValID::t_LocalName;
2249 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002250 case lltok::exclaim: // !42, !{...}, or !"foo"
2251 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002252 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 ID.Kind = ValID::t_APSInt;
2255 break;
2256 case lltok::APFloat:
2257 ID.APFloatVal = Lex.getAPFloatVal();
2258 ID.Kind = ValID::t_APFloat;
2259 break;
2260 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002261 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 ID.Kind = ValID::t_Constant;
2263 break;
2264 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002265 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002266 ID.Kind = ValID::t_Constant;
2267 break;
2268 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2269 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2270 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002271
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 case lltok::lbrace: {
2273 // ValID ::= '{' ConstVector '}'
2274 Lex.Lex();
2275 SmallVector<Constant*, 16> Elts;
2276 if (ParseGlobalValueVector(Elts) ||
2277 ParseToken(lltok::rbrace, "expected end of struct constant"))
2278 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002279
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280 ID.ConstantStructElts = new Constant*[Elts.size()];
2281 ID.UIntVal = Elts.size();
2282 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2283 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284 return false;
2285 }
2286 case lltok::less: {
2287 // ValID ::= '<' ConstVector '>' --> Vector.
2288 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2289 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002290 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002291
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292 SmallVector<Constant*, 16> Elts;
2293 LocTy FirstEltLoc = Lex.getLoc();
2294 if (ParseGlobalValueVector(Elts) ||
2295 (isPackedStruct &&
2296 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2297 ParseToken(lltok::greater, "expected end of constant"))
2298 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002301 ID.ConstantStructElts = new Constant*[Elts.size()];
2302 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2303 ID.UIntVal = Elts.size();
2304 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 return false;
2306 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002307
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 if (Elts.empty())
2309 return Error(ID.Loc, "constant vector must not be empty");
2310
Duncan Sands9dff9be2010-02-15 16:12:20 +00002311 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002312 !Elts[0]->getType()->isFloatingPointTy() &&
2313 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002315 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002316
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 // Verify that all the vector elements have the same type.
2318 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2319 if (Elts[i]->getType() != Elts[0]->getType())
2320 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002321 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002322 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002323
Chris Lattner69229312011-02-15 00:14:00 +00002324 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 ID.Kind = ValID::t_Constant;
2326 return false;
2327 }
2328 case lltok::lsquare: { // Array Constant
2329 Lex.Lex();
2330 SmallVector<Constant*, 16> Elts;
2331 LocTy FirstEltLoc = Lex.getLoc();
2332 if (ParseGlobalValueVector(Elts) ||
2333 ParseToken(lltok::rsquare, "expected end of array constant"))
2334 return true;
2335
2336 // Handle empty element.
2337 if (Elts.empty()) {
2338 // Use undef instead of an array because it's inconvenient to determine
2339 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002340 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 return false;
2342 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002343
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002346 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002347
Owen Anderson4056ca92009-07-29 22:17:13 +00002348 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002351 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 if (Elts[i]->getType() != Elts[0]->getType())
2353 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002354 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002355 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002357
Jay Foad83be3612011-06-22 09:24:39 +00002358 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 ID.Kind = ValID::t_Constant;
2360 return false;
2361 }
2362 case lltok::kw_c: // c "foo"
2363 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002364 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2365 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2367 ID.Kind = ValID::t_Constant;
2368 return false;
2369
2370 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002371 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2372 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002373 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 Lex.Lex();
2375 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002376 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002377 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002378 ParseStringConstant(ID.StrVal) ||
2379 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380 ParseToken(lltok::StringConstant, "expected constraint string"))
2381 return true;
2382 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002383 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002384 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 ID.Kind = ValID::t_InlineAsm;
2386 return false;
2387 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002388
Chris Lattner3432c622009-10-28 03:39:23 +00002389 case lltok::kw_blockaddress: {
2390 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2391 Lex.Lex();
2392
2393 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002394
Chris Lattner3432c622009-10-28 03:39:23 +00002395 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2396 ParseValID(Fn) ||
2397 ParseToken(lltok::comma, "expected comma in block address expression")||
2398 ParseValID(Label) ||
2399 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2400 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002401
Chris Lattner3432c622009-10-28 03:39:23 +00002402 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2403 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002404 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002405 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002406
Chris Lattner3432c622009-10-28 03:39:23 +00002407 // Make a global variable as a placeholder for this reference.
2408 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2409 false, GlobalValue::InternalLinkage,
2410 0, "");
2411 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2412 ID.ConstantVal = FwdRef;
2413 ID.Kind = ValID::t_Constant;
2414 return false;
2415 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002416
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 case lltok::kw_trunc:
2418 case lltok::kw_zext:
2419 case lltok::kw_sext:
2420 case lltok::kw_fptrunc:
2421 case lltok::kw_fpext:
2422 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002423 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424 case lltok::kw_uitofp:
2425 case lltok::kw_sitofp:
2426 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002427 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002429 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 unsigned Opc = Lex.getUIntVal();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002431 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 Constant *SrcVal;
2433 Lex.Lex();
2434 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2435 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002436 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 ParseType(DestTy) ||
2438 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2439 return true;
2440 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2441 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002442 getTypeString(SrcVal->getType()) + "' to '" +
2443 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002445 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 ID.Kind = ValID::t_Constant;
2447 return false;
2448 }
2449 case lltok::kw_extractvalue: {
2450 Lex.Lex();
2451 Constant *Val;
2452 SmallVector<unsigned, 4> Indices;
2453 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2454 ParseGlobalTypeAndValue(Val) ||
2455 ParseIndexList(Indices) ||
2456 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2457 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002458
Chris Lattner392be582010-02-12 20:49:41 +00002459 if (!Val->getType()->isAggregateType())
2460 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002461 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002463 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 ID.Kind = ValID::t_Constant;
2465 return false;
2466 }
2467 case lltok::kw_insertvalue: {
2468 Lex.Lex();
2469 Constant *Val0, *Val1;
2470 SmallVector<unsigned, 4> Indices;
2471 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2472 ParseGlobalTypeAndValue(Val0) ||
2473 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2474 ParseGlobalTypeAndValue(Val1) ||
2475 ParseIndexList(Indices) ||
2476 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2477 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002478 if (!Val0->getType()->isAggregateType())
2479 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002480 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002482 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 ID.Kind = ValID::t_Constant;
2484 return false;
2485 }
2486 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002487 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 unsigned PredVal, Opc = Lex.getUIntVal();
2489 Constant *Val0, *Val1;
2490 Lex.Lex();
2491 if (ParseCmpPredicate(PredVal, Opc) ||
2492 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2493 ParseGlobalTypeAndValue(Val0) ||
2494 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2495 ParseGlobalTypeAndValue(Val1) ||
2496 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2497 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498
Chris Lattnerac161bf2009-01-02 07:01:27 +00002499 if (Val0->getType() != Val1->getType())
2500 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002501
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002503
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002505 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002506 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002507 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002508 } else {
2509 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002510 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002511 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002513 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002514 }
2515 ID.Kind = ValID::t_Constant;
2516 return false;
2517 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002518
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 // Binary Operators.
2520 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002521 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002523 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002525 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 case lltok::kw_udiv:
2527 case lltok::kw_sdiv:
2528 case lltok::kw_fdiv:
2529 case lltok::kw_urem:
2530 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002531 case lltok::kw_frem:
2532 case lltok::kw_shl:
2533 case lltok::kw_lshr:
2534 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002535 bool NUW = false;
2536 bool NSW = false;
2537 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002538 unsigned Opc = Lex.getUIntVal();
2539 Constant *Val0, *Val1;
2540 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002541 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002542 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2543 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002544 if (EatIfPresent(lltok::kw_nuw))
2545 NUW = true;
2546 if (EatIfPresent(lltok::kw_nsw)) {
2547 NSW = true;
2548 if (EatIfPresent(lltok::kw_nuw))
2549 NUW = true;
2550 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002551 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2552 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002553 if (EatIfPresent(lltok::kw_exact))
2554 Exact = true;
2555 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2557 ParseGlobalTypeAndValue(Val0) ||
2558 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2559 ParseGlobalTypeAndValue(Val1) ||
2560 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2561 return true;
2562 if (Val0->getType() != Val1->getType())
2563 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002564 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002565 if (NUW)
2566 return Error(ModifierLoc, "nuw only applies to integer operations");
2567 if (NSW)
2568 return Error(ModifierLoc, "nsw only applies to integer operations");
2569 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002570 // Check that the type is valid for the operator.
2571 switch (Opc) {
2572 case Instruction::Add:
2573 case Instruction::Sub:
2574 case Instruction::Mul:
2575 case Instruction::UDiv:
2576 case Instruction::SDiv:
2577 case Instruction::URem:
2578 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002579 case Instruction::Shl:
2580 case Instruction::AShr:
2581 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002582 if (!Val0->getType()->isIntOrIntVectorTy())
2583 return Error(ID.Loc, "constexpr requires integer operands");
2584 break;
2585 case Instruction::FAdd:
2586 case Instruction::FSub:
2587 case Instruction::FMul:
2588 case Instruction::FDiv:
2589 case Instruction::FRem:
2590 if (!Val0->getType()->isFPOrFPVectorTy())
2591 return Error(ID.Loc, "constexpr requires fp operands");
2592 break;
2593 default: llvm_unreachable("Unknown binary operator!");
2594 }
Dan Gohman1b849082009-09-07 23:54:19 +00002595 unsigned Flags = 0;
2596 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2597 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002598 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002599 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002600 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002601 ID.Kind = ValID::t_Constant;
2602 return false;
2603 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002604
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002606 case lltok::kw_and:
2607 case lltok::kw_or:
2608 case lltok::kw_xor: {
2609 unsigned Opc = Lex.getUIntVal();
2610 Constant *Val0, *Val1;
2611 Lex.Lex();
2612 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2613 ParseGlobalTypeAndValue(Val0) ||
2614 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2615 ParseGlobalTypeAndValue(Val1) ||
2616 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2617 return true;
2618 if (Val0->getType() != Val1->getType())
2619 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002620 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 return Error(ID.Loc,
2622 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002623 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 ID.Kind = ValID::t_Constant;
2625 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626 }
2627
Chris Lattnerac161bf2009-01-02 07:01:27 +00002628 case lltok::kw_getelementptr:
2629 case lltok::kw_shufflevector:
2630 case lltok::kw_insertelement:
2631 case lltok::kw_extractelement:
2632 case lltok::kw_select: {
2633 unsigned Opc = Lex.getUIntVal();
2634 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002635 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002636 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002637 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002638 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2640 ParseGlobalValueVector(Elts) ||
2641 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2642 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002645 if (Elts.size() == 0 ||
2646 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002648
Jay Foaded8db7d2011-07-21 14:31:17 +00002649 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002650 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002652 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2653 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 } else if (Opc == Instruction::Select) {
2655 if (Elts.size() != 3)
2656 return Error(ID.Loc, "expected three operands to select");
2657 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2658 Elts[2]))
2659 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002660 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 } else if (Opc == Instruction::ShuffleVector) {
2662 if (Elts.size() != 3)
2663 return Error(ID.Loc, "expected three operands to shufflevector");
2664 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2665 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002666 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002667 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 } else if (Opc == Instruction::ExtractElement) {
2669 if (Elts.size() != 2)
2670 return Error(ID.Loc, "expected two operands to extractelement");
2671 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2672 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002673 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 } else {
2675 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2676 if (Elts.size() != 3)
2677 return Error(ID.Loc, "expected three operands to insertelement");
2678 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2679 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002680 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002681 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002682 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002683
Chris Lattnerac161bf2009-01-02 07:01:27 +00002684 ID.Kind = ValID::t_Constant;
2685 return false;
2686 }
2687 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002688
Chris Lattnerac161bf2009-01-02 07:01:27 +00002689 Lex.Lex();
2690 return false;
2691}
2692
2693/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002694bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002695 C = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002696 ValID ID;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002697 Value *V = NULL;
2698 bool Parsed = ParseValID(ID) ||
2699 ConvertValIDToValue(Ty, ID, V, NULL);
2700 if (V && !(C = dyn_cast<Constant>(V)))
2701 return Error(ID.Loc, "global values must be constants");
2702 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002703}
2704
Victor Hernandez9d75c962010-01-11 22:31:58 +00002705bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002706 Type *Ty = 0;
2707 return ParseType(Ty) ||
2708 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002709}
2710
2711/// ParseGlobalValueVector
2712/// ::= /*empty*/
2713/// ::= TypeAndValue (',' TypeAndValue)*
2714bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2715 // Empty list.
2716 if (Lex.getKind() == lltok::rbrace ||
2717 Lex.getKind() == lltok::rsquare ||
2718 Lex.getKind() == lltok::greater ||
2719 Lex.getKind() == lltok::rparen)
2720 return false;
2721
2722 Constant *C;
2723 if (ParseGlobalTypeAndValue(C)) return true;
2724 Elts.push_back(C);
2725
2726 while (EatIfPresent(lltok::comma)) {
2727 if (ParseGlobalTypeAndValue(C)) return true;
2728 Elts.push_back(C);
2729 }
2730
2731 return false;
2732}
2733
Dan Gohmanc828c542010-08-24 02:24:03 +00002734bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2735 assert(Lex.getKind() == lltok::lbrace);
2736 Lex.Lex();
2737
2738 SmallVector<Value*, 16> Elts;
2739 if (ParseMDNodeVector(Elts, PFS) ||
2740 ParseToken(lltok::rbrace, "expected end of metadata node"))
2741 return true;
2742
Jay Foad5514afe2011-04-21 19:59:31 +00002743 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002744 ID.Kind = ValID::t_MDNode;
2745 return false;
2746}
2747
Dan Gohman8939ba332010-07-14 18:26:50 +00002748/// ParseMetadataValue
2749/// ::= !42
2750/// ::= !{...}
2751/// ::= !"string"
2752bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2753 assert(Lex.getKind() == lltok::exclaim);
2754 Lex.Lex();
2755
2756 // MDNode:
2757 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002758 if (Lex.getKind() == lltok::lbrace)
2759 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002760
2761 // Standalone metadata reference
2762 // !42
2763 if (Lex.getKind() == lltok::APSInt) {
2764 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2765 ID.Kind = ValID::t_MDNode;
2766 return false;
2767 }
2768
2769 // MDString:
2770 // ::= '!' STRINGCONSTANT
2771 if (ParseMDString(ID.MDStringVal)) return true;
2772 ID.Kind = ValID::t_MDString;
2773 return false;
2774}
2775
Victor Hernandez9d75c962010-01-11 22:31:58 +00002776
2777//===----------------------------------------------------------------------===//
2778// Function Parsing.
2779//===----------------------------------------------------------------------===//
2780
Chris Lattner229907c2011-07-18 04:54:35 +00002781bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00002782 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002783 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002785
Chris Lattnerac161bf2009-01-02 07:01:27 +00002786 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002788 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2789 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2790 return (V == 0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002792 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2793 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2794 return (V == 0);
2795 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00002796 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002797 FunctionType *FTy =
Victor Hernandez9d75c962010-01-11 22:31:58 +00002798 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2799 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2800 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00002801 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00002802 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00002803 return false;
2804 }
2805 case ValID::t_MDNode:
2806 if (!Ty->isMetadataTy())
2807 return Error(ID.Loc, "metadata value must have metadata type");
2808 V = ID.MDNodeVal;
2809 return false;
2810 case ValID::t_MDString:
2811 if (!Ty->isMetadataTy())
2812 return Error(ID.Loc, "metadata value must have metadata type");
2813 V = ID.MDStringVal;
2814 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 case ValID::t_GlobalName:
2816 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2817 return V == 0;
2818 case ValID::t_GlobalID:
2819 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2820 return V == 0;
2821 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00002822 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00002824 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00002825 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 return false;
2827 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00002828 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2830 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002831
Dan Gohman518cda42011-12-17 00:04:22 +00002832 // The lexer has no type info, so builds all half, float, and double FP
2833 // constants as double. Fix this here. Long double does not need this.
2834 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00002836 if (Ty->isHalfTy())
2837 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2838 &Ignored);
2839 else if (Ty->isFloatTy())
2840 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2841 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002842 }
Owen Anderson69c464d2009-07-27 20:59:43 +00002843 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002844
Chris Lattner8f57d29e2009-01-05 18:24:23 +00002845 if (V->getType() != Ty)
2846 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002847 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002848
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 return false;
2850 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00002851 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002853 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002854 return false;
2855 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00002856 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002857 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00002858 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002859 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00002861 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00002862 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00002863 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002864 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00002865 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002866 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00002867 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002868 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002870 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 return false;
2872 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00002873 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002874 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00002875
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 V = ID.ConstantVal;
2877 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002878 case ValID::t_ConstantStruct:
2879 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00002880 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002881 if (ST->getNumElements() != ID.UIntVal)
2882 return Error(ID.Loc,
2883 "initializer with struct type has wrong # elements");
2884 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2885 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002886
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002887 // Verify that the elements are compatible with the structtype.
2888 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2889 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2890 return Error(ID.Loc, "element " + Twine(i) +
2891 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002892
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002893 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2894 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002895 } else
2896 return Error(ID.Loc, "constant expression type mismatch");
2897 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002898 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002899 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002900}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002901
Chris Lattner229907c2011-07-18 04:54:35 +00002902bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002903 V = 0;
2904 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002905 return ParseValID(ID, PFS) ||
2906 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002907}
2908
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002909bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2910 Type *Ty = 0;
2911 return ParseType(Ty) ||
2912 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002913}
2914
Chris Lattner3ed871f2009-10-27 19:13:16 +00002915bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2916 PerFunctionState &PFS) {
2917 Value *V;
2918 Loc = Lex.getLoc();
2919 if (ParseTypeAndValue(V, PFS)) return true;
2920 if (!isa<BasicBlock>(V))
2921 return Error(Loc, "expected a basic block");
2922 BB = cast<BasicBlock>(V);
2923 return false;
2924}
2925
2926
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927/// FunctionHeader
2928/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00002929/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002930/// OptionalAlign OptGC OptionalPrefix
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2932 // Parse the linkage.
2933 LocTy LinkageLoc = Lex.getLoc();
2934 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002935
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00002936 unsigned Visibility;
Bill Wendling50d27842012-10-15 20:35:56 +00002937 AttrBuilder RetAttrs;
Sandeep Patel68c5f472009-09-02 08:44:58 +00002938 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002939 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002940 LocTy RetTypeLoc = Lex.getLoc();
2941 if (ParseOptionalLinkage(Linkage) ||
2942 ParseOptionalVisibility(Visibility) ||
2943 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002944 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00002945 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 return true;
2947
2948 // Verify that the linkage is ok.
2949 switch ((GlobalValue::LinkageTypes)Linkage) {
2950 case GlobalValue::ExternalLinkage:
2951 break; // always ok.
Nico Rieck9d2e0df2014-01-14 12:38:32 +00002952 case GlobalValue::DLLImportLinkage:
Duncan Sandse2881052009-03-11 08:08:06 +00002953 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954 if (isDefine)
2955 return Error(LinkageLoc, "invalid linkage for function definition");
2956 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00002957 case GlobalValue::PrivateLinkage:
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00002958 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling03bcd6e2010-07-01 21:55:59 +00002959 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00002961 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00002962 case GlobalValue::LinkOnceAnyLinkage:
2963 case GlobalValue::LinkOnceODRLinkage:
2964 case GlobalValue::WeakAnyLinkage:
2965 case GlobalValue::WeakODRLinkage:
Nico Rieck9d2e0df2014-01-14 12:38:32 +00002966 case GlobalValue::DLLExportLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002967 if (!isDefine)
2968 return Error(LinkageLoc, "invalid linkage for function declaration");
2969 break;
2970 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00002971 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972 return Error(LinkageLoc, "invalid function linkage type");
2973 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002974
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002975 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002976 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002977
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00002979
2980 std::string FunctionName;
2981 if (Lex.getKind() == lltok::GlobalVar) {
2982 FunctionName = Lex.getStrVal();
2983 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2984 unsigned NameID = Lex.getUIntVal();
2985
2986 if (NameID != NumberedVals.size())
2987 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002988 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00002989 } else {
2990 return TokError("expected function name");
2991 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002992
Chris Lattner3822f632009-01-02 08:05:26 +00002993 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002994
Chris Lattner3822f632009-01-02 08:05:26 +00002995 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002997
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002998 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002999 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003000 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003001 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003002 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003003 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003005 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003006 bool UnnamedAddr;
3007 LocTy UnnamedAddrLoc;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003008 Constant *Prefix = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00003009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003010 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003011 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3012 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003013 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003014 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003015 (EatIfPresent(lltok::kw_section) &&
3016 ParseStringConstant(Section)) ||
3017 ParseOptionalAlignment(Alignment) ||
3018 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003019 ParseStringConstant(GC)) ||
3020 (EatIfPresent(lltok::kw_prefix) &&
3021 ParseGlobalTypeAndValue(Prefix)))
Chris Lattner3822f632009-01-02 08:05:26 +00003022 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023
Michael Gottesman41748d72013-06-27 00:25:01 +00003024 if (FuncAttrs.contains(Attribute::Builtin))
3025 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003026
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003028 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003029 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003030 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003031 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003032
Chris Lattnerac161bf2009-01-02 07:01:27 +00003033 // Okay, if we got here, the function is syntactically valid. Convert types
3034 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003035 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003036 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003037
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003038 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003039 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3040 AttributeSet::ReturnIndex,
3041 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003042
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003044 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003045 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3046 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003047 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3048 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 }
3050
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003051 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003052 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3053 AttributeSet::FunctionIndex,
3054 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055
Bill Wendlinge94d8432012-12-07 23:16:57 +00003056 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003057
Bill Wendling749a43d2012-12-30 13:50:49 +00003058 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003059 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3060
Chris Lattner229907c2011-07-18 04:54:35 +00003061 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003062 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003063 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064
3065 Fn = 0;
3066 if (!FunctionName.empty()) {
3067 // If this was a definition of a forward reference, remove the definition
3068 // from the forward reference table and fill in the forward ref.
3069 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3070 ForwardRefVals.find(FunctionName);
3071 if (FRVI != ForwardRefVals.end()) {
3072 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003073 if (!Fn)
3074 return Error(FRVI->second.second, "invalid forward reference to "
3075 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003076 if (Fn->getType() != PFT)
3077 return Error(FRVI->second.second, "invalid forward reference to "
3078 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003079
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 ForwardRefVals.erase(FRVI);
3081 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003082 // Reject redefinitions.
3083 return Error(NameLoc, "invalid redefinition of function '" +
3084 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003085 } else if (M->getNamedValue(FunctionName)) {
3086 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003088
Dan Gohman399d6ae2009-08-29 23:37:49 +00003089 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003090 // If this is a definition of a forward referenced function, make sure the
3091 // types agree.
3092 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3093 = ForwardRefValIDs.find(NumberedVals.size());
3094 if (I != ForwardRefValIDs.end()) {
3095 Fn = cast<Function>(I->second.first);
3096 if (Fn->getType() != PFT)
3097 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003098 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003099 ForwardRefValIDs.erase(I);
3100 }
3101 }
3102
3103 if (Fn == 0)
3104 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3105 else // Move the forward-reference to the correct spot in the module.
3106 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3107
3108 if (FunctionName.empty())
3109 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003110
Chris Lattnerac161bf2009-01-02 07:01:27 +00003111 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3112 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3113 Fn->setCallingConv(CC);
3114 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003115 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003116 Fn->setAlignment(Alignment);
3117 Fn->setSection(Section);
3118 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003119 Fn->setPrefixData(Prefix);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003120 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003121
Chris Lattnerac161bf2009-01-02 07:01:27 +00003122 // Add all of the arguments we parsed to the function.
3123 Function::arg_iterator ArgIt = Fn->arg_begin();
3124 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3125 // If the argument has a name, insert it into the argument symbol table.
3126 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003127
Chris Lattnerac161bf2009-01-02 07:01:27 +00003128 // Set the name, if it conflicted, it will be auto-renamed.
3129 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003130
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003131 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003132 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3133 ArgList[i].Name + "'");
3134 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003135
Chris Lattnerac161bf2009-01-02 07:01:27 +00003136 return false;
3137}
3138
3139
3140/// ParseFunctionBody
3141/// ::= '{' BasicBlock+ '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142///
3143bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003144 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003145 return TokError("expected '{' in function body");
3146 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003147
Chris Lattner3432c622009-10-28 03:39:23 +00003148 int FunctionNumber = -1;
3149 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003150
Chris Lattner3432c622009-10-28 03:39:23 +00003151 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003152
Chris Lattnerbbddd962010-01-09 19:20:07 +00003153 // We need at least one basic block.
Chris Lattner4649a732011-06-17 06:42:57 +00003154 if (Lex.getKind() == lltok::rbrace)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003155 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003156
Chris Lattner4649a732011-06-17 06:42:57 +00003157 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003159
Chris Lattnerac161bf2009-01-02 07:01:27 +00003160 // Eat the }.
3161 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003162
Chris Lattnerac161bf2009-01-02 07:01:27 +00003163 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003164 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165}
3166
3167/// ParseBasicBlock
3168/// ::= LabelStr? Instruction*
3169bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3170 // If this basic block starts out with a name, remember it.
3171 std::string Name;
3172 LocTy NameLoc = Lex.getLoc();
3173 if (Lex.getKind() == lltok::LabelStr) {
3174 Name = Lex.getStrVal();
3175 Lex.Lex();
3176 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003177
Chris Lattnerac161bf2009-01-02 07:01:27 +00003178 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3179 if (BB == 0) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003180
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003182
Chris Lattnerac161bf2009-01-02 07:01:27 +00003183 // Parse the instructions in this block until we get a terminator.
3184 Instruction *Inst;
3185 do {
3186 // This instruction may have three possibilities for a name: a) none
3187 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3188 LocTy NameLoc = Lex.getLoc();
3189 int NameID = -1;
3190 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003191
Chris Lattnerac161bf2009-01-02 07:01:27 +00003192 if (Lex.getKind() == lltok::LocalVarID) {
3193 NameID = Lex.getUIntVal();
3194 Lex.Lex();
3195 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3196 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003197 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003198 NameStr = Lex.getStrVal();
3199 Lex.Lex();
3200 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3201 return true;
3202 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003203
Chris Lattner77b89dc2009-12-30 05:23:43 +00003204 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003205 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003206 case InstError: return true;
3207 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003208 BB->getInstList().push_back(Inst);
3209
Chris Lattner77b89dc2009-12-30 05:23:43 +00003210 // With a normal result, we check to see if the instruction is followed by
3211 // a comma and metadata.
3212 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003213 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003214 return true;
3215 break;
3216 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003217 BB->getInstList().push_back(Inst);
3218
Chris Lattner77b89dc2009-12-30 05:23:43 +00003219 // If the instruction parser ate an extra comma at the end of it, it
3220 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003221 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003222 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003223 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003224 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003225
Chris Lattnerac161bf2009-01-02 07:01:27 +00003226 // Set the name on the instruction.
3227 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3228 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003229
Chris Lattnerac161bf2009-01-02 07:01:27 +00003230 return false;
3231}
3232
3233//===----------------------------------------------------------------------===//
3234// Instruction Parsing.
3235//===----------------------------------------------------------------------===//
3236
3237/// ParseInstruction - Parse one of the many different instructions.
3238///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003239int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3240 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241 lltok::Kind Token = Lex.getKind();
3242 if (Token == lltok::Eof)
3243 return TokError("found end of file when expecting more instructions");
3244 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003245 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003246 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003247
Chris Lattnerac161bf2009-01-02 07:01:27 +00003248 switch (Token) {
3249 default: return Error(Loc, "expected instruction opcode");
3250 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003251 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003252 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3253 case lltok::kw_br: return ParseBr(Inst, PFS);
3254 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003255 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003256 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003257 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003258 // Binary Operators.
3259 case lltok::kw_add:
3260 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003261 case lltok::kw_mul:
3262 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003263 bool NUW = EatIfPresent(lltok::kw_nuw);
3264 bool NSW = EatIfPresent(lltok::kw_nsw);
3265 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003266
Chris Lattnera676c0f2011-02-07 16:40:21 +00003267 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003268
Chris Lattnera676c0f2011-02-07 16:40:21 +00003269 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3270 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3271 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003272 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003273 case lltok::kw_fadd:
3274 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003275 case lltok::kw_fmul:
3276 case lltok::kw_fdiv:
3277 case lltok::kw_frem: {
3278 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3279 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3280 if (Res != 0)
3281 return Res;
3282 if (FMF.any())
3283 Inst->setFastMathFlags(FMF);
3284 return 0;
3285 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003286
Chris Lattner35315d02011-02-06 21:44:57 +00003287 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003288 case lltok::kw_udiv:
3289 case lltok::kw_lshr:
3290 case lltok::kw_ashr: {
3291 bool Exact = EatIfPresent(lltok::kw_exact);
3292
3293 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3294 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3295 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003296 }
3297
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003299 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003300 case lltok::kw_and:
3301 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003302 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003303 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003304 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003305 // Casts.
3306 case lltok::kw_trunc:
3307 case lltok::kw_zext:
3308 case lltok::kw_sext:
3309 case lltok::kw_fptrunc:
3310 case lltok::kw_fpext:
3311 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003312 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003313 case lltok::kw_uitofp:
3314 case lltok::kw_sitofp:
3315 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003316 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003317 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003318 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003319 // Other.
3320 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003321 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003322 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3323 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3324 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3325 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003326 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003327 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3328 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3329 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003330 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003331 case lltok::kw_load: return ParseLoad(Inst, PFS);
3332 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003333 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3334 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003335 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003336 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3337 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3338 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3339 }
3340}
3341
3342/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3343bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003344 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003346 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003347 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3348 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3349 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3350 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3351 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3352 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3353 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3354 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3355 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3356 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3357 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3358 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3359 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3360 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3361 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3362 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3363 }
3364 } else {
3365 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003366 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003367 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3368 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3369 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3370 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3371 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3372 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3373 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3374 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3375 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3376 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3377 }
3378 }
3379 Lex.Lex();
3380 return false;
3381}
3382
3383//===----------------------------------------------------------------------===//
3384// Terminator Instructions.
3385//===----------------------------------------------------------------------===//
3386
3387/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003388/// ::= 'ret' void (',' !dbg, !1)*
3389/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003390bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003391 PerFunctionState &PFS) {
3392 SMLoc TypeLoc = Lex.getLoc();
3393 Type *Ty = 0;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003394 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003396 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003397
Chris Lattnerfdd87902009-10-05 05:54:46 +00003398 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003399 if (!ResType->isVoidTy())
3400 return Error(TypeLoc, "value doesn't match function result type '" +
3401 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003402
Owen Anderson55f1c092009-08-13 21:58:54 +00003403 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003404 return false;
3405 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003406
Chris Lattnerac161bf2009-01-02 07:01:27 +00003407 Value *RV;
3408 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003410 if (ResType != RV->getType())
3411 return Error(TypeLoc, "value doesn't match function result type '" +
3412 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003413
Owen Anderson55f1c092009-08-13 21:58:54 +00003414 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003415 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003416}
3417
3418
3419/// ParseBr
3420/// ::= 'br' TypeAndValue
3421/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3422bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3423 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003424 Value *Op0;
3425 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003426 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003427
Chris Lattnerac161bf2009-01-02 07:01:27 +00003428 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3429 Inst = BranchInst::Create(BB);
3430 return false;
3431 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003432
Owen Anderson55f1c092009-08-13 21:58:54 +00003433 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003434 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003435
Chris Lattnerac161bf2009-01-02 07:01:27 +00003436 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003437 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003438 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003439 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003440 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003441
Chris Lattner3ed871f2009-10-27 19:13:16 +00003442 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003443 return false;
3444}
3445
3446/// ParseSwitch
3447/// Instruction
3448/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3449/// JumpTable
3450/// ::= (TypeAndValue ',' TypeAndValue)*
3451bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3452 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003453 Value *Cond;
3454 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003455 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3456 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003457 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003458 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3459 return true;
3460
Duncan Sands19d0b472010-02-16 11:11:14 +00003461 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003462 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003463
Chris Lattnerac161bf2009-01-02 07:01:27 +00003464 // Parse the jump table pairs.
3465 SmallPtrSet<Value*, 32> SeenCases;
3466 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3467 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003468 Value *Constant;
3469 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003470
Chris Lattnerac161bf2009-01-02 07:01:27 +00003471 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3472 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003473 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003474 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003475
Chris Lattnerac161bf2009-01-02 07:01:27 +00003476 if (!SeenCases.insert(Constant))
3477 return Error(CondLoc, "duplicate case value in switch");
3478 if (!isa<ConstantInt>(Constant))
3479 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003480
Chris Lattner3ed871f2009-10-27 19:13:16 +00003481 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003482 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003483
Chris Lattnerac161bf2009-01-02 07:01:27 +00003484 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003485
Chris Lattner3ed871f2009-10-27 19:13:16 +00003486 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003487 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3488 SI->addCase(Table[i].first, Table[i].second);
3489 Inst = SI;
3490 return false;
3491}
3492
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003493/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003494/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003495/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3496bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003497 LocTy AddrLoc;
3498 Value *Address;
3499 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003500 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3501 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003502 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003503
Duncan Sands19d0b472010-02-16 11:11:14 +00003504 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003505 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003506
Chris Lattner3ed871f2009-10-27 19:13:16 +00003507 // Parse the destination list.
3508 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003509
Chris Lattner3ed871f2009-10-27 19:13:16 +00003510 if (Lex.getKind() != lltok::rsquare) {
3511 BasicBlock *DestBB;
3512 if (ParseTypeAndBasicBlock(DestBB, PFS))
3513 return true;
3514 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003515
Chris Lattner3ed871f2009-10-27 19:13:16 +00003516 while (EatIfPresent(lltok::comma)) {
3517 if (ParseTypeAndBasicBlock(DestBB, PFS))
3518 return true;
3519 DestList.push_back(DestBB);
3520 }
3521 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003522
Chris Lattner3ed871f2009-10-27 19:13:16 +00003523 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3524 return true;
3525
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003526 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003527 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3528 IBI->addDestination(DestList[i]);
3529 Inst = IBI;
3530 return false;
3531}
3532
3533
Chris Lattnerac161bf2009-01-02 07:01:27 +00003534/// ParseInvoke
3535/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3536/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3537bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3538 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003539 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003540 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003541 LocTy NoBuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003542 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003543 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003544 LocTy RetTypeLoc;
3545 ValID CalleeID;
3546 SmallVector<ParamInfo, 16> ArgList;
3547
Chris Lattner3ed871f2009-10-27 19:13:16 +00003548 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003549 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003550 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003551 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003552 ParseValID(CalleeID) ||
3553 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003554 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3555 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003556 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003557 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003558 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003559 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003560 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003561
Chris Lattnerac161bf2009-01-02 07:01:27 +00003562 // If RetType is a non-function pointer type, then this is the short syntax
3563 // for the call, which means that RetType is just the return type. Infer the
3564 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00003565 PointerType *PFTy = 0;
3566 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003567 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3568 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3569 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003570 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003571 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3572 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003573
Chris Lattnerac161bf2009-01-02 07:01:27 +00003574 if (!FunctionType::isValidReturnType(RetType))
3575 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003576
Owen Anderson4056ca92009-07-29 22:17:13 +00003577 Ty = FunctionType::get(RetType, ParamTypes, false);
3578 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003579 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003580
Chris Lattnerac161bf2009-01-02 07:01:27 +00003581 // Look up the callee.
3582 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003583 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003584
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003585 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003586 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003587 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003588 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3589 AttributeSet::ReturnIndex,
3590 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003591
Chris Lattnerac161bf2009-01-02 07:01:27 +00003592 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003593
Chris Lattnerac161bf2009-01-02 07:01:27 +00003594 // Loop through FunctionType's arguments and ensure they are specified
3595 // correctly. Also, gather any parameter attributes.
3596 FunctionType::param_iterator I = Ty->param_begin();
3597 FunctionType::param_iterator E = Ty->param_end();
3598 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00003599 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003600 if (I != E) {
3601 ExpectedTy = *I++;
3602 } else if (!Ty->isVarArg()) {
3603 return Error(ArgList[i].Loc, "too many arguments specified");
3604 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003605
Chris Lattnerac161bf2009-01-02 07:01:27 +00003606 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3607 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003608 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003609 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003610 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3611 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003612 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3613 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003614 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003615
Chris Lattnerac161bf2009-01-02 07:01:27 +00003616 if (I != E)
3617 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003618
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003619 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003620 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3621 AttributeSet::FunctionIndex,
3622 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003623
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003624 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003625 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003626
Jay Foad5bd375a2011-07-15 08:37:34 +00003627 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003628 II->setCallingConv(CC);
3629 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003630 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003631 Inst = II;
3632 return false;
3633}
3634
Bill Wendlingf891bf82011-07-31 06:30:59 +00003635/// ParseResume
3636/// ::= 'resume' TypeAndValue
3637bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3638 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003639 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3640 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003641
Bill Wendlingf891bf82011-07-31 06:30:59 +00003642 ResumeInst *RI = ResumeInst::Create(Exn);
3643 Inst = RI;
3644 return false;
3645}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003646
3647//===----------------------------------------------------------------------===//
3648// Binary Operators.
3649//===----------------------------------------------------------------------===//
3650
3651/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003652/// ::= ArithmeticOps TypeAndValue ',' Value
3653///
3654/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3655/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003656bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003657 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003658 LocTy Loc; Value *LHS, *RHS;
3659 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3660 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3661 ParseValue(LHS->getType(), RHS, PFS))
3662 return true;
3663
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003664 bool Valid;
3665 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003666 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003667 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003668 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3669 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003670 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003671 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3672 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003673 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003674
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003675 if (!Valid)
3676 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003677
Chris Lattnerac161bf2009-01-02 07:01:27 +00003678 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3679 return false;
3680}
3681
3682/// ParseLogical
3683/// ::= ArithmeticOps TypeAndValue ',' Value {
3684bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3685 unsigned Opc) {
3686 LocTy Loc; Value *LHS, *RHS;
3687 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3688 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3689 ParseValue(LHS->getType(), RHS, PFS))
3690 return true;
3691
Duncan Sands9dff9be2010-02-15 16:12:20 +00003692 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003693 return Error(Loc,"instruction requires integer or integer vector operands");
3694
3695 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3696 return false;
3697}
3698
3699
3700/// ParseCompare
3701/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3702/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003703bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3704 unsigned Opc) {
3705 // Parse the integer/fp comparison predicate.
3706 LocTy Loc;
3707 unsigned Pred;
3708 Value *LHS, *RHS;
3709 if (ParseCmpPredicate(Pred, Opc) ||
3710 ParseTypeAndValue(LHS, Loc, PFS) ||
3711 ParseToken(lltok::comma, "expected ',' after compare value") ||
3712 ParseValue(LHS->getType(), RHS, PFS))
3713 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003714
Chris Lattnerac161bf2009-01-02 07:01:27 +00003715 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003716 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003717 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003718 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003719 } else {
3720 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003721 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003722 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003723 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003724 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003725 }
3726 return false;
3727}
3728
3729//===----------------------------------------------------------------------===//
3730// Other Instructions.
3731//===----------------------------------------------------------------------===//
3732
3733
3734/// ParseCast
3735/// ::= CastOpc TypeAndValue 'to' Type
3736bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3737 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003738 LocTy Loc;
3739 Value *Op;
3740 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003741 if (ParseTypeAndValue(Op, Loc, PFS) ||
3742 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3743 ParseType(DestTy))
3744 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003745
Chris Lattner89d856e2009-03-01 00:53:13 +00003746 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3747 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003748 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003749 getTypeString(Op->getType()) + "' to '" +
3750 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00003751 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003752 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3753 return false;
3754}
3755
3756/// ParseSelect
3757/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3758bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3759 LocTy Loc;
3760 Value *Op0, *Op1, *Op2;
3761 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3762 ParseToken(lltok::comma, "expected ',' after select condition") ||
3763 ParseTypeAndValue(Op1, PFS) ||
3764 ParseToken(lltok::comma, "expected ',' after select value") ||
3765 ParseTypeAndValue(Op2, PFS))
3766 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003767
Chris Lattnerac161bf2009-01-02 07:01:27 +00003768 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3769 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003770
Chris Lattnerac161bf2009-01-02 07:01:27 +00003771 Inst = SelectInst::Create(Op0, Op1, Op2);
3772 return false;
3773}
3774
Chris Lattnerb55ab542009-01-05 08:18:44 +00003775/// ParseVA_Arg
3776/// ::= 'va_arg' TypeAndValue ',' Type
3777bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003778 Value *Op;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003779 Type *EltTy = 0;
Chris Lattnerb55ab542009-01-05 08:18:44 +00003780 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003781 if (ParseTypeAndValue(Op, PFS) ||
3782 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00003783 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003785
Chris Lattnerb55ab542009-01-05 08:18:44 +00003786 if (!EltTy->isFirstClassType())
3787 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003788
3789 Inst = new VAArgInst(Op, EltTy);
3790 return false;
3791}
3792
3793/// ParseExtractElement
3794/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3795bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3796 LocTy Loc;
3797 Value *Op0, *Op1;
3798 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3799 ParseToken(lltok::comma, "expected ',' after extract value") ||
3800 ParseTypeAndValue(Op1, PFS))
3801 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003802
Chris Lattnerac161bf2009-01-02 07:01:27 +00003803 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3804 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003805
Eric Christopherc9742252009-07-25 02:28:41 +00003806 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003807 return false;
3808}
3809
3810/// ParseInsertElement
3811/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3812bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3813 LocTy Loc;
3814 Value *Op0, *Op1, *Op2;
3815 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3816 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3817 ParseTypeAndValue(Op1, PFS) ||
3818 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3819 ParseTypeAndValue(Op2, PFS))
3820 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003821
Chris Lattnerac161bf2009-01-02 07:01:27 +00003822 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00003823 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003824
Chris Lattnerac161bf2009-01-02 07:01:27 +00003825 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3826 return false;
3827}
3828
3829/// ParseShuffleVector
3830/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3831bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3832 LocTy Loc;
3833 Value *Op0, *Op1, *Op2;
3834 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3835 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3836 ParseTypeAndValue(Op1, PFS) ||
3837 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3838 ParseTypeAndValue(Op2, PFS))
3839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003840
Chris Lattnerac161bf2009-01-02 07:01:27 +00003841 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00003842 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003843
Chris Lattnerac161bf2009-01-02 07:01:27 +00003844 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3845 return false;
3846}
3847
3848/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00003849/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00003850int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003851 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003852 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003853
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003854 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003855 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3856 ParseValue(Ty, Op0, PFS) ||
3857 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003858 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003859 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3860 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003861
Chris Lattnerf4f03422009-12-30 05:27:33 +00003862 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003863 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3864 while (1) {
3865 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003866
Chris Lattner3822f632009-01-02 08:05:26 +00003867 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003868 break;
3869
Chris Lattnerf4f03422009-12-30 05:27:33 +00003870 if (Lex.getKind() == lltok::MetadataVar) {
3871 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00003872 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003873 }
Devang Patel8f842d32009-10-16 18:45:49 +00003874
Chris Lattner3822f632009-01-02 08:05:26 +00003875 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003876 ParseValue(Ty, Op0, PFS) ||
3877 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003878 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003879 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3880 return true;
3881 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003882
Chris Lattnerac161bf2009-01-02 07:01:27 +00003883 if (!Ty->isFirstClassType())
3884 return Error(TypeLoc, "phi node must have first class type");
3885
Jay Foad52131342011-03-30 11:28:46 +00003886 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003887 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3888 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3889 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003890 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003891}
3892
Bill Wendlingfae14752011-08-12 20:24:12 +00003893/// ParseLandingPad
3894/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3895/// Clause
3896/// ::= 'catch' TypeAndValue
3897/// ::= 'filter'
3898/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3899bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3900 Type *Ty = 0; LocTy TyLoc;
3901 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00003902
3903 if (ParseType(Ty, TyLoc) ||
3904 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3905 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3906 return true;
3907
3908 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3909 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3910
3911 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3912 LandingPadInst::ClauseType CT;
3913 if (EatIfPresent(lltok::kw_catch))
3914 CT = LandingPadInst::Catch;
3915 else if (EatIfPresent(lltok::kw_filter))
3916 CT = LandingPadInst::Filter;
3917 else
3918 return TokError("expected 'catch' or 'filter' clause type");
3919
3920 Value *V; LocTy VLoc;
3921 if (ParseTypeAndValue(V, VLoc, PFS)) {
3922 delete LP;
3923 return true;
3924 }
3925
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00003926 // A 'catch' type expects a non-array constant. A filter clause expects an
3927 // array constant.
3928 if (CT == LandingPadInst::Catch) {
3929 if (isa<ArrayType>(V->getType()))
3930 Error(VLoc, "'catch' clause has an invalid type");
3931 } else {
3932 if (!isa<ArrayType>(V->getType()))
3933 Error(VLoc, "'filter' clause has an invalid type");
3934 }
3935
Bill Wendlingfae14752011-08-12 20:24:12 +00003936 LP->addClause(V);
3937 }
3938
3939 Inst = LP;
3940 return false;
3941}
3942
Chris Lattnerac161bf2009-01-02 07:01:27 +00003943/// ParseCall
3944/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3945/// ParameterList OptionalAttrs
3946bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3947 bool isTail) {
Bill Wendling50d27842012-10-15 20:35:56 +00003948 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003949 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003950 LocTy BuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003951 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003952 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003953 LocTy RetTypeLoc;
3954 ValID CalleeID;
3955 SmallVector<ParamInfo, 16> ArgList;
3956 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003957
Chris Lattnerac161bf2009-01-02 07:01:27 +00003958 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3959 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003960 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003961 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003962 ParseValID(CalleeID) ||
3963 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003964 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003965 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003966 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003967
Chris Lattnerac161bf2009-01-02 07:01:27 +00003968 // If RetType is a non-function pointer type, then this is the short syntax
3969 // for the call, which means that RetType is just the return type. Infer the
3970 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00003971 PointerType *PFTy = 0;
3972 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003973 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3974 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3975 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003976 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00003977 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3978 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003979
Chris Lattnerac161bf2009-01-02 07:01:27 +00003980 if (!FunctionType::isValidReturnType(RetType))
3981 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003982
Owen Anderson4056ca92009-07-29 22:17:13 +00003983 Ty = FunctionType::get(RetType, ParamTypes, false);
3984 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003985 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003986
Chris Lattnerac161bf2009-01-02 07:01:27 +00003987 // Look up the callee.
3988 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003989 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003990
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003991 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003992 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003993 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003994 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3995 AttributeSet::ReturnIndex,
3996 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003997
Chris Lattnerac161bf2009-01-02 07:01:27 +00003998 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003999
Chris Lattnerac161bf2009-01-02 07:01:27 +00004000 // Loop through FunctionType's arguments and ensure they are specified
4001 // correctly. Also, gather any parameter attributes.
4002 FunctionType::param_iterator I = Ty->param_begin();
4003 FunctionType::param_iterator E = Ty->param_end();
4004 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00004005 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 if (I != E) {
4007 ExpectedTy = *I++;
4008 } else if (!Ty->isVarArg()) {
4009 return Error(ArgList[i].Loc, "too many arguments specified");
4010 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004011
Chris Lattnerac161bf2009-01-02 07:01:27 +00004012 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4013 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004014 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004015 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004016 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4017 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004018 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4019 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004020 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004021
Chris Lattnerac161bf2009-01-02 07:01:27 +00004022 if (I != E)
4023 return Error(CallLoc, "not enough parameters specified for call");
4024
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004025 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004026 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4027 AttributeSet::FunctionIndex,
4028 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004029
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004030 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004031 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004032
Jay Foad5bd375a2011-07-15 08:37:34 +00004033 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004034 CI->setTailCall(isTail);
4035 CI->setCallingConv(CC);
4036 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004037 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038 Inst = CI;
4039 return false;
4040}
4041
4042//===----------------------------------------------------------------------===//
4043// Memory Instructions.
4044//===----------------------------------------------------------------------===//
4045
4046/// ParseAlloc
Devang Patelea8a4b92009-09-17 23:04:48 +00004047/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattner78103722011-06-17 03:16:47 +00004048int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004049 Value *Size = 0;
Chris Lattner200e0752009-07-02 23:08:13 +00004050 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004051 unsigned Alignment = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004052 Type *Ty = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00004053 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004054
Chris Lattnerb2f39502009-12-30 05:44:30 +00004055 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004056 if (EatIfPresent(lltok::comma)) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00004057 if (Lex.getKind() == lltok::kw_align) {
4058 if (ParseOptionalAlignment(Alignment)) return true;
4059 } else if (Lex.getKind() == lltok::MetadataVar) {
4060 AteExtraComma = true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004061 } else {
Chris Lattnerb2f39502009-12-30 05:44:30 +00004062 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4063 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4064 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004065 }
4066 }
4067
Dan Gohman2140a742010-05-28 01:14:11 +00004068 if (Size && !Size->getType()->isIntegerTy())
4069 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070
Chris Lattner78103722011-06-17 03:16:47 +00004071 Inst = new AllocaInst(Ty, Size, Alignment);
4072 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004073}
4074
4075/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004076/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004077/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004078/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004079int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004081 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004082 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004083 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004084 AtomicOrdering Ordering = NotAtomic;
4085 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004086
4087 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004088 isAtomic = true;
4089 Lex.Lex();
4090 }
4091
Chris Lattnerbc639292011-11-27 06:56:53 +00004092 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004093 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004094 isVolatile = true;
4095 Lex.Lex();
4096 }
4097
Chris Lattnerb2f39502009-12-30 05:44:30 +00004098 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004099 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004100 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4101 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004102
Duncan Sands19d0b472010-02-16 11:11:14 +00004103 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004104 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4105 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004106 if (isAtomic && !Alignment)
4107 return Error(Loc, "atomic load must have explicit non-zero alignment");
4108 if (Ordering == Release || Ordering == AcquireRelease)
4109 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004110
Eli Friedman59b66882011-08-09 23:02:53 +00004111 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004112 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004113}
4114
4115/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004116
4117/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4118/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004119/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004120int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004121 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004122 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004123 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004124 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004125 AtomicOrdering Ordering = NotAtomic;
4126 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004127
4128 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004129 isAtomic = true;
4130 Lex.Lex();
4131 }
4132
Chris Lattnerbc639292011-11-27 06:56:53 +00004133 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004134 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004135 isVolatile = true;
4136 Lex.Lex();
4137 }
4138
Chris Lattnerac161bf2009-01-02 07:01:27 +00004139 if (ParseTypeAndValue(Val, Loc, PFS) ||
4140 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004141 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004142 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004143 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004144 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004145
Duncan Sands19d0b472010-02-16 11:11:14 +00004146 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004147 return Error(PtrLoc, "store operand must be a pointer");
4148 if (!Val->getType()->isFirstClassType())
4149 return Error(Loc, "store operand must be a first class value");
4150 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4151 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004152 if (isAtomic && !Alignment)
4153 return Error(Loc, "atomic store must have explicit non-zero alignment");
4154 if (Ordering == Acquire || Ordering == AcquireRelease)
4155 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004156
Eli Friedman59b66882011-08-09 23:02:53 +00004157 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004158 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004159}
4160
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004161/// ParseCmpXchg
Eli Friedman02e737b2011-08-12 22:50:01 +00004162/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4163/// 'singlethread'? AtomicOrdering
4164int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004165 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4166 bool AteExtraComma = false;
4167 AtomicOrdering Ordering = NotAtomic;
4168 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004169 bool isVolatile = false;
4170
4171 if (EatIfPresent(lltok::kw_volatile))
4172 isVolatile = true;
4173
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004174 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4175 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4176 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4177 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4178 ParseTypeAndValue(New, NewLoc, PFS) ||
4179 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4180 return true;
4181
4182 if (Ordering == Unordered)
4183 return TokError("cmpxchg cannot be unordered");
4184 if (!Ptr->getType()->isPointerTy())
4185 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4186 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4187 return Error(CmpLoc, "compare value and pointer type do not match");
4188 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4189 return Error(NewLoc, "new value and pointer type do not match");
4190 if (!New->getType()->isIntegerTy())
4191 return Error(NewLoc, "cmpxchg operand must be an integer");
4192 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4193 if (Size < 8 || (Size & (Size - 1)))
4194 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4195 " integer");
4196
4197 AtomicCmpXchgInst *CXI =
4198 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4199 CXI->setVolatile(isVolatile);
4200 Inst = CXI;
4201 return AteExtraComma ? InstExtraComma : InstNormal;
4202}
4203
4204/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004205/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4206/// 'singlethread'? AtomicOrdering
4207int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004208 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4209 bool AteExtraComma = false;
4210 AtomicOrdering Ordering = NotAtomic;
4211 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004212 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004213 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004214
4215 if (EatIfPresent(lltok::kw_volatile))
4216 isVolatile = true;
4217
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004218 switch (Lex.getKind()) {
4219 default: return TokError("expected binary operation in atomicrmw");
4220 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4221 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4222 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4223 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4224 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4225 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4226 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4227 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4228 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4229 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4230 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4231 }
4232 Lex.Lex(); // Eat the operation.
4233
4234 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4235 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4236 ParseTypeAndValue(Val, ValLoc, PFS) ||
4237 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4238 return true;
4239
4240 if (Ordering == Unordered)
4241 return TokError("atomicrmw cannot be unordered");
4242 if (!Ptr->getType()->isPointerTy())
4243 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4244 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4245 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4246 if (!Val->getType()->isIntegerTy())
4247 return Error(ValLoc, "atomicrmw operand must be an integer");
4248 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4249 if (Size < 8 || (Size & (Size - 1)))
4250 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4251 " integer");
4252
4253 AtomicRMWInst *RMWI =
4254 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4255 RMWI->setVolatile(isVolatile);
4256 Inst = RMWI;
4257 return AteExtraComma ? InstExtraComma : InstNormal;
4258}
4259
Eli Friedmanfee02c62011-07-25 23:16:38 +00004260/// ParseFence
4261/// ::= 'fence' 'singlethread'? AtomicOrdering
4262int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4263 AtomicOrdering Ordering = NotAtomic;
4264 SynchronizationScope Scope = CrossThread;
4265 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4266 return true;
4267
4268 if (Ordering == Unordered)
4269 return TokError("fence cannot be unordered");
4270 if (Ordering == Monotonic)
4271 return TokError("fence cannot be monotonic");
4272
4273 Inst = new FenceInst(Context, Ordering, Scope);
4274 return InstNormal;
4275}
4276
Chris Lattnerac161bf2009-01-02 07:01:27 +00004277/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004278/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004279int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00004280 Value *Ptr = 0;
4281 Value *Val = 0;
4282 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004283
Dan Gohman16cbbe42009-07-29 15:58:36 +00004284 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004285
Chris Lattner3822f632009-01-02 08:05:26 +00004286 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004287
Eli Benderskyd9806682013-04-22 17:03:42 +00004288 Type *BaseType = Ptr->getType();
4289 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4290 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004291 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004292
Chris Lattnerac161bf2009-01-02 07:01:27 +00004293 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004294 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004295 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004296 if (Lex.getKind() == lltok::MetadataVar) {
4297 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004298 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004299 }
Chris Lattner3822f632009-01-02 08:05:26 +00004300 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004301 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004302 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004303 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4304 return Error(EltLoc, "getelementptr index type missmatch");
4305 if (Val->getType()->isVectorTy()) {
4306 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4307 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4308 if (ValNumEl != PtrNumEl)
4309 return Error(EltLoc,
4310 "getelementptr vector index has a wrong number of elements");
4311 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 Indices.push_back(Val);
4313 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004314
Eli Benderskyd9806682013-04-22 17:03:42 +00004315 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4316 return Error(Loc, "base element of getelementptr must be sized");
4317
4318 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004319 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004320 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004321 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004322 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004323 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004324}
4325
4326/// ParseExtractValue
4327/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004328int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004329 Value *Val; LocTy Loc;
4330 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004331 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004332 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004333 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004334 return true;
4335
Chris Lattner392be582010-02-12 20:49:41 +00004336 if (!Val->getType()->isAggregateType())
4337 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004338
Jay Foad57aa6362011-07-13 10:26:04 +00004339 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004340 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004341 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004342 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343}
4344
4345/// ParseInsertValue
4346/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004347int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348 Value *Val0, *Val1; LocTy Loc0, Loc1;
4349 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004350 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004351 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4352 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4353 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004354 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004356
Chris Lattner392be582010-02-12 20:49:41 +00004357 if (!Val0->getType()->isAggregateType())
4358 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004359
Jay Foad57aa6362011-07-13 10:26:04 +00004360 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004362 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004363 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004364}
Nick Lewycky49f89192009-04-04 07:22:01 +00004365
4366//===----------------------------------------------------------------------===//
4367// Embedded metadata.
4368//===----------------------------------------------------------------------===//
4369
4370/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004371/// ::= Element (',' Element)*
4372/// Element
4373/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004374bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004375 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004376 // Check for an empty list.
4377 if (Lex.getKind() == lltok::rbrace)
4378 return false;
4379
Nick Lewycky49f89192009-04-04 07:22:01 +00004380 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004381 // Null is a special case since it is typeless.
4382 if (EatIfPresent(lltok::kw_null)) {
4383 Elts.push_back(0);
4384 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004385 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004386
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004387 Value *V = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004388 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004389 Elts.push_back(V);
Nick Lewycky49f89192009-04-04 07:22:01 +00004390 } while (EatIfPresent(lltok::comma));
4391
4392 return false;
4393}