blob: d4d6f7cee14ec0498df47104d13abec461ba60ca [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 Rieck7157bb72014-01-14 15:22:47 +0000245 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
246 // OptionalThreadLocal 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
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000257 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000258 case lltok::kw_extern_weak: // OptionalLinkage
259 case lltok::kw_external: { // OptionalLinkage
Nico Rieck7157bb72014-01-14 15:22:47 +0000260 unsigned Linkage, Visibility, DLLStorageClass;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 if (ParseOptionalLinkage(Linkage) ||
262 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000263 ParseOptionalDLLStorageClass(DLLStorageClass) ||
264 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 return true;
266 break;
267 }
268 case lltok::kw_default: // OptionalVisibility
269 case lltok::kw_hidden: // OptionalVisibility
270 case lltok::kw_protected: { // OptionalVisibility
Nico Rieck7157bb72014-01-14 15:22:47 +0000271 unsigned Visibility, DLLStorageClass;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000272 if (ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000273 ParseOptionalDLLStorageClass(DLLStorageClass) ||
274 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
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 Rieck7157bb72014-01-14 15:22:47 +0000283 if (ParseGlobal("", SMLoc(), 0, false, 0, 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 Rieck7157bb72014-01-14 15:22:47 +0000449/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
450/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000451/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000452/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000454bool LLParser::ParseUnnamedGlobal() {
455 unsigned VarID = NumberedVals.size();
456 std::string Name;
457 LocTy NameLoc = Lex.getLoc();
458
459 // Handle the GlobalID form.
460 if (Lex.getKind() == lltok::GlobalID) {
461 if (Lex.getUIntVal() != VarID)
462 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000463 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000464 Lex.Lex(); // eat GlobalID;
465
466 if (ParseToken(lltok::equal, "expected '=' after name"))
467 return true;
468 }
469
470 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000471 unsigned Linkage, Visibility, DLLStorageClass;
Dan Gohman466876b2009-08-12 23:32:33 +0000472 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000473 ParseOptionalVisibility(Visibility) ||
474 ParseOptionalDLLStorageClass(DLLStorageClass))
Dan Gohman466876b2009-08-12 23:32:33 +0000475 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000476
Dan Gohman466876b2009-08-12 23:32:33 +0000477 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000478 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
479 DLLStorageClass);
480 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
Dan Gohman466876b2009-08-12 23:32:33 +0000481}
482
Chris Lattnerac161bf2009-01-02 07:01:27 +0000483/// ParseNamedGlobal:
484/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000485/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
486/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000487bool LLParser::ParseNamedGlobal() {
488 assert(Lex.getKind() == lltok::GlobalVar);
489 LocTy NameLoc = Lex.getLoc();
490 std::string Name = Lex.getStrVal();
491 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000492
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000494 unsigned Linkage, Visibility, DLLStorageClass;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000495 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
496 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000497 ParseOptionalVisibility(Visibility) ||
498 ParseOptionalDLLStorageClass(DLLStorageClass))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000499 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattnerac161bf2009-01-02 07:01:27 +0000501 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000502 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
503 DLLStorageClass);
504 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000505}
506
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000507// MDString:
508// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000509bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000510 std::string Str;
511 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000512 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000513 return false;
514}
515
516// MDNode:
517// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000518//
519/// This version of ParseMDNodeID returns the slot number and null in the case
520/// of a forward reference.
521bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
522 // !{ ..., !42, ... }
523 if (ParseUInt32(SlotNo)) return true;
524
525 // Check existing MDNode.
526 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
527 Result = NumberedMetadata[SlotNo];
528 else
529 Result = 0;
530 return false;
531}
532
Chris Lattner6dac02a2009-12-30 04:15:23 +0000533bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000534 // !{ ..., !42, ... }
535 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000536 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000537
Chris Lattner8eff0152010-04-01 05:14:45 +0000538 // If not a forward reference, just return it now.
539 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000540
Chris Lattner8eff0152010-04-01 05:14:45 +0000541 // Otherwise, create MDNode forward reference.
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000542 MDNode *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000544
Chris Lattnerfc58af22009-12-30 04:51:58 +0000545 if (NumberedMetadata.size() <= MID)
546 NumberedMetadata.resize(MID+1);
547 NumberedMetadata[MID] = FwdNode;
Chris Lattner1797fc72009-12-29 21:53:55 +0000548 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000549 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000550}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000551
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000552/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000553/// !foo = !{ !1, !2 }
554bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000555 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000556 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000557 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000558
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000559 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000560 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000561 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000562 return true;
563
Dan Gohman2637cc12010-07-21 23:38:33 +0000564 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000565 if (Lex.getKind() != lltok::rbrace)
566 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000567 if (ParseToken(lltok::exclaim, "Expected '!' here"))
568 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000569
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000570 MDNode *N = 0;
571 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000572 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000573 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000574
575 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
576 return true;
577
Devang Patelbe626972009-07-29 00:34:02 +0000578 return false;
579}
580
Devang Patel39e64d42009-07-01 19:21:12 +0000581/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000582/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000583bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000584 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000585 Lex.Lex();
586 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000587
588 LocTy TyLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000589 Type *Ty = 0;
Devang Patele059ba6e2009-07-23 01:07:34 +0000590 SmallVector<Value *, 16> Elts;
Chris Lattner278bc952009-12-29 22:40:21 +0000591 if (ParseUInt32(MetadataID) ||
592 ParseToken(lltok::equal, "expected '=' here") ||
593 ParseType(Ty, TyLoc) ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000594 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner278bc952009-12-29 22:40:21 +0000595 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandezb8fd1522010-01-10 07:14:18 +0000596 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner278bc952009-12-29 22:40:21 +0000597 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patele059ba6e2009-07-23 01:07:34 +0000598 return true;
599
Jay Foad5514afe2011-04-21 19:59:31 +0000600 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000601
Chris Lattnerfc58af22009-12-30 04:51:58 +0000602 // See if this was forward referenced, if so, handle it.
Chris Lattner218b22f2009-12-29 21:43:58 +0000603 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Pateld2541152009-07-08 19:23:54 +0000604 FI = ForwardRefMDNodes.find(MetadataID);
605 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman16a5d982010-08-20 22:02:26 +0000606 MDNode *Temp = FI->second.first;
607 Temp->replaceAllUsesWith(Init);
608 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000609 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000610
Chris Lattnerfc58af22009-12-30 04:51:58 +0000611 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
612 } else {
613 if (MetadataID >= NumberedMetadata.size())
614 NumberedMetadata.resize(MetadataID+1);
615
616 if (NumberedMetadata[MetadataID] != 0)
617 return TokError("Metadata id is already used");
618 NumberedMetadata[MetadataID] = Init;
Devang Pateld2541152009-07-08 19:23:54 +0000619 }
620
Devang Patel39e64d42009-07-01 19:21:12 +0000621 return false;
622}
623
Chris Lattnerac161bf2009-01-02 07:01:27 +0000624/// ParseAlias:
Nico Rieck7157bb72014-01-14 15:22:47 +0000625/// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
626/// OptionalLinkage Aliasee
Chris Lattnerac161bf2009-01-02 07:01:27 +0000627/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000628/// ::= TypeAndValue
629/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohman1639c392009-07-27 21:53:46 +0000630/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631///
Nico Rieck7157bb72014-01-14 15:22:47 +0000632/// Everything through DLL storage class has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000633///
634bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
Nico Rieck7157bb72014-01-14 15:22:47 +0000635 unsigned Visibility, unsigned DLLStorageClass) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000636 assert(Lex.getKind() == lltok::kw_alias);
637 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000638 LocTy LinkageLoc = Lex.getLoc();
Rafael Espindola78527052013-10-06 15:10:43 +0000639 unsigned L;
640 if (ParseOptionalLinkage(L))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000641 return true;
642
Rafael Espindola78527052013-10-06 15:10:43 +0000643 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
644
Rafael Espindolacaa43562013-10-09 16:07:32 +0000645 if(!GlobalAlias::isValidLinkage(Linkage))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000646 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000647
Chris Lattnerac161bf2009-01-02 07:01:27 +0000648 Constant *Aliasee;
649 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000650 if (Lex.getKind() != lltok::kw_bitcast &&
651 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000652 if (ParseGlobalTypeAndValue(Aliasee)) return true;
653 } else {
654 // The bitcast dest type is not present, it is implied by the dest type.
655 ValID ID;
656 if (ParseValID(ID)) return true;
657 if (ID.Kind != ValID::t_Constant)
658 return Error(AliaseeLoc, "invalid aliasee");
659 Aliasee = ID.ConstantVal;
660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000661
Duncan Sands19d0b472010-02-16 11:11:14 +0000662 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +0000663 return Error(AliaseeLoc, "alias must have pointer type");
664
665 // Okay, create the alias but do not insert it into the module yet.
666 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
667 (GlobalValue::LinkageTypes)Linkage, Name,
668 Aliasee);
669 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000670 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672 // See if this value already exists in the symbol table. If so, it is either
673 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000674 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000675 // See if this was a redefinition. If so, there is no entry in
676 // ForwardRefVals.
677 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
678 I = ForwardRefVals.find(Name);
679 if (I == ForwardRefVals.end())
680 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
681
682 // Otherwise, this was a definition of forward ref. Verify that types
683 // agree.
684 if (Val->getType() != GA->getType())
685 return Error(NameLoc,
686 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687
Chris Lattnerac161bf2009-01-02 07:01:27 +0000688 // If they agree, just RAUW the old value with the alias and remove the
689 // forward ref info.
690 Val->replaceAllUsesWith(GA);
691 Val->eraseFromParent();
692 ForwardRefVals.erase(I);
693 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000694
Chris Lattnerac161bf2009-01-02 07:01:27 +0000695 // Insert into the module, we know its name won't collide now.
696 M->getAliasList().push_back(GA);
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000697 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000698
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 return false;
700}
701
702/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000703/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
704/// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000705/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000706/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
707/// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000708/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709///
710/// Everything through visibility has been parsed already.
711///
712bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
713 unsigned Linkage, bool HasLinkage,
Nico Rieck7157bb72014-01-14 15:22:47 +0000714 unsigned Visibility, unsigned DLLStorageClass) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715 unsigned AddrSpace;
Shuxin Yang2e1890e2013-10-27 03:08:44 +0000716 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000717 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola026d1522011-01-13 01:30:30 +0000718 LocTy UnnamedAddrLoc;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000719 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000721
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000722 Type *Ty = 0;
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000723 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindola026d1522011-01-13 01:30:30 +0000725 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
726 &UnnamedAddrLoc) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000727 ParseOptionalToken(lltok::kw_externally_initialized,
728 IsExternallyInitialized,
729 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000730 ParseGlobalType(IsConstant) ||
731 ParseType(Ty, TyLoc))
732 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000733
Chris Lattnerac161bf2009-01-02 07:01:27 +0000734 // If the linkage is specified and is external, then no initializer is
735 // present.
736 Constant *Init = 0;
Nico Rieck7157bb72014-01-14 15:22:47 +0000737 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000738 Linkage != GlobalValue::ExternalLinkage)) {
739 if (ParseGlobalValue(Ty, Init))
740 return true;
741 }
742
Duncan Sands19d0b472010-02-16 11:11:14 +0000743 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000744 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000745
Chris Lattnerac161bf2009-01-02 07:01:27 +0000746 GlobalVariable *GV = 0;
747
748 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000749 if (!Name.empty()) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000750 if (GlobalValue *GVal = M->getNamedValue(Name)) {
751 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
752 return Error(NameLoc, "redefinition of global '@" + Name + "'");
753 GV = cast<GlobalVariable>(GVal);
754 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000755 } else {
756 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
757 I = ForwardRefValIDs.find(NumberedVals.size());
758 if (I != ForwardRefValIDs.end()) {
759 GV = cast<GlobalVariable>(I->second.first);
760 ForwardRefValIDs.erase(I);
761 }
762 }
763
764 if (GV == 0) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000765 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000766 Name, 0, GlobalVariable::NotThreadLocal,
767 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000768 } else {
769 if (GV->getType()->getElementType() != Ty)
770 return Error(TyLoc,
771 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000772
Chris Lattnerac161bf2009-01-02 07:01:27 +0000773 // Move the forward-reference to the correct spot in the module.
774 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
775 }
776
777 if (Name.empty())
778 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000779
Chris Lattnerac161bf2009-01-02 07:01:27 +0000780 // Set the parsed properties on the global.
781 if (Init)
782 GV->setInitializer(Init);
783 GV->setConstant(IsConstant);
784 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
785 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000786 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000787 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000788 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000789 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000790
Chris Lattnerac161bf2009-01-02 07:01:27 +0000791 // Parse attributes on the global.
792 while (Lex.getKind() == lltok::comma) {
793 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000794
Chris Lattnerac161bf2009-01-02 07:01:27 +0000795 if (Lex.getKind() == lltok::kw_section) {
796 Lex.Lex();
797 GV->setSection(Lex.getStrVal());
798 if (ParseToken(lltok::StringConstant, "expected global section string"))
799 return true;
800 } else if (Lex.getKind() == lltok::kw_align) {
801 unsigned Alignment;
802 if (ParseOptionalAlignment(Alignment)) return true;
803 GV->setAlignment(Alignment);
804 } else {
805 TokError("unknown global variable property!");
806 }
807 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Chris Lattnerac161bf2009-01-02 07:01:27 +0000809 return false;
810}
811
Bill Wendling63b88192013-02-06 06:52:58 +0000812/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000813/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000814bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000815 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000816 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000817 Lex.Lex();
818
819 assert(Lex.getKind() == lltok::AttrGrpID);
Bill Wendling63b88192013-02-06 06:52:58 +0000820 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000821 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000822 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000823 Lex.Lex();
824
825 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000826 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000827 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000828 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000829 ParseToken(lltok::rbrace, "expected end of attribute group"))
830 return true;
831
Bill Wendlingb32b0412013-02-08 06:32:06 +0000832 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000833 return Error(AttrGrpLoc, "attribute group has no attributes");
834
835 return false;
836}
837
Bill Wendling8b0321d2013-02-08 00:52:31 +0000838/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000839/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000840bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
841 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000842 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000843 bool HaveError = false;
844
845 B.clear();
846
Bill Wendling63b88192013-02-06 06:52:58 +0000847 while (true) {
848 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000849 if (Token == lltok::kw_builtin)
850 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000851 switch (Token) {
852 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000853 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000854 return Error(Lex.getLoc(), "unterminated attribute group");
855 case lltok::rbrace:
856 // Finished.
857 return false;
858
Bill Wendlingb32b0412013-02-08 06:32:06 +0000859 case lltok::AttrGrpID: {
860 // Allow a function to reference an attribute group:
861 //
862 // define void @foo() #1 { ... }
863 if (inAttrGrp)
864 HaveError |=
865 Error(Lex.getLoc(),
866 "cannot have an attribute group reference in an attribute group");
867
868 unsigned AttrGrpNum = Lex.getUIntVal();
869 if (inAttrGrp) break;
870
871 // Save the reference to the attribute group. We'll fill it in later.
872 FwdRefAttrGrps.push_back(AttrGrpNum);
873 break;
874 }
Bill Wendling63b88192013-02-06 06:52:58 +0000875 // Target-dependent attributes:
876 case lltok::StringConstant: {
877 std::string Attr = Lex.getStrVal();
878 Lex.Lex();
879 std::string Val;
880 if (EatIfPresent(lltok::equal) &&
881 ParseStringConstant(Val))
882 return true;
883
884 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000885 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000886 }
887
888 // Target-independent attributes:
889 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000890 // As a hack, we allow function alignment to be initially parsed as an
891 // attribute on a function declaration/definition or added to an attribute
892 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000893 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000894 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000895 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000896 if (ParseToken(lltok::equal, "expected '=' here") ||
897 ParseUInt32(Alignment))
898 return true;
899 } else {
900 if (ParseOptionalAlignment(Alignment))
901 return true;
902 }
Bill Wendling63b88192013-02-06 06:52:58 +0000903 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000904 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000905 }
906 case lltok::kw_alignstack: {
907 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000908 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000909 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000910 if (ParseToken(lltok::equal, "expected '=' here") ||
911 ParseUInt32(Alignment))
912 return true;
913 } else {
914 if (ParseOptionalStackAlignment(Alignment))
915 return true;
916 }
Bill Wendling63b88192013-02-06 06:52:58 +0000917 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000918 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000919 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000920 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000921 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000922 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000923 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
924 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
925 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
926 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
927 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
928 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
929 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
930 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
931 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
932 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
933 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000934 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000935 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
936 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
937 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
938 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
939 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
940 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
941 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
942 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
943 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
944 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
945 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000946
947 // Error handling.
948 case lltok::kw_inreg:
949 case lltok::kw_signext:
950 case lltok::kw_zeroext:
951 HaveError |=
952 Error(Lex.getLoc(),
953 "invalid use of attribute on a function");
954 break;
955 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +0000956 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000957 case lltok::kw_nest:
958 case lltok::kw_noalias:
959 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +0000960 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000961 case lltok::kw_sret:
962 HaveError |=
963 Error(Lex.getLoc(),
964 "invalid use of parameter-only attribute on a function");
965 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000966 }
967
968 Lex.Lex();
969 }
970}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000971
972//===----------------------------------------------------------------------===//
973// GlobalValue Reference/Resolution Routines.
974//===----------------------------------------------------------------------===//
975
976/// GetGlobalVal - Get a value with the specified name or ID, creating a
977/// forward reference record if needed. This can return null if the value
978/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +0000979GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +0000980 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +0000981 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000982 if (PTy == 0) {
983 Error(Loc, "global variable reference must have pointer type");
984 return 0;
985 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000986
Chris Lattnerac161bf2009-01-02 07:01:27 +0000987 // Look this name up in the normal function symbol table.
988 GlobalValue *Val =
989 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000990
Chris Lattnerac161bf2009-01-02 07:01:27 +0000991 // If this is a forward reference for the value, see if we already created a
992 // forward ref record.
993 if (Val == 0) {
994 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
995 I = ForwardRefVals.find(Name);
996 if (I != ForwardRefVals.end())
997 Val = I->second.first;
998 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000999
Chris Lattnerac161bf2009-01-02 07:01:27 +00001000 // If we have the value in the symbol table or fwd-ref table, return it.
1001 if (Val) {
1002 if (Val->getType() == Ty) return Val;
1003 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001004 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001005 return 0;
1006 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001007
Chris Lattnerac161bf2009-01-02 07:01:27 +00001008 // Otherwise, create a new forward reference for this value and remember it.
1009 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001010 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001011 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001012 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001013 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001014 GlobalValue::ExternalWeakLinkage, 0, Name,
1015 0, GlobalVariable::NotThreadLocal,
1016 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001017
Chris Lattnerac161bf2009-01-02 07:01:27 +00001018 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1019 return FwdVal;
1020}
1021
Chris Lattner229907c2011-07-18 04:54:35 +00001022GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1023 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001024 if (PTy == 0) {
1025 Error(Loc, "global variable reference must have pointer type");
1026 return 0;
1027 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001028
Chris Lattnerac161bf2009-01-02 07:01:27 +00001029 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001030
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031 // If this is a forward reference for the value, see if we already created a
1032 // forward ref record.
1033 if (Val == 0) {
1034 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1035 I = ForwardRefValIDs.find(ID);
1036 if (I != ForwardRefValIDs.end())
1037 Val = I->second.first;
1038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001039
Chris Lattnerac161bf2009-01-02 07:01:27 +00001040 // If we have the value in the symbol table or fwd-ref table, return it.
1041 if (Val) {
1042 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001043 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001044 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001045 return 0;
1046 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001047
Chris Lattnerac161bf2009-01-02 07:01:27 +00001048 // Otherwise, create a new forward reference for this value and remember it.
1049 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001050 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001051 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001052 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001053 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1054 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001055
Chris Lattnerac161bf2009-01-02 07:01:27 +00001056 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1057 return FwdVal;
1058}
1059
1060
1061//===----------------------------------------------------------------------===//
1062// Helper Routines.
1063//===----------------------------------------------------------------------===//
1064
1065/// ParseToken - If the current token has the specified kind, eat it and return
1066/// success. Otherwise, emit the specified error and return failure.
1067bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1068 if (Lex.getKind() != T)
1069 return TokError(ErrMsg);
1070 Lex.Lex();
1071 return false;
1072}
1073
Chris Lattner3822f632009-01-02 08:05:26 +00001074/// ParseStringConstant
1075/// ::= StringConstant
1076bool LLParser::ParseStringConstant(std::string &Result) {
1077 if (Lex.getKind() != lltok::StringConstant)
1078 return TokError("expected string constant");
1079 Result = Lex.getStrVal();
1080 Lex.Lex();
1081 return false;
1082}
1083
1084/// ParseUInt32
1085/// ::= uint32
1086bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001087 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1088 return TokError("expected integer");
1089 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1090 if (Val64 != unsigned(Val64))
1091 return TokError("expected 32-bit integer (too large)");
1092 Val = Val64;
1093 Lex.Lex();
1094 return false;
1095}
1096
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001097/// ParseTLSModel
1098/// := 'localdynamic'
1099/// := 'initialexec'
1100/// := 'localexec'
1101bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1102 switch (Lex.getKind()) {
1103 default:
1104 return TokError("expected localdynamic, initialexec or localexec");
1105 case lltok::kw_localdynamic:
1106 TLM = GlobalVariable::LocalDynamicTLSModel;
1107 break;
1108 case lltok::kw_initialexec:
1109 TLM = GlobalVariable::InitialExecTLSModel;
1110 break;
1111 case lltok::kw_localexec:
1112 TLM = GlobalVariable::LocalExecTLSModel;
1113 break;
1114 }
1115
1116 Lex.Lex();
1117 return false;
1118}
1119
1120/// ParseOptionalThreadLocal
1121/// := /*empty*/
1122/// := 'thread_local'
1123/// := 'thread_local' '(' tlsmodel ')'
1124bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1125 TLM = GlobalVariable::NotThreadLocal;
1126 if (!EatIfPresent(lltok::kw_thread_local))
1127 return false;
1128
1129 TLM = GlobalVariable::GeneralDynamicTLSModel;
1130 if (Lex.getKind() == lltok::lparen) {
1131 Lex.Lex();
1132 return ParseTLSModel(TLM) ||
1133 ParseToken(lltok::rparen, "expected ')' after thread local model");
1134 }
1135 return false;
1136}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001137
1138/// ParseOptionalAddrSpace
1139/// := /*empty*/
1140/// := 'addrspace' '(' uint32 ')'
1141bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1142 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001143 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001144 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001146 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001148}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001149
Bill Wendling34c2eb22012-12-04 23:40:58 +00001150/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1151bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1152 bool HaveError = false;
1153
1154 B.clear();
1155
1156 while (1) {
1157 lltok::Kind Token = Lex.getKind();
1158 switch (Token) {
1159 default: // End of attributes.
1160 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001161 case lltok::kw_align: {
1162 unsigned Alignment;
1163 if (ParseOptionalAlignment(Alignment))
1164 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001165 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166 continue;
1167 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001168 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Reid Klecknera534a382013-12-19 02:14:12 +00001169 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001170 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1171 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1172 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1173 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001174 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1175 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001176 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001177 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1178 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1179 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001180
Stephen Lin7577ed52013-04-20 13:16:13 +00001181 case lltok::kw_alignstack:
1182 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001183 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001184 case lltok::kw_inlinehint:
1185 case lltok::kw_minsize:
1186 case lltok::kw_naked:
1187 case lltok::kw_nobuiltin:
1188 case lltok::kw_noduplicate:
1189 case lltok::kw_noimplicitfloat:
1190 case lltok::kw_noinline:
1191 case lltok::kw_nonlazybind:
1192 case lltok::kw_noredzone:
1193 case lltok::kw_noreturn:
1194 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001195 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001196 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001197 case lltok::kw_returns_twice:
1198 case lltok::kw_sanitize_address:
1199 case lltok::kw_sanitize_memory:
1200 case lltok::kw_sanitize_thread:
1201 case lltok::kw_ssp:
1202 case lltok::kw_sspreq:
1203 case lltok::kw_sspstrong:
1204 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001205 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1206 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001207 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001208
Bill Wendling34c2eb22012-12-04 23:40:58 +00001209 Lex.Lex();
1210 }
1211}
1212
1213/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1214bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1215 bool HaveError = false;
1216
1217 B.clear();
1218
1219 while (1) {
1220 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001221 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001222 default: // End of attributes.
1223 return HaveError;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001224 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1225 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1226 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1227 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001228
Bill Wendling34c2eb22012-12-04 23:40:58 +00001229 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001230 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001231 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001232 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001233 case lltok::kw_nest:
1234 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001235 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001236 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001237 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001238 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001239
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001240 case lltok::kw_alignstack:
1241 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001242 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001243 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001244 case lltok::kw_inlinehint:
1245 case lltok::kw_minsize:
1246 case lltok::kw_naked:
1247 case lltok::kw_nobuiltin:
1248 case lltok::kw_noduplicate:
1249 case lltok::kw_noimplicitfloat:
1250 case lltok::kw_noinline:
1251 case lltok::kw_nonlazybind:
1252 case lltok::kw_noredzone:
1253 case lltok::kw_noreturn:
1254 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001255 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001256 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001257 case lltok::kw_returns_twice:
1258 case lltok::kw_sanitize_address:
1259 case lltok::kw_sanitize_memory:
1260 case lltok::kw_sanitize_thread:
1261 case lltok::kw_ssp:
1262 case lltok::kw_sspreq:
1263 case lltok::kw_sspstrong:
1264 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001265 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001266 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001267
1268 case lltok::kw_readnone:
1269 case lltok::kw_readonly:
1270 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001271 }
1272
Chris Lattnerac161bf2009-01-02 07:01:27 +00001273 Lex.Lex();
1274 }
1275}
1276
1277/// ParseOptionalLinkage
1278/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001279/// ::= 'private'
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001280/// ::= 'linker_private'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001281/// ::= 'linker_private_weak'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001282/// ::= 'internal'
1283/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001284/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001285/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001286/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001287/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001288/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001289/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001290/// ::= 'extern_weak'
1291/// ::= 'external'
1292bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1293 HasLinkage = false;
1294 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001295 default: Res=GlobalValue::ExternalLinkage; return false;
1296 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1297 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001298 case lltok::kw_linker_private_weak:
1299 Res = GlobalValue::LinkerPrivateWeakLinkage;
1300 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001301 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1302 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1303 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1304 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1305 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001306 case lltok::kw_available_externally:
1307 Res = GlobalValue::AvailableExternallyLinkage;
1308 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001309 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001310 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001311 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1312 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001313 }
1314 Lex.Lex();
1315 HasLinkage = true;
1316 return false;
1317}
1318
1319/// ParseOptionalVisibility
1320/// ::= /*empty*/
1321/// ::= 'default'
1322/// ::= 'hidden'
1323/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001324///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001325bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1326 switch (Lex.getKind()) {
1327 default: Res = GlobalValue::DefaultVisibility; return false;
1328 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1329 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1330 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1331 }
1332 Lex.Lex();
1333 return false;
1334}
1335
Nico Rieck7157bb72014-01-14 15:22:47 +00001336/// ParseOptionalDLLStorageClass
1337/// ::= /*empty*/
1338/// ::= 'dllimport'
1339/// ::= 'dllexport'
1340///
1341bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1342 switch (Lex.getKind()) {
1343 default: Res = GlobalValue::DefaultStorageClass; return false;
1344 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1345 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1346 }
1347 Lex.Lex();
1348 return false;
1349}
1350
Chris Lattnerac161bf2009-01-02 07:01:27 +00001351/// ParseOptionalCallingConv
1352/// ::= /*empty*/
1353/// ::= 'ccc'
1354/// ::= 'fastcc'
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001355/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356/// ::= 'coldcc'
1357/// ::= 'x86_stdcallcc'
1358/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001359/// ::= 'x86_thiscallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001360/// ::= 'arm_apcscc'
1361/// ::= 'arm_aapcscc'
1362/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001363/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001364/// ::= 'ptx_kernel'
1365/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001366/// ::= 'spir_func'
1367/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001368/// ::= 'x86_64_sysvcc'
1369/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001370/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001371/// ::= 'anyregcc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001373///
Sandeep Patel68c5f472009-09-02 08:44:58 +00001374bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001375 switch (Lex.getKind()) {
1376 default: CC = CallingConv::C; return false;
1377 case lltok::kw_ccc: CC = CallingConv::C; break;
1378 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1379 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1380 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1381 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001382 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001383 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1384 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1385 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001386 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001387 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1388 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001389 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1390 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001391 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001392 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1393 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001394 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001395 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001396 case lltok::kw_cc: {
1397 unsigned ArbitraryCC;
1398 Lex.Lex();
David Blaikie46a9f012012-01-20 21:51:11 +00001399 if (ParseUInt32(ArbitraryCC))
Sandeep Patel68c5f472009-09-02 08:44:58 +00001400 return true;
David Blaikie46a9f012012-01-20 21:51:11 +00001401 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1402 return false;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001403 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001405
Chris Lattnerac161bf2009-01-02 07:01:27 +00001406 Lex.Lex();
1407 return false;
1408}
1409
Chris Lattner5c427632009-12-30 05:31:19 +00001410/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001411/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001412bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1413 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001414 do {
1415 if (Lex.getKind() != lltok::MetadataVar)
1416 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001417
Chris Lattner596760d2009-12-29 21:25:40 +00001418 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001419 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001420 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001421
Chris Lattner1797fc72009-12-29 21:53:55 +00001422 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001423 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001424
1425 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001426 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001427
Dan Gohmanf0715b12010-08-24 14:35:45 +00001428 // This code is similar to that of ParseMetadataValue, however it needs to
1429 // have special-case code for a forward reference; see the comments on
1430 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1431 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001432 if (Lex.getKind() == lltok::lbrace) {
1433 ValID ID;
1434 if (ParseMetadataListValue(ID, PFS))
1435 return true;
1436 assert(ID.Kind == ValID::t_MDNode);
1437 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner8eff0152010-04-01 05:14:45 +00001438 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001439 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001440 if (ParseMDNodeID(Node, NodeID))
1441 return true;
1442 if (Node) {
1443 // If we got the node, add it to the instruction.
1444 Inst->setMetadata(MDK, Node);
1445 } else {
1446 MDRef R = { Loc, MDK, NodeID };
1447 // Otherwise, remember that this should be resolved later.
1448 ForwardRefInstMetadata[Inst].push_back(R);
1449 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001450 }
Chris Lattner596760d2009-12-29 21:25:40 +00001451
Manman Ren209b17c2013-09-28 00:22:27 +00001452 if (MDK == LLVMContext::MD_tbaa)
1453 InstsWithTBAATag.push_back(Inst);
1454
Chris Lattner596760d2009-12-29 21:25:40 +00001455 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001456 } while (EatIfPresent(lltok::comma));
1457 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001458}
1459
Chris Lattnerac161bf2009-01-02 07:01:27 +00001460/// ParseOptionalAlignment
1461/// ::= /* empty */
1462/// ::= 'align' 4
1463bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1464 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001465 if (!EatIfPresent(lltok::kw_align))
1466 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001467 LocTy AlignLoc = Lex.getLoc();
1468 if (ParseUInt32(Alignment)) return true;
1469 if (!isPowerOf2_32(Alignment))
1470 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001471 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001472 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001473 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001474}
1475
Chris Lattnerb2f39502009-12-30 05:44:30 +00001476/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001477/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001478/// ::= ',' align 4
1479///
1480/// This returns with AteExtraComma set to true if it ate an excess comma at the
1481/// end.
1482bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1483 bool &AteExtraComma) {
1484 AteExtraComma = false;
1485 while (EatIfPresent(lltok::comma)) {
1486 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001487 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001488 AteExtraComma = true;
1489 return false;
1490 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001491
Chris Lattner95b0ff42010-04-23 00:50:50 +00001492 if (Lex.getKind() != lltok::kw_align)
1493 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001494
Chris Lattner95b0ff42010-04-23 00:50:50 +00001495 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001496 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001497
Devang Patelea8a4b92009-09-17 23:04:48 +00001498 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001499}
1500
Eli Friedmanfee02c62011-07-25 23:16:38 +00001501/// ParseScopeAndOrdering
1502/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1503/// else: ::=
1504///
1505/// This sets Scope and Ordering to the parsed values.
1506bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1507 AtomicOrdering &Ordering) {
1508 if (!isAtomic)
1509 return false;
1510
1511 Scope = CrossThread;
1512 if (EatIfPresent(lltok::kw_singlethread))
1513 Scope = SingleThread;
1514 switch (Lex.getKind()) {
1515 default: return TokError("Expected ordering on atomic instruction");
1516 case lltok::kw_unordered: Ordering = Unordered; break;
1517 case lltok::kw_monotonic: Ordering = Monotonic; break;
1518 case lltok::kw_acquire: Ordering = Acquire; break;
1519 case lltok::kw_release: Ordering = Release; break;
1520 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1521 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1522 }
1523 Lex.Lex();
1524 return false;
1525}
1526
Charles Davisbe5557e2010-02-12 00:31:15 +00001527/// ParseOptionalStackAlignment
1528/// ::= /* empty */
1529/// ::= 'alignstack' '(' 4 ')'
1530bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1531 Alignment = 0;
1532 if (!EatIfPresent(lltok::kw_alignstack))
1533 return false;
1534 LocTy ParenLoc = Lex.getLoc();
1535 if (!EatIfPresent(lltok::lparen))
1536 return Error(ParenLoc, "expected '('");
1537 LocTy AlignLoc = Lex.getLoc();
1538 if (ParseUInt32(Alignment)) return true;
1539 ParenLoc = Lex.getLoc();
1540 if (!EatIfPresent(lltok::rparen))
1541 return Error(ParenLoc, "expected ')'");
1542 if (!isPowerOf2_32(Alignment))
1543 return Error(AlignLoc, "stack alignment is not a power of two");
1544 return false;
1545}
Devang Patelea8a4b92009-09-17 23:04:48 +00001546
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001547/// ParseIndexList - This parses the index list for an insert/extractvalue
1548/// instruction. This sets AteExtraComma in the case where we eat an extra
1549/// comma at the end of the line and find that it is followed by metadata.
1550/// Clients that don't allow metadata can call the version of this function that
1551/// only takes one argument.
1552///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001553/// ParseIndexList
1554/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001555///
1556bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1557 bool &AteExtraComma) {
1558 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001559
Chris Lattnerac161bf2009-01-02 07:01:27 +00001560 if (Lex.getKind() != lltok::comma)
1561 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001562
Chris Lattner3822f632009-01-02 08:05:26 +00001563 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001564 if (Lex.getKind() == lltok::MetadataVar) {
1565 AteExtraComma = true;
1566 return false;
1567 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001568 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001569 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001570 Indices.push_back(Idx);
1571 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001572
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573 return false;
1574}
1575
1576//===----------------------------------------------------------------------===//
1577// Type Parsing.
1578//===----------------------------------------------------------------------===//
1579
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001580/// ParseType - Parse a type.
1581bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1582 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001583 switch (Lex.getKind()) {
1584 default:
1585 return TokError("expected type");
1586 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001587 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001588 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001589 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001590 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001591 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001592 // Type ::= StructType
1593 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001594 return true;
1595 break;
1596 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001597 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001598 Lex.Lex(); // eat the lsquare.
1599 if (ParseArrayVectorType(Result, false))
1600 return true;
1601 break;
1602 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001603 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001604 Lex.Lex();
1605 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001606 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001607 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001608 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001609 } else if (ParseArrayVectorType(Result, true))
1610 return true;
1611 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001612 case lltok::LocalVar: {
1613 // Type ::= %foo
1614 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001615
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001616 // If the type hasn't been defined yet, create a forward definition and
1617 // remember where that forward def'n was seen (in case it never is defined).
1618 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001619 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001620 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001622 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001623 Lex.Lex();
1624 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001626
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001627 case lltok::LocalVarID: {
1628 // Type ::= %4
1629 if (Lex.getUIntVal() >= NumberedTypes.size())
1630 NumberedTypes.resize(Lex.getUIntVal()+1);
1631 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001632
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001633 // If the type hasn't been defined yet, create a forward definition and
1634 // remember where that forward def'n was seen (in case it never is defined).
1635 if (Entry.first == 0) {
Chris Lattner335d3992011-08-12 18:06:37 +00001636 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001637 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001639 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001640 Lex.Lex();
1641 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001642 }
1643 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001644
1645 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646 while (1) {
1647 switch (Lex.getKind()) {
1648 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001649 default:
1650 if (!AllowVoid && Result->isVoidTy())
1651 return Error(TypeLoc, "void type only allowed for function results");
1652 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001653
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001655 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001656 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001657 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001658 if (Result->isVoidTy())
1659 return TokError("pointers to void are invalid - use i8* instead");
1660 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001661 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001662 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 Lex.Lex();
1664 break;
1665
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001666 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001667 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001668 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001669 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001670 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001671 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001672 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001673 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001674 unsigned AddrSpace;
1675 if (ParseOptionalAddrSpace(AddrSpace) ||
1676 ParseToken(lltok::star, "expected '*' in address space"))
1677 return true;
1678
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001680 break;
1681 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001682
Chris Lattnerac161bf2009-01-02 07:01:27 +00001683 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1684 case lltok::lparen:
1685 if (ParseFunctionType(Result))
1686 return true;
1687 break;
1688 }
1689 }
1690}
1691
1692/// ParseParameterList
1693/// ::= '(' ')'
1694/// ::= '(' Arg (',' Arg)* ')'
1695/// Arg
1696/// ::= Type OptionalAttributes Value OptionalAttributes
1697bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1698 PerFunctionState &PFS) {
1699 if (ParseToken(lltok::lparen, "expected '(' in call"))
1700 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001701
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001702 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001703 while (Lex.getKind() != lltok::rparen) {
1704 // If this isn't the first argument, we need a comma.
1705 if (!ArgList.empty() &&
1706 ParseToken(lltok::comma, "expected ',' in argument list"))
1707 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001708
Chris Lattnerac161bf2009-01-02 07:01:27 +00001709 // Parse the argument.
1710 LocTy ArgLoc;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001712 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001714 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001715 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001716
Chris Lattner5b4a9622009-12-30 02:11:14 +00001717 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001718 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001719 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001720 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1721 AttrIndex++,
1722 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723 }
1724
1725 Lex.Lex(); // Lex the ')'.
1726 return false;
1727}
1728
1729
1730
Chris Lattner2ed06b42009-01-05 18:34:07 +00001731/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001733/// ::= '(' ArgTypeListI ')'
1734/// ArgTypeListI
1735/// ::= /*empty*/
1736/// ::= '...'
1737/// ::= ArgTypeList ',' '...'
1738/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001739///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001740bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1741 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001742 isVarArg = false;
1743 assert(Lex.getKind() == lltok::lparen);
1744 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001745
Chris Lattnerac161bf2009-01-02 07:01:27 +00001746 if (Lex.getKind() == lltok::rparen) {
1747 // empty
1748 } else if (Lex.getKind() == lltok::dotdotdot) {
1749 isVarArg = true;
1750 Lex.Lex();
1751 } else {
1752 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 Type *ArgTy = 0;
Bill Wendling50d27842012-10-15 20:35:56 +00001754 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001755 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001756
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001757 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001758 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001759
Chris Lattnerfdd87902009-10-05 05:54:46 +00001760 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001761 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001762
Chris Lattnerdef19492011-06-17 06:36:20 +00001763 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001764 Name = Lex.getStrVal();
1765 Lex.Lex();
1766 }
Chris Lattner3822f632009-01-02 08:05:26 +00001767
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001768 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001769 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001770
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001771 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001772 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001773 AttributeSet::get(ArgTy->getContext(),
1774 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001775
Chris Lattner3822f632009-01-02 08:05:26 +00001776 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001777 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001778 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001780 break;
1781 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001782
Chris Lattnerac161bf2009-01-02 07:01:27 +00001783 // Otherwise must be an argument type.
1784 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001785 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001786
Chris Lattnerfdd87902009-10-05 05:54:46 +00001787 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001788 return Error(TypeLoc, "argument can not have void type");
1789
Chris Lattnerdef19492011-06-17 06:36:20 +00001790 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001791 Name = Lex.getStrVal();
1792 Lex.Lex();
1793 } else {
1794 Name = "";
1795 }
Chris Lattner3822f632009-01-02 08:05:26 +00001796
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001798 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001799
Bill Wendlingd079a442012-10-15 04:46:55 +00001800 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001801 AttributeSet::get(ArgTy->getContext(),
1802 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001803 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 }
1805 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001806
Chris Lattner3822f632009-01-02 08:05:26 +00001807 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001808}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810/// ParseFunctionType
1811/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001812bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001813 assert(Lex.getKind() == lltok::lparen);
1814
Chris Lattnerce473c72009-01-05 08:04:33 +00001815 if (!FunctionType::isValidReturnType(Result))
1816 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001817
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001818 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001819 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001821 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001822
Chris Lattnerac161bf2009-01-02 07:01:27 +00001823 // Reject names on the arguments lists.
1824 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1825 if (!ArgList[i].Name.empty())
1826 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001827 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001828 return Error(ArgList[i].Loc,
1829 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001831
Jay Foadb804a2b2011-07-12 14:06:48 +00001832 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001834 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001835
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001836 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001837 return false;
1838}
1839
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001840/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1841/// other structs.
1842bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1843 SmallVector<Type*, 8> Elts;
1844 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001845
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001846 Result = StructType::get(Context, Elts, Packed);
1847 return false;
1848}
1849
1850/// ParseStructDefinition - Parse a struct in a 'type' definition.
1851bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1852 std::pair<Type*, LocTy> &Entry,
1853 Type *&ResultTy) {
1854 // If the type was already defined, diagnose the redefinition.
1855 if (Entry.first && !Entry.second.isValid())
1856 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001857
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001858 // If we have opaque, just return without filling in the definition for the
1859 // struct. This counts as a definition as far as the .ll file goes.
1860 if (EatIfPresent(lltok::kw_opaque)) {
1861 // This type is being defined, so clear the location to indicate this.
1862 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001863
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001864 // If this type number has never been uttered, create it.
1865 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001866 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 ResultTy = Entry.first;
1868 return false;
1869 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001870
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001871 // If the type starts with '<', then it is either a packed struct or a vector.
1872 bool isPacked = EatIfPresent(lltok::less);
1873
1874 // If we don't have a struct, then we have a random type alias, which we
1875 // accept for compatibility with old files. These types are not allowed to be
1876 // forward referenced and not allowed to be recursive.
1877 if (Lex.getKind() != lltok::lbrace) {
1878 if (Entry.first)
1879 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001880
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001881 ResultTy = 0;
1882 if (isPacked)
1883 return ParseArrayVectorType(ResultTy, true);
1884 return ParseType(ResultTy);
1885 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001886
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001887 // This type is being defined, so clear the location to indicate this.
1888 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001889
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001890 // If this type number has never been uttered, create it.
1891 if (Entry.first == 0)
Chris Lattner335d3992011-08-12 18:06:37 +00001892 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001893
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001894 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001895
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001896 SmallVector<Type*, 8> Body;
1897 if (ParseStructBody(Body) ||
1898 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1899 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001900
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901 STy->setBody(Body, isPacked);
1902 ResultTy = STy;
1903 return false;
1904}
1905
1906
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001908/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00001909/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001912/// ::= '<' '{' Type (',' Type)* '}' '>'
1913bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 assert(Lex.getKind() == lltok::lbrace);
1915 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001916
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 // Handle the empty struct.
1918 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001919 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920
Chris Lattnerf880ca22009-03-09 04:49:14 +00001921 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001922 Type *Ty = 0;
1923 if (ParseType(Ty)) return true;
1924 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001925
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001927 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001928
Chris Lattner3822f632009-01-02 08:05:26 +00001929 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00001930 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001934 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001935
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001936 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001938
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001940}
1941
1942/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1943/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001944/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945/// ::= '[' APSINTVAL 'x' Types ']'
1946/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001947bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001948 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1949 Lex.getAPSIntVal().getBitWidth() > 64)
1950 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001951
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952 LocTy SizeLoc = Lex.getLoc();
1953 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00001954 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Chris Lattner3822f632009-01-02 08:05:26 +00001956 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1957 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001958
1959 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960 Type *EltTy = 0;
1961 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00001962
Chris Lattner3822f632009-01-02 08:05:26 +00001963 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1964 "expected end of sequential type"))
1965 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001966
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00001968 if (Size == 0)
1969 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 if ((unsigned)Size != Size)
1971 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001972 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00001973 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00001974 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001975 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001976 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001979 }
1980 return false;
1981}
1982
1983//===----------------------------------------------------------------------===//
1984// Function Semantic Analysis.
1985//===----------------------------------------------------------------------===//
1986
Chris Lattner3432c622009-10-28 03:39:23 +00001987LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1988 int functionNumber)
1989 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990
1991 // Insert unnamed arguments into the NumberedVals list.
1992 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1993 AI != E; ++AI)
1994 if (!AI->hasName())
1995 NumberedVals.push_back(AI);
1996}
1997
1998LLParser::PerFunctionState::~PerFunctionState() {
1999 // If there were any forward referenced non-basicblock values, delete them.
2000 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2001 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2002 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002003 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002004 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 delete I->second.first;
2006 I->second.first = 0;
2007 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002008
Chris Lattnerac161bf2009-01-02 07:01:27 +00002009 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2010 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2011 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002012 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002013 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002014 delete I->second.first;
2015 I->second.first = 0;
2016 }
2017}
2018
Chris Lattner3432c622009-10-28 03:39:23 +00002019bool LLParser::PerFunctionState::FinishFunction() {
2020 // Check to see if someone took the address of labels in this block.
2021 if (!P.ForwardRefBlockAddresses.empty()) {
2022 ValID FunctionID;
2023 if (!F.getName().empty()) {
2024 FunctionID.Kind = ValID::t_GlobalName;
2025 FunctionID.StrVal = F.getName();
2026 } else {
2027 FunctionID.Kind = ValID::t_GlobalID;
2028 FunctionID.UIntVal = FunctionNumber;
2029 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002030
Chris Lattner3432c622009-10-28 03:39:23 +00002031 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2032 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2033 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2034 // Resolve all these references.
2035 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2036 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002037
Chris Lattner3432c622009-10-28 03:39:23 +00002038 P.ForwardRefBlockAddresses.erase(FRBAI);
2039 }
2040 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002041
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 if (!ForwardRefVals.empty())
2043 return P.Error(ForwardRefVals.begin()->second.second,
2044 "use of undefined value '%" + ForwardRefVals.begin()->first +
2045 "'");
2046 if (!ForwardRefValIDs.empty())
2047 return P.Error(ForwardRefValIDs.begin()->second.second,
2048 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002049 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 return false;
2051}
2052
2053
2054/// GetVal - Get a value with the specified name or ID, creating a
2055/// forward reference record if needed. This can return null if the value
2056/// exists but does not have the right type.
2057Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002058 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059 // Look this name up in the normal function symbol table.
2060 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002061
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 // If this is a forward reference for the value, see if we already created a
2063 // forward ref record.
2064 if (Val == 0) {
2065 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2066 I = ForwardRefVals.find(Name);
2067 if (I != ForwardRefVals.end())
2068 Val = I->second.first;
2069 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002070
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 // If we have the value in the symbol table or fwd-ref table, return it.
2072 if (Val) {
2073 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002074 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 P.Error(Loc, "'%" + Name + "' is not a basic block");
2076 else
2077 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002078 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079 return 0;
2080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002081
Chris Lattnerac161bf2009-01-02 07:01:27 +00002082 // Don't make placeholders with invalid type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084 P.Error(Loc, "invalid use of a non-first-class type");
2085 return 0;
2086 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002087
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088 // Otherwise, create a new forward reference for this value and remember it.
2089 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002090 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002091 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 else
2093 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002094
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2096 return FwdVal;
2097}
2098
Chris Lattner229907c2011-07-18 04:54:35 +00002099Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 LocTy Loc) {
2101 // Look this name up in the normal function symbol table.
2102 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 // If this is a forward reference for the value, see if we already created a
2105 // forward ref record.
2106 if (Val == 0) {
2107 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2108 I = ForwardRefValIDs.find(ID);
2109 if (I != ForwardRefValIDs.end())
2110 Val = I->second.first;
2111 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002112
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 // If we have the value in the symbol table or fwd-ref table, return it.
2114 if (Val) {
2115 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002116 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002117 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002119 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002120 getTypeString(Val->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 return 0;
2122 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002124 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 P.Error(Loc, "invalid use of a non-first-class type");
2126 return 0;
2127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002128
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 // Otherwise, create a new forward reference for this value and remember it.
2130 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002131 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002132 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002133 else
2134 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002135
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2137 return FwdVal;
2138}
2139
2140/// SetInstName - After an instruction is parsed and inserted into its
2141/// basic block, this installs its name.
2142bool LLParser::PerFunctionState::SetInstName(int NameID,
2143 const std::string &NameStr,
2144 LocTy NameLoc, Instruction *Inst) {
2145 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002146 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002147 if (NameID != -1 || !NameStr.empty())
2148 return P.Error(NameLoc, "instructions returning void cannot have a name");
2149 return false;
2150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 // If this was a numbered instruction, verify that the instruction is the
2153 // expected value and resolve any forward references.
2154 if (NameStr.empty()) {
2155 // If neither a name nor an ID was specified, just use the next ID.
2156 if (NameID == -1)
2157 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002158
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 if (unsigned(NameID) != NumberedVals.size())
2160 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002161 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002162
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2164 ForwardRefValIDs.find(NameID);
2165 if (FI != ForwardRefValIDs.end()) {
2166 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002167 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002168 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002170 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 ForwardRefValIDs.erase(FI);
2172 }
2173
2174 NumberedVals.push_back(Inst);
2175 return false;
2176 }
2177
2178 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2179 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2180 FI = ForwardRefVals.find(NameStr);
2181 if (FI != ForwardRefVals.end()) {
2182 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002183 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002184 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002186 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 ForwardRefVals.erase(FI);
2188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002189
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 // Set the name on the instruction.
2191 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002192
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002193 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002194 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 NameStr + "'");
2196 return false;
2197}
2198
2199/// GetBB - Get a basic block with the specified name or ID, creating a
2200/// forward reference record if needed.
2201BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2202 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002203 return cast_or_null<BasicBlock>(GetVal(Name,
2204 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205}
2206
2207BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002208 return cast_or_null<BasicBlock>(GetVal(ID,
2209 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210}
2211
2212/// DefineBB - Define the specified basic block, which is either named or
2213/// unnamed. If there is an error, this returns null otherwise it returns
2214/// the block being defined.
2215BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2216 LocTy Loc) {
2217 BasicBlock *BB;
2218 if (Name.empty())
2219 BB = GetBB(NumberedVals.size(), Loc);
2220 else
2221 BB = GetBB(Name, Loc);
2222 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002223
Chris Lattnerac161bf2009-01-02 07:01:27 +00002224 // Move the block to the end of the function. Forward ref'd blocks are
2225 // inserted wherever they happen to be referenced.
2226 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 // Remove the block from forward ref sets.
2229 if (Name.empty()) {
2230 ForwardRefValIDs.erase(NumberedVals.size());
2231 NumberedVals.push_back(BB);
2232 } else {
2233 // BB forward references are already in the function symbol table.
2234 ForwardRefVals.erase(Name);
2235 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 return BB;
2238}
2239
2240//===----------------------------------------------------------------------===//
2241// Constants.
2242//===----------------------------------------------------------------------===//
2243
2244/// ParseValID - Parse an abstract value that doesn't necessarily have a
2245/// type implied. For example, if we parse "4" we don't know what integer type
2246/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002247/// sanity. PFS is used to convert function-local operands of metadata (since
2248/// metadata operands are not just parsed here but also converted to values).
2249/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002250bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 ID.Loc = Lex.getLoc();
2252 switch (Lex.getKind()) {
2253 default: return TokError("expected value token");
2254 case lltok::GlobalID: // @42
2255 ID.UIntVal = Lex.getUIntVal();
2256 ID.Kind = ValID::t_GlobalID;
2257 break;
2258 case lltok::GlobalVar: // @foo
2259 ID.StrVal = Lex.getStrVal();
2260 ID.Kind = ValID::t_GlobalName;
2261 break;
2262 case lltok::LocalVarID: // %42
2263 ID.UIntVal = Lex.getUIntVal();
2264 ID.Kind = ValID::t_LocalID;
2265 break;
2266 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 ID.StrVal = Lex.getStrVal();
2268 ID.Kind = ValID::t_LocalName;
2269 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002270 case lltok::exclaim: // !42, !{...}, or !"foo"
2271 return ParseMetadataValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002273 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274 ID.Kind = ValID::t_APSInt;
2275 break;
2276 case lltok::APFloat:
2277 ID.APFloatVal = Lex.getAPFloatVal();
2278 ID.Kind = ValID::t_APFloat;
2279 break;
2280 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002281 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 ID.Kind = ValID::t_Constant;
2283 break;
2284 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002285 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 ID.Kind = ValID::t_Constant;
2287 break;
2288 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2289 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2290 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002291
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292 case lltok::lbrace: {
2293 // ValID ::= '{' ConstVector '}'
2294 Lex.Lex();
2295 SmallVector<Constant*, 16> Elts;
2296 if (ParseGlobalValueVector(Elts) ||
2297 ParseToken(lltok::rbrace, "expected end of struct constant"))
2298 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 ID.ConstantStructElts = new Constant*[Elts.size()];
2301 ID.UIntVal = Elts.size();
2302 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2303 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 return false;
2305 }
2306 case lltok::less: {
2307 // ValID ::= '<' ConstVector '>' --> Vector.
2308 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2309 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002310 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002311
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 SmallVector<Constant*, 16> Elts;
2313 LocTy FirstEltLoc = Lex.getLoc();
2314 if (ParseGlobalValueVector(Elts) ||
2315 (isPackedStruct &&
2316 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2317 ParseToken(lltok::greater, "expected end of constant"))
2318 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002319
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 ID.ConstantStructElts = new Constant*[Elts.size()];
2322 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2323 ID.UIntVal = Elts.size();
2324 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 return false;
2326 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002327
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328 if (Elts.empty())
2329 return Error(ID.Loc, "constant vector must not be empty");
2330
Duncan Sands9dff9be2010-02-15 16:12:20 +00002331 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002332 !Elts[0]->getType()->isFloatingPointTy() &&
2333 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002335 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002336
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 // Verify that all the vector elements have the same type.
2338 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2339 if (Elts[i]->getType() != Elts[0]->getType())
2340 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002341 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002342 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002343
Chris Lattner69229312011-02-15 00:14:00 +00002344 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002345 ID.Kind = ValID::t_Constant;
2346 return false;
2347 }
2348 case lltok::lsquare: { // Array Constant
2349 Lex.Lex();
2350 SmallVector<Constant*, 16> Elts;
2351 LocTy FirstEltLoc = Lex.getLoc();
2352 if (ParseGlobalValueVector(Elts) ||
2353 ParseToken(lltok::rsquare, "expected end of array constant"))
2354 return true;
2355
2356 // Handle empty element.
2357 if (Elts.empty()) {
2358 // Use undef instead of an array because it's inconvenient to determine
2359 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002360 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361 return false;
2362 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002363
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002365 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002366 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002367
Owen Anderson4056ca92009-07-29 22:17:13 +00002368 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002371 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 if (Elts[i]->getType() != Elts[0]->getType())
2373 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002374 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002375 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Jay Foad83be3612011-06-22 09:24:39 +00002378 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379 ID.Kind = ValID::t_Constant;
2380 return false;
2381 }
2382 case lltok::kw_c: // c "foo"
2383 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002384 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2385 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002386 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2387 ID.Kind = ValID::t_Constant;
2388 return false;
2389
2390 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002391 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2392 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002393 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 Lex.Lex();
2395 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002396 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002397 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002398 ParseStringConstant(ID.StrVal) ||
2399 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 ParseToken(lltok::StringConstant, "expected constraint string"))
2401 return true;
2402 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002403 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002404 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405 ID.Kind = ValID::t_InlineAsm;
2406 return false;
2407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002408
Chris Lattner3432c622009-10-28 03:39:23 +00002409 case lltok::kw_blockaddress: {
2410 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2411 Lex.Lex();
2412
2413 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002414
Chris Lattner3432c622009-10-28 03:39:23 +00002415 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2416 ParseValID(Fn) ||
2417 ParseToken(lltok::comma, "expected comma in block address expression")||
2418 ParseValID(Label) ||
2419 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2420 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002421
Chris Lattner3432c622009-10-28 03:39:23 +00002422 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2423 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002424 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002425 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002426
Chris Lattner3432c622009-10-28 03:39:23 +00002427 // Make a global variable as a placeholder for this reference.
2428 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2429 false, GlobalValue::InternalLinkage,
2430 0, "");
2431 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2432 ID.ConstantVal = FwdRef;
2433 ID.Kind = ValID::t_Constant;
2434 return false;
2435 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002436
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 case lltok::kw_trunc:
2438 case lltok::kw_zext:
2439 case lltok::kw_sext:
2440 case lltok::kw_fptrunc:
2441 case lltok::kw_fpext:
2442 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002443 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 case lltok::kw_uitofp:
2445 case lltok::kw_sitofp:
2446 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002447 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002449 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 unsigned Opc = Lex.getUIntVal();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002451 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 Constant *SrcVal;
2453 Lex.Lex();
2454 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2455 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002456 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457 ParseType(DestTy) ||
2458 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2459 return true;
2460 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2461 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002462 getTypeString(SrcVal->getType()) + "' to '" +
2463 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002464 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002465 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002466 ID.Kind = ValID::t_Constant;
2467 return false;
2468 }
2469 case lltok::kw_extractvalue: {
2470 Lex.Lex();
2471 Constant *Val;
2472 SmallVector<unsigned, 4> Indices;
2473 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2474 ParseGlobalTypeAndValue(Val) ||
2475 ParseIndexList(Indices) ||
2476 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2477 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002478
Chris Lattner392be582010-02-12 20:49:41 +00002479 if (!Val->getType()->isAggregateType())
2480 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002481 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002482 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002483 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484 ID.Kind = ValID::t_Constant;
2485 return false;
2486 }
2487 case lltok::kw_insertvalue: {
2488 Lex.Lex();
2489 Constant *Val0, *Val1;
2490 SmallVector<unsigned, 4> Indices;
2491 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2492 ParseGlobalTypeAndValue(Val0) ||
2493 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2494 ParseGlobalTypeAndValue(Val1) ||
2495 ParseIndexList(Indices) ||
2496 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2497 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002498 if (!Val0->getType()->isAggregateType())
2499 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002500 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002502 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503 ID.Kind = ValID::t_Constant;
2504 return false;
2505 }
2506 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002507 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 unsigned PredVal, Opc = Lex.getUIntVal();
2509 Constant *Val0, *Val1;
2510 Lex.Lex();
2511 if (ParseCmpPredicate(PredVal, Opc) ||
2512 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2513 ParseGlobalTypeAndValue(Val0) ||
2514 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2515 ParseGlobalTypeAndValue(Val1) ||
2516 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2517 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002518
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 if (Val0->getType() != Val1->getType())
2520 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002523
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002525 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002527 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002528 } else {
2529 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002530 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002531 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002532 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002533 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002534 }
2535 ID.Kind = ValID::t_Constant;
2536 return false;
2537 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 // Binary Operators.
2540 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002541 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002542 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002543 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002545 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002546 case lltok::kw_udiv:
2547 case lltok::kw_sdiv:
2548 case lltok::kw_fdiv:
2549 case lltok::kw_urem:
2550 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002551 case lltok::kw_frem:
2552 case lltok::kw_shl:
2553 case lltok::kw_lshr:
2554 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002555 bool NUW = false;
2556 bool NSW = false;
2557 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 unsigned Opc = Lex.getUIntVal();
2559 Constant *Val0, *Val1;
2560 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002561 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002562 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2563 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002564 if (EatIfPresent(lltok::kw_nuw))
2565 NUW = true;
2566 if (EatIfPresent(lltok::kw_nsw)) {
2567 NSW = true;
2568 if (EatIfPresent(lltok::kw_nuw))
2569 NUW = true;
2570 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002571 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2572 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002573 if (EatIfPresent(lltok::kw_exact))
2574 Exact = true;
2575 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2577 ParseGlobalTypeAndValue(Val0) ||
2578 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2579 ParseGlobalTypeAndValue(Val1) ||
2580 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2581 return true;
2582 if (Val0->getType() != Val1->getType())
2583 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002584 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002585 if (NUW)
2586 return Error(ModifierLoc, "nuw only applies to integer operations");
2587 if (NSW)
2588 return Error(ModifierLoc, "nsw only applies to integer operations");
2589 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002590 // Check that the type is valid for the operator.
2591 switch (Opc) {
2592 case Instruction::Add:
2593 case Instruction::Sub:
2594 case Instruction::Mul:
2595 case Instruction::UDiv:
2596 case Instruction::SDiv:
2597 case Instruction::URem:
2598 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002599 case Instruction::Shl:
2600 case Instruction::AShr:
2601 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002602 if (!Val0->getType()->isIntOrIntVectorTy())
2603 return Error(ID.Loc, "constexpr requires integer operands");
2604 break;
2605 case Instruction::FAdd:
2606 case Instruction::FSub:
2607 case Instruction::FMul:
2608 case Instruction::FDiv:
2609 case Instruction::FRem:
2610 if (!Val0->getType()->isFPOrFPVectorTy())
2611 return Error(ID.Loc, "constexpr requires fp operands");
2612 break;
2613 default: llvm_unreachable("Unknown binary operator!");
2614 }
Dan Gohman1b849082009-09-07 23:54:19 +00002615 unsigned Flags = 0;
2616 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2617 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002618 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002619 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002620 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 ID.Kind = ValID::t_Constant;
2622 return false;
2623 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002624
Chris Lattnerac161bf2009-01-02 07:01:27 +00002625 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 case lltok::kw_and:
2627 case lltok::kw_or:
2628 case lltok::kw_xor: {
2629 unsigned Opc = Lex.getUIntVal();
2630 Constant *Val0, *Val1;
2631 Lex.Lex();
2632 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2633 ParseGlobalTypeAndValue(Val0) ||
2634 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2635 ParseGlobalTypeAndValue(Val1) ||
2636 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2637 return true;
2638 if (Val0->getType() != Val1->getType())
2639 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002640 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 return Error(ID.Loc,
2642 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002643 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 ID.Kind = ValID::t_Constant;
2645 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646 }
2647
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 case lltok::kw_getelementptr:
2649 case lltok::kw_shufflevector:
2650 case lltok::kw_insertelement:
2651 case lltok::kw_extractelement:
2652 case lltok::kw_select: {
2653 unsigned Opc = Lex.getUIntVal();
2654 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002655 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002657 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002658 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2660 ParseGlobalValueVector(Elts) ||
2661 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2662 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663
Chris Lattnerac161bf2009-01-02 07:01:27 +00002664 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002665 if (Elts.size() == 0 ||
2666 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002668
Jay Foaded8db7d2011-07-21 14:31:17 +00002669 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002670 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002672 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2673 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 } else if (Opc == Instruction::Select) {
2675 if (Elts.size() != 3)
2676 return Error(ID.Loc, "expected three operands to select");
2677 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2678 Elts[2]))
2679 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002680 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002681 } else if (Opc == Instruction::ShuffleVector) {
2682 if (Elts.size() != 3)
2683 return Error(ID.Loc, "expected three operands to shufflevector");
2684 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2685 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002686 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002687 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 } else if (Opc == Instruction::ExtractElement) {
2689 if (Elts.size() != 2)
2690 return Error(ID.Loc, "expected two operands to extractelement");
2691 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2692 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002693 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 } else {
2695 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2696 if (Elts.size() != 3)
2697 return Error(ID.Loc, "expected three operands to insertelement");
2698 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2699 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002700 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002701 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002703
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 ID.Kind = ValID::t_Constant;
2705 return false;
2706 }
2707 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 Lex.Lex();
2710 return false;
2711}
2712
2713/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002714bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002715 C = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 ValID ID;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002717 Value *V = NULL;
2718 bool Parsed = ParseValID(ID) ||
2719 ConvertValIDToValue(Ty, ID, V, NULL);
2720 if (V && !(C = dyn_cast<Constant>(V)))
2721 return Error(ID.Loc, "global values must be constants");
2722 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723}
2724
Victor Hernandez9d75c962010-01-11 22:31:58 +00002725bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002726 Type *Ty = 0;
2727 return ParseType(Ty) ||
2728 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002729}
2730
2731/// ParseGlobalValueVector
2732/// ::= /*empty*/
2733/// ::= TypeAndValue (',' TypeAndValue)*
2734bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2735 // Empty list.
2736 if (Lex.getKind() == lltok::rbrace ||
2737 Lex.getKind() == lltok::rsquare ||
2738 Lex.getKind() == lltok::greater ||
2739 Lex.getKind() == lltok::rparen)
2740 return false;
2741
2742 Constant *C;
2743 if (ParseGlobalTypeAndValue(C)) return true;
2744 Elts.push_back(C);
2745
2746 while (EatIfPresent(lltok::comma)) {
2747 if (ParseGlobalTypeAndValue(C)) return true;
2748 Elts.push_back(C);
2749 }
2750
2751 return false;
2752}
2753
Dan Gohmanc828c542010-08-24 02:24:03 +00002754bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2755 assert(Lex.getKind() == lltok::lbrace);
2756 Lex.Lex();
2757
2758 SmallVector<Value*, 16> Elts;
2759 if (ParseMDNodeVector(Elts, PFS) ||
2760 ParseToken(lltok::rbrace, "expected end of metadata node"))
2761 return true;
2762
Jay Foad5514afe2011-04-21 19:59:31 +00002763 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002764 ID.Kind = ValID::t_MDNode;
2765 return false;
2766}
2767
Dan Gohman8939ba332010-07-14 18:26:50 +00002768/// ParseMetadataValue
2769/// ::= !42
2770/// ::= !{...}
2771/// ::= !"string"
2772bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2773 assert(Lex.getKind() == lltok::exclaim);
2774 Lex.Lex();
2775
2776 // MDNode:
2777 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002778 if (Lex.getKind() == lltok::lbrace)
2779 return ParseMetadataListValue(ID, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002780
2781 // Standalone metadata reference
2782 // !42
2783 if (Lex.getKind() == lltok::APSInt) {
2784 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2785 ID.Kind = ValID::t_MDNode;
2786 return false;
2787 }
2788
2789 // MDString:
2790 // ::= '!' STRINGCONSTANT
2791 if (ParseMDString(ID.MDStringVal)) return true;
2792 ID.Kind = ValID::t_MDString;
2793 return false;
2794}
2795
Victor Hernandez9d75c962010-01-11 22:31:58 +00002796
2797//===----------------------------------------------------------------------===//
2798// Function Parsing.
2799//===----------------------------------------------------------------------===//
2800
Chris Lattner229907c2011-07-18 04:54:35 +00002801bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00002802 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002803 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002805
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002807 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002808 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2809 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2810 return (V == 0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00002812 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2813 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2814 return (V == 0);
2815 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00002816 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002817 FunctionType *FTy =
Victor Hernandez9d75c962010-01-11 22:31:58 +00002818 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2819 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2820 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00002821 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00002822 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00002823 return false;
2824 }
2825 case ValID::t_MDNode:
2826 if (!Ty->isMetadataTy())
2827 return Error(ID.Loc, "metadata value must have metadata type");
2828 V = ID.MDNodeVal;
2829 return false;
2830 case ValID::t_MDString:
2831 if (!Ty->isMetadataTy())
2832 return Error(ID.Loc, "metadata value must have metadata type");
2833 V = ID.MDStringVal;
2834 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 case ValID::t_GlobalName:
2836 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2837 return V == 0;
2838 case ValID::t_GlobalID:
2839 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2840 return V == 0;
2841 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00002842 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00002844 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00002845 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002846 return false;
2847 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00002848 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2850 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002851
Dan Gohman518cda42011-12-17 00:04:22 +00002852 // The lexer has no type info, so builds all half, float, and double FP
2853 // constants as double. Fix this here. Long double does not need this.
2854 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002855 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00002856 if (Ty->isHalfTy())
2857 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2858 &Ignored);
2859 else if (Ty->isFloatTy())
2860 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2861 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002862 }
Owen Anderson69c464d2009-07-27 20:59:43 +00002863 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002864
Chris Lattner8f57d29e2009-01-05 18:24:23 +00002865 if (V->getType() != Ty)
2866 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002867 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 return false;
2870 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00002871 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002872 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002873 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002874 return false;
2875 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00002876 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002877 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00002878 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002879 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002880 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00002881 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00002882 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00002883 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002884 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00002885 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002886 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00002887 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002888 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002890 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 return false;
2892 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00002893 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00002895
Chris Lattnerac161bf2009-01-02 07:01:27 +00002896 V = ID.ConstantVal;
2897 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002898 case ValID::t_ConstantStruct:
2899 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00002900 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002901 if (ST->getNumElements() != ID.UIntVal)
2902 return Error(ID.Loc,
2903 "initializer with struct type has wrong # elements");
2904 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2905 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002906
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002907 // Verify that the elements are compatible with the structtype.
2908 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2909 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2910 return Error(ID.Loc, "element " + Twine(i) +
2911 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002912
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002913 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2914 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002915 } else
2916 return Error(ID.Loc, "constant expression type mismatch");
2917 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002918 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002919 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002920}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002921
Chris Lattner229907c2011-07-18 04:54:35 +00002922bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002923 V = 0;
2924 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002925 return ParseValID(ID, PFS) ||
2926 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927}
2928
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002929bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2930 Type *Ty = 0;
2931 return ParseType(Ty) ||
2932 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933}
2934
Chris Lattner3ed871f2009-10-27 19:13:16 +00002935bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2936 PerFunctionState &PFS) {
2937 Value *V;
2938 Loc = Lex.getLoc();
2939 if (ParseTypeAndValue(V, PFS)) return true;
2940 if (!isa<BasicBlock>(V))
2941 return Error(Loc, "expected a basic block");
2942 BB = cast<BasicBlock>(V);
2943 return false;
2944}
2945
2946
Chris Lattnerac161bf2009-01-02 07:01:27 +00002947/// FunctionHeader
2948/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00002949/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002950/// OptionalAlign OptGC OptionalPrefix
Chris Lattnerac161bf2009-01-02 07:01:27 +00002951bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2952 // Parse the linkage.
2953 LocTy LinkageLoc = Lex.getLoc();
2954 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002955
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00002956 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00002957 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00002958 AttrBuilder RetAttrs;
Sandeep Patel68c5f472009-09-02 08:44:58 +00002959 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002960 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002961 LocTy RetTypeLoc = Lex.getLoc();
2962 if (ParseOptionalLinkage(Linkage) ||
2963 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00002964 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002965 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002966 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00002967 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002968 return true;
2969
2970 // Verify that the linkage is ok.
2971 switch ((GlobalValue::LinkageTypes)Linkage) {
2972 case GlobalValue::ExternalLinkage:
2973 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00002974 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002975 if (isDefine)
2976 return Error(LinkageLoc, "invalid linkage for function definition");
2977 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00002978 case GlobalValue::PrivateLinkage:
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00002979 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling03bcd6e2010-07-01 21:55:59 +00002980 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002981 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00002982 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00002983 case GlobalValue::LinkOnceAnyLinkage:
2984 case GlobalValue::LinkOnceODRLinkage:
2985 case GlobalValue::WeakAnyLinkage:
2986 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002987 if (!isDefine)
2988 return Error(LinkageLoc, "invalid linkage for function declaration");
2989 break;
2990 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00002991 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002992 return Error(LinkageLoc, "invalid function linkage type");
2993 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002994
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002995 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002997
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00002999
3000 std::string FunctionName;
3001 if (Lex.getKind() == lltok::GlobalVar) {
3002 FunctionName = Lex.getStrVal();
3003 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3004 unsigned NameID = Lex.getUIntVal();
3005
3006 if (NameID != NumberedVals.size())
3007 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003008 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003009 } else {
3010 return TokError("expected function name");
3011 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012
Chris Lattner3822f632009-01-02 08:05:26 +00003013 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003014
Chris Lattner3822f632009-01-02 08:05:26 +00003015 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003016 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003017
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003018 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003019 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003020 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003021 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003022 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003024 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003025 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003026 bool UnnamedAddr;
3027 LocTy UnnamedAddrLoc;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003028 Constant *Prefix = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00003029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003030 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003031 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3032 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003033 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003034 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003035 (EatIfPresent(lltok::kw_section) &&
3036 ParseStringConstant(Section)) ||
3037 ParseOptionalAlignment(Alignment) ||
3038 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003039 ParseStringConstant(GC)) ||
3040 (EatIfPresent(lltok::kw_prefix) &&
3041 ParseGlobalTypeAndValue(Prefix)))
Chris Lattner3822f632009-01-02 08:05:26 +00003042 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043
Michael Gottesman41748d72013-06-27 00:25:01 +00003044 if (FuncAttrs.contains(Attribute::Builtin))
3045 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003046
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003048 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003049 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003050 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003052
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 // Okay, if we got here, the function is syntactically valid. Convert types
3054 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003055 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003056 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003057
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003058 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003059 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3060 AttributeSet::ReturnIndex,
3061 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003062
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003064 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003065 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3066 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003067 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3068 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003069 }
3070
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003071 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003072 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3073 AttributeSet::FunctionIndex,
3074 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075
Bill Wendlinge94d8432012-12-07 23:16:57 +00003076 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003077
Bill Wendling749a43d2012-12-30 13:50:49 +00003078 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003079 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3080
Chris Lattner229907c2011-07-18 04:54:35 +00003081 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003082 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003083 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003084
3085 Fn = 0;
3086 if (!FunctionName.empty()) {
3087 // If this was a definition of a forward reference, remove the definition
3088 // from the forward reference table and fill in the forward ref.
3089 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3090 ForwardRefVals.find(FunctionName);
3091 if (FRVI != ForwardRefVals.end()) {
3092 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003093 if (!Fn)
3094 return Error(FRVI->second.second, "invalid forward reference to "
3095 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003096 if (Fn->getType() != PFT)
3097 return Error(FRVI->second.second, "invalid forward reference to "
3098 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003099
Chris Lattnerac161bf2009-01-02 07:01:27 +00003100 ForwardRefVals.erase(FRVI);
3101 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003102 // Reject redefinitions.
3103 return Error(NameLoc, "invalid redefinition of function '" +
3104 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003105 } else if (M->getNamedValue(FunctionName)) {
3106 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003108
Dan Gohman399d6ae2009-08-29 23:37:49 +00003109 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003110 // If this is a definition of a forward referenced function, make sure the
3111 // types agree.
3112 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3113 = ForwardRefValIDs.find(NumberedVals.size());
3114 if (I != ForwardRefValIDs.end()) {
3115 Fn = cast<Function>(I->second.first);
3116 if (Fn->getType() != PFT)
3117 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003118 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003119 ForwardRefValIDs.erase(I);
3120 }
3121 }
3122
3123 if (Fn == 0)
3124 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3125 else // Move the forward-reference to the correct spot in the module.
3126 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3127
3128 if (FunctionName.empty())
3129 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003130
Chris Lattnerac161bf2009-01-02 07:01:27 +00003131 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3132 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003133 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003134 Fn->setCallingConv(CC);
3135 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003136 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003137 Fn->setAlignment(Alignment);
3138 Fn->setSection(Section);
3139 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003140 Fn->setPrefixData(Prefix);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003141 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003142
Chris Lattnerac161bf2009-01-02 07:01:27 +00003143 // Add all of the arguments we parsed to the function.
3144 Function::arg_iterator ArgIt = Fn->arg_begin();
3145 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3146 // If the argument has a name, insert it into the argument symbol table.
3147 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003148
Chris Lattnerac161bf2009-01-02 07:01:27 +00003149 // Set the name, if it conflicted, it will be auto-renamed.
3150 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003151
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003152 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003153 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3154 ArgList[i].Name + "'");
3155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003156
Chris Lattnerac161bf2009-01-02 07:01:27 +00003157 return false;
3158}
3159
3160
3161/// ParseFunctionBody
3162/// ::= '{' BasicBlock+ '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003163///
3164bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003165 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003166 return TokError("expected '{' in function body");
3167 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003168
Chris Lattner3432c622009-10-28 03:39:23 +00003169 int FunctionNumber = -1;
3170 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003171
Chris Lattner3432c622009-10-28 03:39:23 +00003172 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003173
Chris Lattnerbbddd962010-01-09 19:20:07 +00003174 // We need at least one basic block.
Chris Lattner4649a732011-06-17 06:42:57 +00003175 if (Lex.getKind() == lltok::rbrace)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003176 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003177
Chris Lattner4649a732011-06-17 06:42:57 +00003178 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003179 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003180
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 // Eat the }.
3182 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003183
Chris Lattnerac161bf2009-01-02 07:01:27 +00003184 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003185 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003186}
3187
3188/// ParseBasicBlock
3189/// ::= LabelStr? Instruction*
3190bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3191 // If this basic block starts out with a name, remember it.
3192 std::string Name;
3193 LocTy NameLoc = Lex.getLoc();
3194 if (Lex.getKind() == lltok::LabelStr) {
3195 Name = Lex.getStrVal();
3196 Lex.Lex();
3197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Chris Lattnerac161bf2009-01-02 07:01:27 +00003199 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3200 if (BB == 0) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003201
Chris Lattnerac161bf2009-01-02 07:01:27 +00003202 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003203
Chris Lattnerac161bf2009-01-02 07:01:27 +00003204 // Parse the instructions in this block until we get a terminator.
3205 Instruction *Inst;
3206 do {
3207 // This instruction may have three possibilities for a name: a) none
3208 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3209 LocTy NameLoc = Lex.getLoc();
3210 int NameID = -1;
3211 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003212
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 if (Lex.getKind() == lltok::LocalVarID) {
3214 NameID = Lex.getUIntVal();
3215 Lex.Lex();
3216 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3217 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003218 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003219 NameStr = Lex.getStrVal();
3220 Lex.Lex();
3221 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3222 return true;
3223 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003224
Chris Lattner77b89dc2009-12-30 05:23:43 +00003225 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003226 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003227 case InstError: return true;
3228 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003229 BB->getInstList().push_back(Inst);
3230
Chris Lattner77b89dc2009-12-30 05:23:43 +00003231 // With a normal result, we check to see if the instruction is followed by
3232 // a comma and metadata.
3233 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003234 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003235 return true;
3236 break;
3237 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003238 BB->getInstList().push_back(Inst);
3239
Chris Lattner77b89dc2009-12-30 05:23:43 +00003240 // If the instruction parser ate an extra comma at the end of it, it
3241 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003242 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003243 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003244 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003245 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003246
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247 // Set the name on the instruction.
3248 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3249 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003250
Chris Lattnerac161bf2009-01-02 07:01:27 +00003251 return false;
3252}
3253
3254//===----------------------------------------------------------------------===//
3255// Instruction Parsing.
3256//===----------------------------------------------------------------------===//
3257
3258/// ParseInstruction - Parse one of the many different instructions.
3259///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003260int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3261 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003262 lltok::Kind Token = Lex.getKind();
3263 if (Token == lltok::Eof)
3264 return TokError("found end of file when expecting more instructions");
3265 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003266 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003268
Chris Lattnerac161bf2009-01-02 07:01:27 +00003269 switch (Token) {
3270 default: return Error(Loc, "expected instruction opcode");
3271 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003272 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3274 case lltok::kw_br: return ParseBr(Inst, PFS);
3275 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003276 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003277 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003278 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003279 // Binary Operators.
3280 case lltok::kw_add:
3281 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003282 case lltok::kw_mul:
3283 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003284 bool NUW = EatIfPresent(lltok::kw_nuw);
3285 bool NSW = EatIfPresent(lltok::kw_nsw);
3286 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003287
Chris Lattnera676c0f2011-02-07 16:40:21 +00003288 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003289
Chris Lattnera676c0f2011-02-07 16:40:21 +00003290 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3291 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3292 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003293 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003294 case lltok::kw_fadd:
3295 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003296 case lltok::kw_fmul:
3297 case lltok::kw_fdiv:
3298 case lltok::kw_frem: {
3299 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3300 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3301 if (Res != 0)
3302 return Res;
3303 if (FMF.any())
3304 Inst->setFastMathFlags(FMF);
3305 return 0;
3306 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003307
Chris Lattner35315d02011-02-06 21:44:57 +00003308 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003309 case lltok::kw_udiv:
3310 case lltok::kw_lshr:
3311 case lltok::kw_ashr: {
3312 bool Exact = EatIfPresent(lltok::kw_exact);
3313
3314 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3315 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3316 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003317 }
3318
Chris Lattnerac161bf2009-01-02 07:01:27 +00003319 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003320 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003321 case lltok::kw_and:
3322 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003323 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003324 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003325 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003326 // Casts.
3327 case lltok::kw_trunc:
3328 case lltok::kw_zext:
3329 case lltok::kw_sext:
3330 case lltok::kw_fptrunc:
3331 case lltok::kw_fpext:
3332 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003333 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003334 case lltok::kw_uitofp:
3335 case lltok::kw_sitofp:
3336 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003337 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003338 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003339 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 // Other.
3341 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003342 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003343 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3344 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3345 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3346 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003347 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003348 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3349 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3350 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003351 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003352 case lltok::kw_load: return ParseLoad(Inst, PFS);
3353 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003354 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3355 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003356 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003357 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3358 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3359 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3360 }
3361}
3362
3363/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3364bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003365 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003366 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003367 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003368 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3369 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3370 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3371 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3372 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3373 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3374 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3375 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3376 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3377 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3378 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3379 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3380 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3381 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3382 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3383 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3384 }
3385 } else {
3386 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003387 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003388 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3389 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3390 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3391 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3392 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3393 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3394 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3395 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3396 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3397 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3398 }
3399 }
3400 Lex.Lex();
3401 return false;
3402}
3403
3404//===----------------------------------------------------------------------===//
3405// Terminator Instructions.
3406//===----------------------------------------------------------------------===//
3407
3408/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003409/// ::= 'ret' void (',' !dbg, !1)*
3410/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003411bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003412 PerFunctionState &PFS) {
3413 SMLoc TypeLoc = Lex.getLoc();
3414 Type *Ty = 0;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003415 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003417 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003418
Chris Lattnerfdd87902009-10-05 05:54:46 +00003419 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003420 if (!ResType->isVoidTy())
3421 return Error(TypeLoc, "value doesn't match function result type '" +
3422 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003423
Owen Anderson55f1c092009-08-13 21:58:54 +00003424 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003425 return false;
3426 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003427
Chris Lattnerac161bf2009-01-02 07:01:27 +00003428 Value *RV;
3429 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003430
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003431 if (ResType != RV->getType())
3432 return Error(TypeLoc, "value doesn't match function result type '" +
3433 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003434
Owen Anderson55f1c092009-08-13 21:58:54 +00003435 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003436 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003437}
3438
3439
3440/// ParseBr
3441/// ::= 'br' TypeAndValue
3442/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3443bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3444 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003445 Value *Op0;
3446 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003447 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003448
Chris Lattnerac161bf2009-01-02 07:01:27 +00003449 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3450 Inst = BranchInst::Create(BB);
3451 return false;
3452 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003453
Owen Anderson55f1c092009-08-13 21:58:54 +00003454 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003455 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003456
Chris Lattnerac161bf2009-01-02 07:01:27 +00003457 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003458 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003459 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003460 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003461 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003462
Chris Lattner3ed871f2009-10-27 19:13:16 +00003463 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003464 return false;
3465}
3466
3467/// ParseSwitch
3468/// Instruction
3469/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3470/// JumpTable
3471/// ::= (TypeAndValue ',' TypeAndValue)*
3472bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3473 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003474 Value *Cond;
3475 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003476 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003478 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003479 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3480 return true;
3481
Duncan Sands19d0b472010-02-16 11:11:14 +00003482 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003483 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003484
Chris Lattnerac161bf2009-01-02 07:01:27 +00003485 // Parse the jump table pairs.
3486 SmallPtrSet<Value*, 32> SeenCases;
3487 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3488 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003489 Value *Constant;
3490 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003491
Chris Lattnerac161bf2009-01-02 07:01:27 +00003492 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3493 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003494 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003495 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003496
Chris Lattnerac161bf2009-01-02 07:01:27 +00003497 if (!SeenCases.insert(Constant))
3498 return Error(CondLoc, "duplicate case value in switch");
3499 if (!isa<ConstantInt>(Constant))
3500 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003501
Chris Lattner3ed871f2009-10-27 19:13:16 +00003502 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003504
Chris Lattnerac161bf2009-01-02 07:01:27 +00003505 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003506
Chris Lattner3ed871f2009-10-27 19:13:16 +00003507 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003508 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3509 SI->addCase(Table[i].first, Table[i].second);
3510 Inst = SI;
3511 return false;
3512}
3513
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003514/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003515/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003516/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3517bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003518 LocTy AddrLoc;
3519 Value *Address;
3520 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003521 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3522 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003523 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003524
Duncan Sands19d0b472010-02-16 11:11:14 +00003525 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003526 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003527
Chris Lattner3ed871f2009-10-27 19:13:16 +00003528 // Parse the destination list.
3529 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003530
Chris Lattner3ed871f2009-10-27 19:13:16 +00003531 if (Lex.getKind() != lltok::rsquare) {
3532 BasicBlock *DestBB;
3533 if (ParseTypeAndBasicBlock(DestBB, PFS))
3534 return true;
3535 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003536
Chris Lattner3ed871f2009-10-27 19:13:16 +00003537 while (EatIfPresent(lltok::comma)) {
3538 if (ParseTypeAndBasicBlock(DestBB, PFS))
3539 return true;
3540 DestList.push_back(DestBB);
3541 }
3542 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003543
Chris Lattner3ed871f2009-10-27 19:13:16 +00003544 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3545 return true;
3546
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003547 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003548 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3549 IBI->addDestination(DestList[i]);
3550 Inst = IBI;
3551 return false;
3552}
3553
3554
Chris Lattnerac161bf2009-01-02 07:01:27 +00003555/// ParseInvoke
3556/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3557/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3558bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3559 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003560 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003561 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003562 LocTy NoBuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003563 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003564 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003565 LocTy RetTypeLoc;
3566 ValID CalleeID;
3567 SmallVector<ParamInfo, 16> ArgList;
3568
Chris Lattner3ed871f2009-10-27 19:13:16 +00003569 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003570 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003571 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003572 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003573 ParseValID(CalleeID) ||
3574 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003575 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3576 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003577 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003578 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003579 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003580 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003581 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003582
Chris Lattnerac161bf2009-01-02 07:01:27 +00003583 // If RetType is a non-function pointer type, then this is the short syntax
3584 // for the call, which means that RetType is just the return type. Infer the
3585 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00003586 PointerType *PFTy = 0;
3587 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003588 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3589 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3590 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003591 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003592 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3593 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003594
Chris Lattnerac161bf2009-01-02 07:01:27 +00003595 if (!FunctionType::isValidReturnType(RetType))
3596 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003597
Owen Anderson4056ca92009-07-29 22:17:13 +00003598 Ty = FunctionType::get(RetType, ParamTypes, false);
3599 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003600 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003601
Chris Lattnerac161bf2009-01-02 07:01:27 +00003602 // Look up the callee.
3603 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003604 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003605
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003606 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003607 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003608 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003609 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3610 AttributeSet::ReturnIndex,
3611 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003612
Chris Lattnerac161bf2009-01-02 07:01:27 +00003613 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003614
Chris Lattnerac161bf2009-01-02 07:01:27 +00003615 // Loop through FunctionType's arguments and ensure they are specified
3616 // correctly. Also, gather any parameter attributes.
3617 FunctionType::param_iterator I = Ty->param_begin();
3618 FunctionType::param_iterator E = Ty->param_end();
3619 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00003620 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003621 if (I != E) {
3622 ExpectedTy = *I++;
3623 } else if (!Ty->isVarArg()) {
3624 return Error(ArgList[i].Loc, "too many arguments specified");
3625 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003626
Chris Lattnerac161bf2009-01-02 07:01:27 +00003627 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3628 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003629 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003630 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003631 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3632 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003633 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3634 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003636
Chris Lattnerac161bf2009-01-02 07:01:27 +00003637 if (I != E)
3638 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003639
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003640 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003641 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3642 AttributeSet::FunctionIndex,
3643 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003644
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003645 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003646 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003647
Jay Foad5bd375a2011-07-15 08:37:34 +00003648 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003649 II->setCallingConv(CC);
3650 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003651 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003652 Inst = II;
3653 return false;
3654}
3655
Bill Wendlingf891bf82011-07-31 06:30:59 +00003656/// ParseResume
3657/// ::= 'resume' TypeAndValue
3658bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3659 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003660 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3661 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003662
Bill Wendlingf891bf82011-07-31 06:30:59 +00003663 ResumeInst *RI = ResumeInst::Create(Exn);
3664 Inst = RI;
3665 return false;
3666}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003667
3668//===----------------------------------------------------------------------===//
3669// Binary Operators.
3670//===----------------------------------------------------------------------===//
3671
3672/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003673/// ::= ArithmeticOps TypeAndValue ',' Value
3674///
3675/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3676/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003677bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003678 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003679 LocTy Loc; Value *LHS, *RHS;
3680 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3681 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3682 ParseValue(LHS->getType(), RHS, PFS))
3683 return true;
3684
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003685 bool Valid;
3686 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003687 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003688 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003689 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3690 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003691 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003692 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3693 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003694 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003695
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003696 if (!Valid)
3697 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003698
Chris Lattnerac161bf2009-01-02 07:01:27 +00003699 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3700 return false;
3701}
3702
3703/// ParseLogical
3704/// ::= ArithmeticOps TypeAndValue ',' Value {
3705bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3706 unsigned Opc) {
3707 LocTy Loc; Value *LHS, *RHS;
3708 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3709 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3710 ParseValue(LHS->getType(), RHS, PFS))
3711 return true;
3712
Duncan Sands9dff9be2010-02-15 16:12:20 +00003713 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003714 return Error(Loc,"instruction requires integer or integer vector operands");
3715
3716 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3717 return false;
3718}
3719
3720
3721/// ParseCompare
3722/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3723/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003724bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3725 unsigned Opc) {
3726 // Parse the integer/fp comparison predicate.
3727 LocTy Loc;
3728 unsigned Pred;
3729 Value *LHS, *RHS;
3730 if (ParseCmpPredicate(Pred, Opc) ||
3731 ParseTypeAndValue(LHS, Loc, PFS) ||
3732 ParseToken(lltok::comma, "expected ',' after compare value") ||
3733 ParseValue(LHS->getType(), RHS, PFS))
3734 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003735
Chris Lattnerac161bf2009-01-02 07:01:27 +00003736 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003737 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003738 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003739 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003740 } else {
3741 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003742 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003743 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003744 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003745 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003746 }
3747 return false;
3748}
3749
3750//===----------------------------------------------------------------------===//
3751// Other Instructions.
3752//===----------------------------------------------------------------------===//
3753
3754
3755/// ParseCast
3756/// ::= CastOpc TypeAndValue 'to' Type
3757bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3758 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003759 LocTy Loc;
3760 Value *Op;
3761 Type *DestTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003762 if (ParseTypeAndValue(Op, Loc, PFS) ||
3763 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3764 ParseType(DestTy))
3765 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003766
Chris Lattner89d856e2009-03-01 00:53:13 +00003767 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3768 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003769 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003770 getTypeString(Op->getType()) + "' to '" +
3771 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00003772 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003773 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3774 return false;
3775}
3776
3777/// ParseSelect
3778/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3779bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3780 LocTy Loc;
3781 Value *Op0, *Op1, *Op2;
3782 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3783 ParseToken(lltok::comma, "expected ',' after select condition") ||
3784 ParseTypeAndValue(Op1, PFS) ||
3785 ParseToken(lltok::comma, "expected ',' after select value") ||
3786 ParseTypeAndValue(Op2, PFS))
3787 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003788
Chris Lattnerac161bf2009-01-02 07:01:27 +00003789 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3790 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003791
Chris Lattnerac161bf2009-01-02 07:01:27 +00003792 Inst = SelectInst::Create(Op0, Op1, Op2);
3793 return false;
3794}
3795
Chris Lattnerb55ab542009-01-05 08:18:44 +00003796/// ParseVA_Arg
3797/// ::= 'va_arg' TypeAndValue ',' Type
3798bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003799 Value *Op;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003800 Type *EltTy = 0;
Chris Lattnerb55ab542009-01-05 08:18:44 +00003801 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003802 if (ParseTypeAndValue(Op, PFS) ||
3803 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00003804 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003805 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003806
Chris Lattnerb55ab542009-01-05 08:18:44 +00003807 if (!EltTy->isFirstClassType())
3808 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003809
3810 Inst = new VAArgInst(Op, EltTy);
3811 return false;
3812}
3813
3814/// ParseExtractElement
3815/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3816bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3817 LocTy Loc;
3818 Value *Op0, *Op1;
3819 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3820 ParseToken(lltok::comma, "expected ',' after extract value") ||
3821 ParseTypeAndValue(Op1, PFS))
3822 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003823
Chris Lattnerac161bf2009-01-02 07:01:27 +00003824 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3825 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003826
Eric Christopherc9742252009-07-25 02:28:41 +00003827 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003828 return false;
3829}
3830
3831/// ParseInsertElement
3832/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3833bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3834 LocTy Loc;
3835 Value *Op0, *Op1, *Op2;
3836 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3837 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3838 ParseTypeAndValue(Op1, PFS) ||
3839 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3840 ParseTypeAndValue(Op2, PFS))
3841 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003842
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00003844 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003845
Chris Lattnerac161bf2009-01-02 07:01:27 +00003846 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3847 return false;
3848}
3849
3850/// ParseShuffleVector
3851/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3852bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3853 LocTy Loc;
3854 Value *Op0, *Op1, *Op2;
3855 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3856 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3857 ParseTypeAndValue(Op1, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3859 ParseTypeAndValue(Op2, PFS))
3860 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003861
Chris Lattnerac161bf2009-01-02 07:01:27 +00003862 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00003863 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003864
Chris Lattnerac161bf2009-01-02 07:01:27 +00003865 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3866 return false;
3867}
3868
3869/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00003870/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00003871int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003872 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003873 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003874
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003875 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003876 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3877 ParseValue(Ty, Op0, PFS) ||
3878 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003879 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003880 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3881 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003882
Chris Lattnerf4f03422009-12-30 05:27:33 +00003883 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3885 while (1) {
3886 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003887
Chris Lattner3822f632009-01-02 08:05:26 +00003888 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003889 break;
3890
Chris Lattnerf4f03422009-12-30 05:27:33 +00003891 if (Lex.getKind() == lltok::MetadataVar) {
3892 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00003893 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003894 }
Devang Patel8f842d32009-10-16 18:45:49 +00003895
Chris Lattner3822f632009-01-02 08:05:26 +00003896 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003897 ParseValue(Ty, Op0, PFS) ||
3898 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00003899 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003900 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3901 return true;
3902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003903
Chris Lattnerac161bf2009-01-02 07:01:27 +00003904 if (!Ty->isFirstClassType())
3905 return Error(TypeLoc, "phi node must have first class type");
3906
Jay Foad52131342011-03-30 11:28:46 +00003907 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003908 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3909 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3910 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00003911 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003912}
3913
Bill Wendlingfae14752011-08-12 20:24:12 +00003914/// ParseLandingPad
3915/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3916/// Clause
3917/// ::= 'catch' TypeAndValue
3918/// ::= 'filter'
3919/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3920bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3921 Type *Ty = 0; LocTy TyLoc;
3922 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00003923
3924 if (ParseType(Ty, TyLoc) ||
3925 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3926 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3927 return true;
3928
3929 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3930 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3931
3932 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3933 LandingPadInst::ClauseType CT;
3934 if (EatIfPresent(lltok::kw_catch))
3935 CT = LandingPadInst::Catch;
3936 else if (EatIfPresent(lltok::kw_filter))
3937 CT = LandingPadInst::Filter;
3938 else
3939 return TokError("expected 'catch' or 'filter' clause type");
3940
3941 Value *V; LocTy VLoc;
3942 if (ParseTypeAndValue(V, VLoc, PFS)) {
3943 delete LP;
3944 return true;
3945 }
3946
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00003947 // A 'catch' type expects a non-array constant. A filter clause expects an
3948 // array constant.
3949 if (CT == LandingPadInst::Catch) {
3950 if (isa<ArrayType>(V->getType()))
3951 Error(VLoc, "'catch' clause has an invalid type");
3952 } else {
3953 if (!isa<ArrayType>(V->getType()))
3954 Error(VLoc, "'filter' clause has an invalid type");
3955 }
3956
Bill Wendlingfae14752011-08-12 20:24:12 +00003957 LP->addClause(V);
3958 }
3959
3960 Inst = LP;
3961 return false;
3962}
3963
Chris Lattnerac161bf2009-01-02 07:01:27 +00003964/// ParseCall
3965/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3966/// ParameterList OptionalAttrs
3967bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3968 bool isTail) {
Bill Wendling50d27842012-10-15 20:35:56 +00003969 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003970 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003971 LocTy BuiltinLoc;
Sandeep Patel68c5f472009-09-02 08:44:58 +00003972 CallingConv::ID CC;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003973 Type *RetType = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003974 LocTy RetTypeLoc;
3975 ValID CalleeID;
3976 SmallVector<ParamInfo, 16> ArgList;
3977 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003978
Chris Lattnerac161bf2009-01-02 07:01:27 +00003979 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3980 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003981 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003982 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003983 ParseValID(CalleeID) ||
3984 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003985 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003986 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003987 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003988
Chris Lattnerac161bf2009-01-02 07:01:27 +00003989 // If RetType is a non-function pointer type, then this is the short syntax
3990 // for the call, which means that RetType is just the return type. Infer the
3991 // rest of the function argument types from the arguments that are present.
Chris Lattner229907c2011-07-18 04:54:35 +00003992 PointerType *PFTy = 0;
3993 FunctionType *Ty = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003994 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3995 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3996 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003997 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00003998 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3999 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004000
Chris Lattnerac161bf2009-01-02 07:01:27 +00004001 if (!FunctionType::isValidReturnType(RetType))
4002 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004003
Owen Anderson4056ca92009-07-29 22:17:13 +00004004 Ty = FunctionType::get(RetType, ParamTypes, false);
4005 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004007
Chris Lattnerac161bf2009-01-02 07:01:27 +00004008 // Look up the callee.
4009 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004010 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004011
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004012 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004013 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004014 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004015 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4016 AttributeSet::ReturnIndex,
4017 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004018
Chris Lattnerac161bf2009-01-02 07:01:27 +00004019 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004020
Chris Lattnerac161bf2009-01-02 07:01:27 +00004021 // Loop through FunctionType's arguments and ensure they are specified
4022 // correctly. Also, gather any parameter attributes.
4023 FunctionType::param_iterator I = Ty->param_begin();
4024 FunctionType::param_iterator E = Ty->param_end();
4025 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00004026 Type *ExpectedTy = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004027 if (I != E) {
4028 ExpectedTy = *I++;
4029 } else if (!Ty->isVarArg()) {
4030 return Error(ArgList[i].Loc, "too many arguments specified");
4031 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004032
Chris Lattnerac161bf2009-01-02 07:01:27 +00004033 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4034 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004035 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004036 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004037 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4038 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004039 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4040 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004042
Chris Lattnerac161bf2009-01-02 07:01:27 +00004043 if (I != E)
4044 return Error(CallLoc, "not enough parameters specified for call");
4045
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004046 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004047 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4048 AttributeSet::FunctionIndex,
4049 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004050
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004051 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004052 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004053
Jay Foad5bd375a2011-07-15 08:37:34 +00004054 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004055 CI->setTailCall(isTail);
4056 CI->setCallingConv(CC);
4057 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004058 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004059 Inst = CI;
4060 return false;
4061}
4062
4063//===----------------------------------------------------------------------===//
4064// Memory Instructions.
4065//===----------------------------------------------------------------------===//
4066
4067/// ParseAlloc
Devang Patelea8a4b92009-09-17 23:04:48 +00004068/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattner78103722011-06-17 03:16:47 +00004069int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070 Value *Size = 0;
Chris Lattner200e0752009-07-02 23:08:13 +00004071 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004072 unsigned Alignment = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004073 Type *Ty = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00004074 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004075
Chris Lattnerb2f39502009-12-30 05:44:30 +00004076 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004077 if (EatIfPresent(lltok::comma)) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00004078 if (Lex.getKind() == lltok::kw_align) {
4079 if (ParseOptionalAlignment(Alignment)) return true;
4080 } else if (Lex.getKind() == lltok::MetadataVar) {
4081 AteExtraComma = true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004082 } else {
Chris Lattnerb2f39502009-12-30 05:44:30 +00004083 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4084 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4085 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004086 }
4087 }
4088
Dan Gohman2140a742010-05-28 01:14:11 +00004089 if (Size && !Size->getType()->isIntegerTy())
4090 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004091
Chris Lattner78103722011-06-17 03:16:47 +00004092 Inst = new AllocaInst(Ty, Size, Alignment);
4093 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004094}
4095
4096/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004097/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004098/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004099/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004100int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004101 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004102 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004103 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004104 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004105 AtomicOrdering Ordering = NotAtomic;
4106 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004107
4108 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004109 isAtomic = true;
4110 Lex.Lex();
4111 }
4112
Chris Lattnerbc639292011-11-27 06:56:53 +00004113 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004114 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004115 isVolatile = true;
4116 Lex.Lex();
4117 }
4118
Chris Lattnerb2f39502009-12-30 05:44:30 +00004119 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004120 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004121 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4122 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004123
Duncan Sands19d0b472010-02-16 11:11:14 +00004124 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004125 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4126 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004127 if (isAtomic && !Alignment)
4128 return Error(Loc, "atomic load must have explicit non-zero alignment");
4129 if (Ordering == Release || Ordering == AcquireRelease)
4130 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004131
Eli Friedman59b66882011-08-09 23:02:53 +00004132 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004133 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004134}
4135
4136/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004137
4138/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4139/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004140/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004141int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004142 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004143 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004144 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004145 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004146 AtomicOrdering Ordering = NotAtomic;
4147 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004148
4149 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004150 isAtomic = true;
4151 Lex.Lex();
4152 }
4153
Chris Lattnerbc639292011-11-27 06:56:53 +00004154 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004155 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004156 isVolatile = true;
4157 Lex.Lex();
4158 }
4159
Chris Lattnerac161bf2009-01-02 07:01:27 +00004160 if (ParseTypeAndValue(Val, Loc, PFS) ||
4161 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004162 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004163 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004164 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004165 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004166
Duncan Sands19d0b472010-02-16 11:11:14 +00004167 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004168 return Error(PtrLoc, "store operand must be a pointer");
4169 if (!Val->getType()->isFirstClassType())
4170 return Error(Loc, "store operand must be a first class value");
4171 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4172 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004173 if (isAtomic && !Alignment)
4174 return Error(Loc, "atomic store must have explicit non-zero alignment");
4175 if (Ordering == Acquire || Ordering == AcquireRelease)
4176 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004177
Eli Friedman59b66882011-08-09 23:02:53 +00004178 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004179 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004180}
4181
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004182/// ParseCmpXchg
Eli Friedman02e737b2011-08-12 22:50:01 +00004183/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4184/// 'singlethread'? AtomicOrdering
4185int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004186 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4187 bool AteExtraComma = false;
4188 AtomicOrdering Ordering = NotAtomic;
4189 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004190 bool isVolatile = false;
4191
4192 if (EatIfPresent(lltok::kw_volatile))
4193 isVolatile = true;
4194
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004195 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4196 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4197 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4198 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4199 ParseTypeAndValue(New, NewLoc, PFS) ||
4200 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4201 return true;
4202
4203 if (Ordering == Unordered)
4204 return TokError("cmpxchg cannot be unordered");
4205 if (!Ptr->getType()->isPointerTy())
4206 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4207 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4208 return Error(CmpLoc, "compare value and pointer type do not match");
4209 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4210 return Error(NewLoc, "new value and pointer type do not match");
4211 if (!New->getType()->isIntegerTy())
4212 return Error(NewLoc, "cmpxchg operand must be an integer");
4213 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4214 if (Size < 8 || (Size & (Size - 1)))
4215 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4216 " integer");
4217
4218 AtomicCmpXchgInst *CXI =
4219 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4220 CXI->setVolatile(isVolatile);
4221 Inst = CXI;
4222 return AteExtraComma ? InstExtraComma : InstNormal;
4223}
4224
4225/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004226/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4227/// 'singlethread'? AtomicOrdering
4228int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004229 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4230 bool AteExtraComma = false;
4231 AtomicOrdering Ordering = NotAtomic;
4232 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004233 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004234 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004235
4236 if (EatIfPresent(lltok::kw_volatile))
4237 isVolatile = true;
4238
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004239 switch (Lex.getKind()) {
4240 default: return TokError("expected binary operation in atomicrmw");
4241 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4242 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4243 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4244 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4245 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4246 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4247 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4248 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4249 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4250 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4251 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4252 }
4253 Lex.Lex(); // Eat the operation.
4254
4255 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4256 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4257 ParseTypeAndValue(Val, ValLoc, PFS) ||
4258 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4259 return true;
4260
4261 if (Ordering == Unordered)
4262 return TokError("atomicrmw cannot be unordered");
4263 if (!Ptr->getType()->isPointerTy())
4264 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4265 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4266 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4267 if (!Val->getType()->isIntegerTy())
4268 return Error(ValLoc, "atomicrmw operand must be an integer");
4269 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4270 if (Size < 8 || (Size & (Size - 1)))
4271 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4272 " integer");
4273
4274 AtomicRMWInst *RMWI =
4275 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4276 RMWI->setVolatile(isVolatile);
4277 Inst = RMWI;
4278 return AteExtraComma ? InstExtraComma : InstNormal;
4279}
4280
Eli Friedmanfee02c62011-07-25 23:16:38 +00004281/// ParseFence
4282/// ::= 'fence' 'singlethread'? AtomicOrdering
4283int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4284 AtomicOrdering Ordering = NotAtomic;
4285 SynchronizationScope Scope = CrossThread;
4286 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4287 return true;
4288
4289 if (Ordering == Unordered)
4290 return TokError("fence cannot be unordered");
4291 if (Ordering == Monotonic)
4292 return TokError("fence cannot be monotonic");
4293
4294 Inst = new FenceInst(Context, Ordering, Scope);
4295 return InstNormal;
4296}
4297
Chris Lattnerac161bf2009-01-02 07:01:27 +00004298/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004299/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004300int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00004301 Value *Ptr = 0;
4302 Value *Val = 0;
4303 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004304
Dan Gohman16cbbe42009-07-29 15:58:36 +00004305 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004306
Chris Lattner3822f632009-01-02 08:05:26 +00004307 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004308
Eli Benderskyd9806682013-04-22 17:03:42 +00004309 Type *BaseType = Ptr->getType();
4310 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4311 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004313
Chris Lattnerac161bf2009-01-02 07:01:27 +00004314 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004315 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004316 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004317 if (Lex.getKind() == lltok::MetadataVar) {
4318 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004319 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004320 }
Chris Lattner3822f632009-01-02 08:05:26 +00004321 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004322 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004324 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4325 return Error(EltLoc, "getelementptr index type missmatch");
4326 if (Val->getType()->isVectorTy()) {
4327 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4328 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4329 if (ValNumEl != PtrNumEl)
4330 return Error(EltLoc,
4331 "getelementptr vector index has a wrong number of elements");
4332 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004333 Indices.push_back(Val);
4334 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004335
Eli Benderskyd9806682013-04-22 17:03:42 +00004336 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4337 return Error(Loc, "base element of getelementptr must be sized");
4338
4339 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004340 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004341 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004342 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004343 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004344 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004345}
4346
4347/// ParseExtractValue
4348/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004349int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 Value *Val; LocTy Loc;
4351 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004352 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004353 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004354 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 return true;
4356
Chris Lattner392be582010-02-12 20:49:41 +00004357 if (!Val->getType()->isAggregateType())
4358 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004359
Jay Foad57aa6362011-07-13 10:26:04 +00004360 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004362 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004363 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004364}
4365
4366/// ParseInsertValue
4367/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004368int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004369 Value *Val0, *Val1; LocTy Loc0, Loc1;
4370 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004371 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004372 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4373 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4374 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004375 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004377
Chris Lattner392be582010-02-12 20:49:41 +00004378 if (!Val0->getType()->isAggregateType())
4379 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004380
Jay Foad57aa6362011-07-13 10:26:04 +00004381 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004383 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004384 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004385}
Nick Lewycky49f89192009-04-04 07:22:01 +00004386
4387//===----------------------------------------------------------------------===//
4388// Embedded metadata.
4389//===----------------------------------------------------------------------===//
4390
4391/// ParseMDNodeVector
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004392/// ::= Element (',' Element)*
4393/// Element
4394/// ::= 'null' | TypeAndValue
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00004395bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004396 PerFunctionState *PFS) {
Dan Gohman1e0213a2010-07-13 19:33:27 +00004397 // Check for an empty list.
4398 if (Lex.getKind() == lltok::rbrace)
4399 return false;
4400
Nick Lewycky49f89192009-04-04 07:22:01 +00004401 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004402 // Null is a special case since it is typeless.
4403 if (EatIfPresent(lltok::kw_null)) {
4404 Elts.push_back(0);
4405 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004406 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004407
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004408 Value *V = 0;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004409 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004410 Elts.push_back(V);
Nick Lewycky49f89192009-04-04 07:22:01 +00004411 } while (EatIfPresent(lltok::comma));
4412
4413 return false;
4414}