blob: eb6afd36c77221e930da026998b80de03f573f0a [file] [log] [blame]
Chris Lattnerdf986172009-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"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000026#include "llvm/Support/raw_ostream.h"
Lang Hames5fa792e2011-10-17 23:24:48 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000028using namespace llvm;
29
Chris Lattnerdb125cf2011-07-18 04:54:35 +000030static std::string getTypeString(Type *T) {
Chris Lattner0cd0d882011-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 Lattner3ed88ef2009-01-02 08:05:26 +000037/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000038bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000039 // Prime the lexer.
40 Lex.Lex();
41
Chris Lattnerad7d1e22009-01-04 20:44:11 +000042 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
Chris Lattnerdf986172009-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 Lattner449c3102010-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;
56
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
59
60 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
61 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000062 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000063 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
64 }
65 }
66 ForwardRefInstMetadata.clear();
67 }
68
69
Chris Lattner09d9ef42009-10-28 03:39:23 +000070 // If there are entries in ForwardRefBlockAddresses at this point, they are
71 // references after the function was defined. Resolve those now.
72 while (!ForwardRefBlockAddresses.empty()) {
73 // Okay, we are referencing an already-parsed function, resolve them now.
74 Function *TheFn = 0;
75 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
76 if (Fn.Kind == ValID::t_GlobalName)
77 TheFn = M->getFunction(Fn.StrVal);
78 else if (Fn.UIntVal < NumberedVals.size())
79 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
80
81 if (TheFn == 0)
82 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83
84 // Resolve all these references.
85 if (ResolveForwardRefBlockAddresses(TheFn,
86 ForwardRefBlockAddresses.begin()->second,
87 0))
88 return true;
89
90 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
91 }
92
Chris Lattner1afcace2011-07-09 17:41:24 +000093 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
94 if (NumberedTypes[i].second.isValid())
95 return Error(NumberedTypes[i].second,
96 "use of undefined type '%" + Twine(i) + "'");
97
98 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
99 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
100 if (I->second.second.isValid())
101 return Error(I->second.second,
102 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000103
Chris Lattnerdf986172009-01-02 07:01:27 +0000104 if (!ForwardRefVals.empty())
105 return Error(ForwardRefVals.begin()->second.second,
106 "use of undefined value '@" + ForwardRefVals.begin()->first +
107 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000108
Chris Lattnerdf986172009-01-02 07:01:27 +0000109 if (!ForwardRefValIDs.empty())
110 return Error(ForwardRefValIDs.begin()->second.second,
111 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000112 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000113
Devang Patel1c7eea62009-07-08 19:23:54 +0000114 if (!ForwardRefMDNodes.empty())
115 return Error(ForwardRefMDNodes.begin()->second.second,
116 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000117 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000118
Devang Patel1c7eea62009-07-08 19:23:54 +0000119
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 // Look for intrinsic functions and CallInst that need to be upgraded
121 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
122 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000123
Bill Wendlingdf77a712011-08-27 06:11:03 +0000124 // Upgrade to new EH scheme. N.B. This will go away in 3.1.
125 UpgradeExceptionHandling(M);
126
Devang Patele4b27562009-08-28 23:24:31 +0000127 // Check debug info intrinsics.
128 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000129 return false;
130}
131
Chris Lattner09d9ef42009-10-28 03:39:23 +0000132bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
133 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
134 PerFunctionState *PFS) {
135 // Loop over all the references, resolving them.
136 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
137 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000138 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000139 if (Refs[i].first.Kind == ValID::t_LocalName)
140 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000141 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000142 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
143 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
144 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000145 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 } else {
147 Res = dyn_cast_or_null<BasicBlock>(
148 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
149 }
150
Chris Lattnercdfc9402009-11-01 01:27:45 +0000151 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000152 return Error(Refs[i].first.Loc,
153 "referenced value is not a basic block");
154
155 // Get the BlockAddress for this and update references to use it.
156 BlockAddress *BA = BlockAddress::get(TheFn, Res);
157 Refs[i].second->replaceAllUsesWith(BA);
158 Refs[i].second->eraseFromParent();
159 }
160 return false;
161}
162
163
Chris Lattnerdf986172009-01-02 07:01:27 +0000164//===----------------------------------------------------------------------===//
165// Top-Level Entities
166//===----------------------------------------------------------------------===//
167
168bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 while (1) {
170 switch (Lex.getKind()) {
171 default: return TokError("expected top-level entity");
172 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173 case lltok::kw_declare: if (ParseDeclare()) return true; break;
174 case lltok::kw_define: if (ParseDefine()) return true; break;
175 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
176 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
177 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000178 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000179 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000180 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000183 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000184
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000188 // OptionalAddrSpace OptionalUnNammedAddr
189 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000190 case lltok::kw_private: // OptionalLinkage
191 case lltok::kw_linker_private: // OptionalLinkage
192 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000193 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000194 case lltok::kw_internal: // OptionalLinkage
195 case lltok::kw_weak: // OptionalLinkage
196 case lltok::kw_weak_odr: // OptionalLinkage
197 case lltok::kw_linkonce: // OptionalLinkage
198 case lltok::kw_linkonce_odr: // OptionalLinkage
199 case lltok::kw_appending: // OptionalLinkage
200 case lltok::kw_dllexport: // OptionalLinkage
201 case lltok::kw_common: // OptionalLinkage
202 case lltok::kw_dllimport: // OptionalLinkage
203 case lltok::kw_extern_weak: // OptionalLinkage
204 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 unsigned Linkage, Visibility;
206 if (ParseOptionalLinkage(Linkage) ||
207 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000208 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000209 return true;
210 break;
211 }
212 case lltok::kw_default: // OptionalVisibility
213 case lltok::kw_hidden: // OptionalVisibility
214 case lltok::kw_protected: { // OptionalVisibility
215 unsigned Visibility;
216 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000217 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 return true;
219 break;
220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000221
Chris Lattnerdf986172009-01-02 07:01:27 +0000222 case lltok::kw_thread_local: // OptionalThreadLocal
223 case lltok::kw_addrspace: // OptionalAddrSpace
224 case lltok::kw_constant: // GlobalType
225 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000226 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000227 break;
228 }
229 }
230}
231
232
233/// toplevelentity
234/// ::= 'module' 'asm' STRINGCONSTANT
235bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
237 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000238
239 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000242
Rafael Espindola38c4e532011-03-02 04:14:42 +0000243 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000244 return false;
245}
246
247/// toplevelentity
248/// ::= 'target' 'triple' '=' STRINGCONSTANT
249/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000252 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000253 switch (Lex.Lex()) {
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
256 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000259 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000260 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000261 return false;
262 case lltok::kw_datalayout:
263 Lex.Lex();
Lang Hames5fa792e2011-10-17 23:24:48 +0000264 LocTy SpecifierLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000265 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
266 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 return true;
Lang Hames5fa792e2011-10-17 23:24:48 +0000268 std::string errMsg = TargetData::parseSpecifier(Str);
269 if (errMsg != "") {
270 return Error(SpecifierLoc, errMsg);
271 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000273 return false;
274 }
275}
276
277/// toplevelentity
278/// ::= 'deplibs' '=' '[' ']'
279/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
280bool LLParser::ParseDepLibs() {
281 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000282 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000283 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285 return true;
286
287 if (EatIfPresent(lltok::rsquare))
288 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000289
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000290 std::string Str;
291 if (ParseStringConstant(Str)) return true;
292 M->addLibrary(Str);
293
294 while (EatIfPresent(lltok::comma)) {
295 if (ParseStringConstant(Str)) return true;
296 M->addLibrary(Str);
297 }
298
299 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000300}
301
Dan Gohman3845e502009-08-12 23:32:33 +0000302/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000303/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000304bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000305 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000306 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000307 Lex.Lex(); // eat LocalVarID;
308
309 if (ParseToken(lltok::equal, "expected '=' after name") ||
310 ParseToken(lltok::kw_type, "expected 'type' after '='"))
311 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000312
Chris Lattner1afcace2011-07-09 17:41:24 +0000313 if (TypeID >= NumberedTypes.size())
314 NumberedTypes.resize(TypeID+1);
315
316 Type *Result = 0;
317 if (ParseStructDefinition(TypeLoc, "",
318 NumberedTypes[TypeID], Result)) return true;
319
320 if (!isa<StructType>(Result)) {
321 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
322 if (Entry.first)
323 return Error(TypeLoc, "non-struct types may not be recursive");
324 Entry.first = Result;
325 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000326 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327
Chris Lattnerdf986172009-01-02 07:01:27 +0000328 return false;
329}
330
Chris Lattner1afcace2011-07-09 17:41:24 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332/// toplevelentity
333/// ::= LocalVar '=' 'type' type
334bool LLParser::ParseNamedType() {
335 std::string Name = Lex.getStrVal();
336 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000337 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000338
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000339 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000340 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000341 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000342
343 Type *Result = 0;
344 if (ParseStructDefinition(NameLoc, Name,
345 NamedTypes[Name], Result)) return true;
346
347 if (!isa<StructType>(Result)) {
348 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
349 if (Entry.first)
350 return Error(NameLoc, "non-struct types may not be recursive");
351 Entry.first = Result;
352 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000353 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000354
355 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000356}
357
358
359/// toplevelentity
360/// ::= 'declare' FunctionHeader
361bool LLParser::ParseDeclare() {
362 assert(Lex.getKind() == lltok::kw_declare);
363 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000364
Chris Lattnerdf986172009-01-02 07:01:27 +0000365 Function *F;
366 return ParseFunctionHeader(F, false);
367}
368
369/// toplevelentity
370/// ::= 'define' FunctionHeader '{' ...
371bool LLParser::ParseDefine() {
372 assert(Lex.getKind() == lltok::kw_define);
373 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000374
Chris Lattnerdf986172009-01-02 07:01:27 +0000375 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000376 return ParseFunctionHeader(F, true) ||
377 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000378}
379
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000380/// ParseGlobalType
381/// ::= 'constant'
382/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000383bool LLParser::ParseGlobalType(bool &IsConstant) {
384 if (Lex.getKind() == lltok::kw_constant)
385 IsConstant = true;
386 else if (Lex.getKind() == lltok::kw_global)
387 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000388 else {
389 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000391 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000392 Lex.Lex();
393 return false;
394}
395
Dan Gohman3845e502009-08-12 23:32:33 +0000396/// ParseUnnamedGlobal:
397/// OptionalVisibility ALIAS ...
398/// OptionalLinkage OptionalVisibility ... -> global variable
399/// GlobalID '=' OptionalVisibility ALIAS ...
400/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
401bool LLParser::ParseUnnamedGlobal() {
402 unsigned VarID = NumberedVals.size();
403 std::string Name;
404 LocTy NameLoc = Lex.getLoc();
405
406 // Handle the GlobalID form.
407 if (Lex.getKind() == lltok::GlobalID) {
408 if (Lex.getUIntVal() != VarID)
409 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000410 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000411 Lex.Lex(); // eat GlobalID;
412
413 if (ParseToken(lltok::equal, "expected '=' after name"))
414 return true;
415 }
416
417 bool HasLinkage;
418 unsigned Linkage, Visibility;
419 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
420 ParseOptionalVisibility(Visibility))
421 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000422
Dan Gohman3845e502009-08-12 23:32:33 +0000423 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
425 return ParseAlias(Name, NameLoc, Visibility);
426}
427
Chris Lattnerdf986172009-01-02 07:01:27 +0000428/// ParseNamedGlobal:
429/// GlobalVar '=' OptionalVisibility ALIAS ...
430/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
431bool LLParser::ParseNamedGlobal() {
432 assert(Lex.getKind() == lltok::GlobalVar);
433 LocTy NameLoc = Lex.getLoc();
434 std::string Name = Lex.getStrVal();
435 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000436
Chris Lattnerdf986172009-01-02 07:01:27 +0000437 bool HasLinkage;
438 unsigned Linkage, Visibility;
439 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
440 ParseOptionalLinkage(Linkage, HasLinkage) ||
441 ParseOptionalVisibility(Visibility))
442 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000443
Chris Lattnerdf986172009-01-02 07:01:27 +0000444 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
445 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
446 return ParseAlias(Name, NameLoc, Visibility);
447}
448
Devang Patel256be962009-07-20 19:00:08 +0000449// MDString:
450// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000451bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000452 std::string Str;
453 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000454 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000455 return false;
456}
457
458// MDNode:
459// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000460//
461/// This version of ParseMDNodeID returns the slot number and null in the case
462/// of a forward reference.
463bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
464 // !{ ..., !42, ... }
465 if (ParseUInt32(SlotNo)) return true;
466
467 // Check existing MDNode.
468 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
469 Result = NumberedMetadata[SlotNo];
470 else
471 Result = 0;
472 return false;
473}
474
Chris Lattner4a72efc2009-12-30 04:15:23 +0000475bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000476 // !{ ..., !42, ... }
477 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000478 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattner449c3102010-04-01 05:14:45 +0000480 // If not a forward reference, just return it now.
481 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000482
Chris Lattner449c3102010-04-01 05:14:45 +0000483 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000484 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000485 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000486
487 if (NumberedMetadata.size() <= MID)
488 NumberedMetadata.resize(MID+1);
489 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000490 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000491 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000492}
Devang Patel256be962009-07-20 19:00:08 +0000493
Chris Lattner84d03b12009-12-29 22:35:39 +0000494/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000495/// !foo = !{ !1, !2 }
496bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000497 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000498 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000499 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000500
Chris Lattner84d03b12009-12-29 22:35:39 +0000501 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000502 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000503 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000504 return true;
505
Dan Gohman17aa92c2010-07-21 23:38:33 +0000506 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000507 if (Lex.getKind() != lltok::rbrace)
508 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000509 if (ParseToken(lltok::exclaim, "Expected '!' here"))
510 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000511
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000512 MDNode *N = 0;
513 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000514 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000515 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000516
517 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
518 return true;
519
Devang Pateleff2ab62009-07-29 00:34:02 +0000520 return false;
521}
522
Devang Patel923078c2009-07-01 19:21:12 +0000523/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000524/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000525bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000526 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000527 Lex.Lex();
528 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000529
530 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000531 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000532 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000533 if (ParseUInt32(MetadataID) ||
534 ParseToken(lltok::equal, "expected '=' here") ||
535 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000536 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000537 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000538 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000539 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000540 return true;
541
Jay Foadec9186b2011-04-21 19:59:31 +0000542 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000543
544 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000545 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000546 FI = ForwardRefMDNodes.find(MetadataID);
547 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000548 MDNode *Temp = FI->second.first;
549 Temp->replaceAllUsesWith(Init);
550 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000551 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000552
553 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
554 } else {
555 if (MetadataID >= NumberedMetadata.size())
556 NumberedMetadata.resize(MetadataID+1);
557
558 if (NumberedMetadata[MetadataID] != 0)
559 return TokError("Metadata id is already used");
560 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000561 }
562
Devang Patel923078c2009-07-01 19:21:12 +0000563 return false;
564}
565
Chris Lattnerdf986172009-01-02 07:01:27 +0000566/// ParseAlias:
567/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
568/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000569/// ::= TypeAndValue
570/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000571/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000572///
573/// Everything through visibility has already been parsed.
574///
575bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
576 unsigned Visibility) {
577 assert(Lex.getKind() == lltok::kw_alias);
578 Lex.Lex();
579 unsigned Linkage;
580 LocTy LinkageLoc = Lex.getLoc();
581 if (ParseOptionalLinkage(Linkage))
582 return true;
583
584 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000585 Linkage != GlobalValue::WeakAnyLinkage &&
586 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000587 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000588 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000589 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000590 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
591 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000592 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000593
Chris Lattnerdf986172009-01-02 07:01:27 +0000594 Constant *Aliasee;
595 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000596 if (Lex.getKind() != lltok::kw_bitcast &&
597 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000598 if (ParseGlobalTypeAndValue(Aliasee)) return true;
599 } else {
600 // The bitcast dest type is not present, it is implied by the dest type.
601 ValID ID;
602 if (ParseValID(ID)) return true;
603 if (ID.Kind != ValID::t_Constant)
604 return Error(AliaseeLoc, "invalid aliasee");
605 Aliasee = ID.ConstantVal;
606 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000607
Duncan Sands1df98592010-02-16 11:11:14 +0000608 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000609 return Error(AliaseeLoc, "alias must have pointer type");
610
611 // Okay, create the alias but do not insert it into the module yet.
612 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
613 (GlobalValue::LinkageTypes)Linkage, Name,
614 Aliasee);
615 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000616
Chris Lattnerdf986172009-01-02 07:01:27 +0000617 // See if this value already exists in the symbol table. If so, it is either
618 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000619 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 // See if this was a redefinition. If so, there is no entry in
621 // ForwardRefVals.
622 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
623 I = ForwardRefVals.find(Name);
624 if (I == ForwardRefVals.end())
625 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
626
627 // Otherwise, this was a definition of forward ref. Verify that types
628 // agree.
629 if (Val->getType() != GA->getType())
630 return Error(NameLoc,
631 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000632
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 // If they agree, just RAUW the old value with the alias and remove the
634 // forward ref info.
635 Val->replaceAllUsesWith(GA);
636 Val->eraseFromParent();
637 ForwardRefVals.erase(I);
638 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000639
Chris Lattnerdf986172009-01-02 07:01:27 +0000640 // Insert into the module, we know its name won't collide now.
641 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000642 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000643
Chris Lattnerdf986172009-01-02 07:01:27 +0000644 return false;
645}
646
647/// ParseGlobal
648/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000649/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000650/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000651/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000652///
653/// Everything through visibility has been parsed already.
654///
655bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
656 unsigned Linkage, bool HasLinkage,
657 unsigned Visibility) {
658 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000659 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000660 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000662
Chris Lattner1afcace2011-07-09 17:41:24 +0000663 Type *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +0000664 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
665 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000666 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
667 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000668 ParseGlobalType(IsConstant) ||
669 ParseType(Ty, TyLoc))
670 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000671
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 // If the linkage is specified and is external, then no initializer is
673 // present.
674 Constant *Init = 0;
675 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000676 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 Linkage != GlobalValue::ExternalLinkage)) {
678 if (ParseGlobalValue(Ty, Init))
679 return true;
680 }
681
Duncan Sands1df98592010-02-16 11:11:14 +0000682 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000683 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 GlobalVariable *GV = 0;
686
687 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000688 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000689 if (GlobalValue *GVal = M->getNamedValue(Name)) {
690 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
691 return Error(NameLoc, "redefinition of global '@" + Name + "'");
692 GV = cast<GlobalVariable>(GVal);
693 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 } else {
695 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
696 I = ForwardRefValIDs.find(NumberedVals.size());
697 if (I != ForwardRefValIDs.end()) {
698 GV = cast<GlobalVariable>(I->second.first);
699 ForwardRefValIDs.erase(I);
700 }
701 }
702
703 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000704 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000705 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 } else {
707 if (GV->getType()->getElementType() != Ty)
708 return Error(TyLoc,
709 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000710
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 // Move the forward-reference to the correct spot in the module.
712 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
713 }
714
715 if (Name.empty())
716 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 // Set the parsed properties on the global.
719 if (Init)
720 GV->setInitializer(Init);
721 GV->setConstant(IsConstant);
722 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
723 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
724 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000725 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000726
Chris Lattnerdf986172009-01-02 07:01:27 +0000727 // Parse attributes on the global.
728 while (Lex.getKind() == lltok::comma) {
729 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000730
Chris Lattnerdf986172009-01-02 07:01:27 +0000731 if (Lex.getKind() == lltok::kw_section) {
732 Lex.Lex();
733 GV->setSection(Lex.getStrVal());
734 if (ParseToken(lltok::StringConstant, "expected global section string"))
735 return true;
736 } else if (Lex.getKind() == lltok::kw_align) {
737 unsigned Alignment;
738 if (ParseOptionalAlignment(Alignment)) return true;
739 GV->setAlignment(Alignment);
740 } else {
741 TokError("unknown global variable property!");
742 }
743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 return false;
746}
747
748
749//===----------------------------------------------------------------------===//
750// GlobalValue Reference/Resolution Routines.
751//===----------------------------------------------------------------------===//
752
753/// GetGlobalVal - Get a value with the specified name or ID, creating a
754/// forward reference record if needed. This can return null if the value
755/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000756GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000757 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000758 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 if (PTy == 0) {
760 Error(Loc, "global variable reference must have pointer type");
761 return 0;
762 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 // Look this name up in the normal function symbol table.
765 GlobalValue *Val =
766 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000767
Chris Lattnerdf986172009-01-02 07:01:27 +0000768 // If this is a forward reference for the value, see if we already created a
769 // forward ref record.
770 if (Val == 0) {
771 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
772 I = ForwardRefVals.find(Name);
773 if (I != ForwardRefVals.end())
774 Val = I->second.first;
775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 // If we have the value in the symbol table or fwd-ref table, return it.
778 if (Val) {
779 if (Val->getType() == Ty) return Val;
780 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000781 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000782 return 0;
783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 // Otherwise, create a new forward reference for this value and remember it.
786 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000787 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000788 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000789 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000790 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
791 GlobalValue::ExternalWeakLinkage, 0, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Chris Lattnerdf986172009-01-02 07:01:27 +0000793 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
794 return FwdVal;
795}
796
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000797GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
798 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 if (PTy == 0) {
800 Error(Loc, "global variable reference must have pointer type");
801 return 0;
802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000803
Chris Lattnerdf986172009-01-02 07:01:27 +0000804 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Chris Lattnerdf986172009-01-02 07:01:27 +0000806 // If this is a forward reference for the value, see if we already created a
807 // forward ref record.
808 if (Val == 0) {
809 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
810 I = ForwardRefValIDs.find(ID);
811 if (I != ForwardRefValIDs.end())
812 Val = I->second.first;
813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000814
Chris Lattnerdf986172009-01-02 07:01:27 +0000815 // If we have the value in the symbol table or fwd-ref table, return it.
816 if (Val) {
817 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000818 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000819 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000820 return 0;
821 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000822
Chris Lattnerdf986172009-01-02 07:01:27 +0000823 // Otherwise, create a new forward reference for this value and remember it.
824 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000825 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000826 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000827 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000828 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
829 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Chris Lattnerdf986172009-01-02 07:01:27 +0000831 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
832 return FwdVal;
833}
834
835
836//===----------------------------------------------------------------------===//
837// Helper Routines.
838//===----------------------------------------------------------------------===//
839
840/// ParseToken - If the current token has the specified kind, eat it and return
841/// success. Otherwise, emit the specified error and return failure.
842bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
843 if (Lex.getKind() != T)
844 return TokError(ErrMsg);
845 Lex.Lex();
846 return false;
847}
848
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000849/// ParseStringConstant
850/// ::= StringConstant
851bool LLParser::ParseStringConstant(std::string &Result) {
852 if (Lex.getKind() != lltok::StringConstant)
853 return TokError("expected string constant");
854 Result = Lex.getStrVal();
855 Lex.Lex();
856 return false;
857}
858
859/// ParseUInt32
860/// ::= uint32
861bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000862 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
863 return TokError("expected integer");
864 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
865 if (Val64 != unsigned(Val64))
866 return TokError("expected 32-bit integer (too large)");
867 Val = Val64;
868 Lex.Lex();
869 return false;
870}
871
872
873/// ParseOptionalAddrSpace
874/// := /*empty*/
875/// := 'addrspace' '(' uint32 ')'
876bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
877 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000878 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000880 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000881 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000882 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000883}
Chris Lattnerdf986172009-01-02 07:01:27 +0000884
885/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
886/// indicates what kind of attribute list this is: 0: function arg, 1: result,
887/// 2: function attr.
888bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
889 Attrs = Attribute::None;
890 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000891
Chris Lattnerdf986172009-01-02 07:01:27 +0000892 while (1) {
893 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000894 default: // End of attributes.
895 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
896 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000897
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000898 // As a hack, we allow "align 2" on functions as a synonym for
899 // "alignstack 2".
900 if (AttrKind == 2 &&
901 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
902 return Error(AttrLoc, "invalid use of attribute on a function");
903
904 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000905 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000906
Chris Lattnerdf986172009-01-02 07:01:27 +0000907 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000908 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
909 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
910 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
911 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
912 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
913 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
914 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
915 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000916
Devang Patel578efa92009-06-05 21:57:13 +0000917 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
918 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000919 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Rafael Espindola25456ef2011-10-03 14:45:37 +0000920 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
Devang Patel578efa92009-06-05 21:57:13 +0000921 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
922 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
923 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000924 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000925 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
926 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
927 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
928 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
929 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
930 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000931 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
John McCall3a3465b2011-06-15 20:36:13 +0000932 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000933
Charles Davis1e063d12010-02-12 00:31:15 +0000934 case lltok::kw_alignstack: {
935 unsigned Alignment;
936 if (ParseOptionalStackAlignment(Alignment))
937 return true;
938 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
939 continue;
940 }
941
Chris Lattnerdf986172009-01-02 07:01:27 +0000942 case lltok::kw_align: {
943 unsigned Alignment;
944 if (ParseOptionalAlignment(Alignment))
945 return true;
946 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
947 continue;
948 }
Charles Davis1e063d12010-02-12 00:31:15 +0000949
Chris Lattnerdf986172009-01-02 07:01:27 +0000950 }
951 Lex.Lex();
952 }
953}
954
955/// ParseOptionalLinkage
956/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000957/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000958/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000959/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000960/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000961/// ::= 'internal'
962/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000963/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000964/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000965/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000966/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000967/// ::= 'appending'
968/// ::= 'dllexport'
969/// ::= 'common'
970/// ::= 'dllimport'
971/// ::= 'extern_weak'
972/// ::= 'external'
973bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
974 HasLinkage = false;
975 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000976 default: Res=GlobalValue::ExternalLinkage; return false;
977 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
978 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000979 case lltok::kw_linker_private_weak:
980 Res = GlobalValue::LinkerPrivateWeakLinkage;
981 break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000982 case lltok::kw_linker_private_weak_def_auto:
983 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
984 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000985 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
986 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
987 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
988 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
989 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000990 case lltok::kw_available_externally:
991 Res = GlobalValue::AvailableExternallyLinkage;
992 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000993 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
994 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
995 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
996 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
997 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
998 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000999 }
1000 Lex.Lex();
1001 HasLinkage = true;
1002 return false;
1003}
1004
1005/// ParseOptionalVisibility
1006/// ::= /*empty*/
1007/// ::= 'default'
1008/// ::= 'hidden'
1009/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001010///
Chris Lattnerdf986172009-01-02 07:01:27 +00001011bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1012 switch (Lex.getKind()) {
1013 default: Res = GlobalValue::DefaultVisibility; return false;
1014 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1015 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1016 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1017 }
1018 Lex.Lex();
1019 return false;
1020}
1021
1022/// ParseOptionalCallingConv
1023/// ::= /*empty*/
1024/// ::= 'ccc'
1025/// ::= 'fastcc'
1026/// ::= 'coldcc'
1027/// ::= 'x86_stdcallcc'
1028/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001029/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001030/// ::= 'arm_apcscc'
1031/// ::= 'arm_aapcscc'
1032/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001033/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001034/// ::= 'ptx_kernel'
1035/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001036/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001037///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001038bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001039 switch (Lex.getKind()) {
1040 default: CC = CallingConv::C; return false;
1041 case lltok::kw_ccc: CC = CallingConv::C; break;
1042 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1043 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1044 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1045 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001046 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001047 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1048 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1049 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001050 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001051 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1052 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001053 case lltok::kw_cc: {
1054 unsigned ArbitraryCC;
1055 Lex.Lex();
1056 if (ParseUInt32(ArbitraryCC)) {
1057 return true;
1058 } else
1059 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1060 return false;
1061 }
1062 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001063 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001064
Chris Lattnerdf986172009-01-02 07:01:27 +00001065 Lex.Lex();
1066 return false;
1067}
1068
Chris Lattnerb8c46862009-12-30 05:31:19 +00001069/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001070/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001071bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1072 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001073 do {
1074 if (Lex.getKind() != lltok::MetadataVar)
1075 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001076
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001077 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001078 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001079 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001080
Chris Lattner442ffa12009-12-29 21:53:55 +00001081 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001082 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001083
1084 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001085 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001086
Dan Gohman68261142010-08-24 14:35:45 +00001087 // This code is similar to that of ParseMetadataValue, however it needs to
1088 // have special-case code for a forward reference; see the comments on
1089 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1090 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001091 if (Lex.getKind() == lltok::lbrace) {
1092 ValID ID;
1093 if (ParseMetadataListValue(ID, PFS))
1094 return true;
1095 assert(ID.Kind == ValID::t_MDNode);
1096 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001097 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001098 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001099 if (ParseMDNodeID(Node, NodeID))
1100 return true;
1101 if (Node) {
1102 // If we got the node, add it to the instruction.
1103 Inst->setMetadata(MDK, Node);
1104 } else {
1105 MDRef R = { Loc, MDK, NodeID };
1106 // Otherwise, remember that this should be resolved later.
1107 ForwardRefInstMetadata[Inst].push_back(R);
1108 }
Chris Lattner449c3102010-04-01 05:14:45 +00001109 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001110
1111 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001112 } while (EatIfPresent(lltok::comma));
1113 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001114}
1115
Chris Lattnerdf986172009-01-02 07:01:27 +00001116/// ParseOptionalAlignment
1117/// ::= /* empty */
1118/// ::= 'align' 4
1119bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1120 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001121 if (!EatIfPresent(lltok::kw_align))
1122 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001123 LocTy AlignLoc = Lex.getLoc();
1124 if (ParseUInt32(Alignment)) return true;
1125 if (!isPowerOf2_32(Alignment))
1126 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001127 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001128 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001129 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001130}
1131
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001132/// ParseOptionalCommaAlign
1133/// ::=
1134/// ::= ',' align 4
1135///
1136/// This returns with AteExtraComma set to true if it ate an excess comma at the
1137/// end.
1138bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1139 bool &AteExtraComma) {
1140 AteExtraComma = false;
1141 while (EatIfPresent(lltok::comma)) {
1142 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001143 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001144 AteExtraComma = true;
1145 return false;
1146 }
1147
Chris Lattner093eed12010-04-23 00:50:50 +00001148 if (Lex.getKind() != lltok::kw_align)
1149 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001150
Chris Lattner093eed12010-04-23 00:50:50 +00001151 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001152 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001153
Devang Patelf633a062009-09-17 23:04:48 +00001154 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001155}
1156
Eli Friedman47f35132011-07-25 23:16:38 +00001157/// ParseScopeAndOrdering
1158/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1159/// else: ::=
1160///
1161/// This sets Scope and Ordering to the parsed values.
1162bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1163 AtomicOrdering &Ordering) {
1164 if (!isAtomic)
1165 return false;
1166
1167 Scope = CrossThread;
1168 if (EatIfPresent(lltok::kw_singlethread))
1169 Scope = SingleThread;
1170 switch (Lex.getKind()) {
1171 default: return TokError("Expected ordering on atomic instruction");
1172 case lltok::kw_unordered: Ordering = Unordered; break;
1173 case lltok::kw_monotonic: Ordering = Monotonic; break;
1174 case lltok::kw_acquire: Ordering = Acquire; break;
1175 case lltok::kw_release: Ordering = Release; break;
1176 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1177 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1178 }
1179 Lex.Lex();
1180 return false;
1181}
1182
Charles Davis1e063d12010-02-12 00:31:15 +00001183/// ParseOptionalStackAlignment
1184/// ::= /* empty */
1185/// ::= 'alignstack' '(' 4 ')'
1186bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1187 Alignment = 0;
1188 if (!EatIfPresent(lltok::kw_alignstack))
1189 return false;
1190 LocTy ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::lparen))
1192 return Error(ParenLoc, "expected '('");
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::rparen))
1197 return Error(ParenLoc, "expected ')'");
1198 if (!isPowerOf2_32(Alignment))
1199 return Error(AlignLoc, "stack alignment is not a power of two");
1200 return false;
1201}
Devang Patelf633a062009-09-17 23:04:48 +00001202
Chris Lattner628c13a2009-12-30 05:14:00 +00001203/// ParseIndexList - This parses the index list for an insert/extractvalue
1204/// instruction. This sets AteExtraComma in the case where we eat an extra
1205/// comma at the end of the line and find that it is followed by metadata.
1206/// Clients that don't allow metadata can call the version of this function that
1207/// only takes one argument.
1208///
Chris Lattnerdf986172009-01-02 07:01:27 +00001209/// ParseIndexList
1210/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001211///
1212bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1213 bool &AteExtraComma) {
1214 AteExtraComma = false;
1215
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 if (Lex.getKind() != lltok::comma)
1217 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001218
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001219 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1222 return false;
1223 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001224 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001225 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001226 Indices.push_back(Idx);
1227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001228
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 return false;
1230}
1231
1232//===----------------------------------------------------------------------===//
1233// Type Parsing.
1234//===----------------------------------------------------------------------===//
1235
Chris Lattner1afcace2011-07-09 17:41:24 +00001236/// ParseType - Parse a type.
1237bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1238 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 switch (Lex.getKind()) {
1240 default:
1241 return TokError("expected type");
1242 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001243 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001245 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001248 // Type ::= StructType
1249 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 return true;
1251 break;
1252 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001253 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 Lex.Lex(); // eat the lsquare.
1255 if (ParseArrayVectorType(Result, false))
1256 return true;
1257 break;
1258 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001259 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001260 Lex.Lex();
1261 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001262 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001263 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001264 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 } else if (ParseArrayVectorType(Result, true))
1266 return true;
1267 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001268 case lltok::LocalVar: {
1269 // Type ::= %foo
1270 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1271
1272 // If the type hasn't been defined yet, create a forward definition and
1273 // remember where that forward def'n was seen (in case it never is defined).
1274 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001275 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001276 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001277 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001278 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001279 Lex.Lex();
1280 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001281 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001282
Chris Lattner1afcace2011-07-09 17:41:24 +00001283 case lltok::LocalVarID: {
1284 // Type ::= %4
1285 if (Lex.getUIntVal() >= NumberedTypes.size())
1286 NumberedTypes.resize(Lex.getUIntVal()+1);
1287 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1288
1289 // If the type hasn't been defined yet, create a forward definition and
1290 // remember where that forward def'n was seen (in case it never is defined).
1291 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001292 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001293 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001295 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 Lex.Lex();
1297 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 }
1299 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001300
1301 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 while (1) {
1303 switch (Lex.getKind()) {
1304 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001305 default:
1306 if (!AllowVoid && Result->isVoidTy())
1307 return Error(TypeLoc, "void type only allowed for function results");
1308 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001309
Chris Lattner1afcace2011-07-09 17:41:24 +00001310 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001312 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001314 if (Result->isVoidTy())
1315 return TokError("pointers to void are invalid - use i8* instead");
1316 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001317 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001318 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 Lex.Lex();
1320 break;
1321
Chris Lattner1afcace2011-07-09 17:41:24 +00001322 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001323 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001324 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001325 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001326 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001327 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001328 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001329 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 unsigned AddrSpace;
1331 if (ParseOptionalAddrSpace(AddrSpace) ||
1332 ParseToken(lltok::star, "expected '*' in address space"))
1333 return true;
1334
Chris Lattner1afcace2011-07-09 17:41:24 +00001335 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001336 break;
1337 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001338
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1340 case lltok::lparen:
1341 if (ParseFunctionType(Result))
1342 return true;
1343 break;
1344 }
1345 }
1346}
1347
1348/// ParseParameterList
1349/// ::= '(' ')'
1350/// ::= '(' Arg (',' Arg)* ')'
1351/// Arg
1352/// ::= Type OptionalAttributes Value OptionalAttributes
1353bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1354 PerFunctionState &PFS) {
1355 if (ParseToken(lltok::lparen, "expected '(' in call"))
1356 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001357
Chris Lattnerdf986172009-01-02 07:01:27 +00001358 while (Lex.getKind() != lltok::rparen) {
1359 // If this isn't the first argument, we need a comma.
1360 if (!ArgList.empty() &&
1361 ParseToken(lltok::comma, "expected ',' in argument list"))
1362 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001363
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 // Parse the argument.
1365 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001366 Type *ArgTy = 0;
Victor Hernandez19715562009-12-03 23:40:58 +00001367 unsigned ArgAttrs1 = Attribute::None;
1368 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001369 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001370 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001372
Chris Lattner287881d2009-12-30 02:11:14 +00001373 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001374 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001375 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1377 }
1378
1379 Lex.Lex(); // Lex the ')'.
1380 return false;
1381}
1382
1383
1384
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001385/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001386/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001387/// ::= '(' ArgTypeListI ')'
1388/// ArgTypeListI
1389/// ::= /*empty*/
1390/// ::= '...'
1391/// ::= ArgTypeList ',' '...'
1392/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001393///
Chris Lattner1afcace2011-07-09 17:41:24 +00001394bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1395 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 isVarArg = false;
1397 assert(Lex.getKind() == lltok::lparen);
1398 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 if (Lex.getKind() == lltok::rparen) {
1401 // empty
1402 } else if (Lex.getKind() == lltok::dotdotdot) {
1403 isVarArg = true;
1404 Lex.Lex();
1405 } else {
1406 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001407 Type *ArgTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001409 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410
Chris Lattner1afcace2011-07-09 17:41:24 +00001411 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001412 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001413
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001414 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001415 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001416
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001417 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 Name = Lex.getStrVal();
1419 Lex.Lex();
1420 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001421
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001422 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001423 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001424
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001426
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001427 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001429 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001430 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001431 break;
1432 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001433
Chris Lattnerdf986172009-01-02 07:01:27 +00001434 // Otherwise must be an argument type.
1435 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001436 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001437
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001438 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001439 return Error(TypeLoc, "argument can not have void type");
1440
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001441 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 Name = Lex.getStrVal();
1443 Lex.Lex();
1444 } else {
1445 Name = "";
1446 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001447
Chris Lattner1afcace2011-07-09 17:41:24 +00001448 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001449 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001450
Chris Lattnerdf986172009-01-02 07:01:27 +00001451 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1452 }
1453 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001454
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001455 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001456}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001457
Chris Lattnerdf986172009-01-02 07:01:27 +00001458/// ParseFunctionType
1459/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001460bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001461 assert(Lex.getKind() == lltok::lparen);
1462
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001463 if (!FunctionType::isValidReturnType(Result))
1464 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001465
Chris Lattner1afcace2011-07-09 17:41:24 +00001466 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001467 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001468 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001469 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001470
Chris Lattnerdf986172009-01-02 07:01:27 +00001471 // Reject names on the arguments lists.
1472 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1473 if (!ArgList[i].Name.empty())
1474 return Error(ArgList[i].Loc, "argument name invalid in function type");
Chris Lattnera16546a2011-06-17 17:37:13 +00001475 if (ArgList[i].Attrs != 0)
1476 return Error(ArgList[i].Loc,
1477 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001478 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Jay Foad5fdd6c82011-07-12 14:06:48 +00001480 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001481 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001482 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001483
Chris Lattner1afcace2011-07-09 17:41:24 +00001484 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001485 return false;
1486}
1487
Chris Lattner1afcace2011-07-09 17:41:24 +00001488/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1489/// other structs.
1490bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1491 SmallVector<Type*, 8> Elts;
1492 if (ParseStructBody(Elts)) return true;
1493
1494 Result = StructType::get(Context, Elts, Packed);
1495 return false;
1496}
1497
1498/// ParseStructDefinition - Parse a struct in a 'type' definition.
1499bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1500 std::pair<Type*, LocTy> &Entry,
1501 Type *&ResultTy) {
1502 // If the type was already defined, diagnose the redefinition.
1503 if (Entry.first && !Entry.second.isValid())
1504 return Error(TypeLoc, "redefinition of type");
1505
1506 // If we have opaque, just return without filling in the definition for the
1507 // struct. This counts as a definition as far as the .ll file goes.
1508 if (EatIfPresent(lltok::kw_opaque)) {
1509 // This type is being defined, so clear the location to indicate this.
1510 Entry.second = SMLoc();
1511
1512 // If this type number has never been uttered, create it.
1513 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001514 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001515 ResultTy = Entry.first;
1516 return false;
1517 }
1518
1519 // If the type starts with '<', then it is either a packed struct or a vector.
1520 bool isPacked = EatIfPresent(lltok::less);
1521
1522 // If we don't have a struct, then we have a random type alias, which we
1523 // accept for compatibility with old files. These types are not allowed to be
1524 // forward referenced and not allowed to be recursive.
1525 if (Lex.getKind() != lltok::lbrace) {
1526 if (Entry.first)
1527 return Error(TypeLoc, "forward references to non-struct type");
1528
1529 ResultTy = 0;
1530 if (isPacked)
1531 return ParseArrayVectorType(ResultTy, true);
1532 return ParseType(ResultTy);
1533 }
1534
1535 // This type is being defined, so clear the location to indicate this.
1536 Entry.second = SMLoc();
1537
1538 // If this type number has never been uttered, create it.
1539 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001540 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001541
1542 StructType *STy = cast<StructType>(Entry.first);
1543
1544 SmallVector<Type*, 8> Body;
1545 if (ParseStructBody(Body) ||
1546 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1547 return true;
1548
1549 STy->setBody(Body, isPacked);
1550 ResultTy = STy;
1551 return false;
1552}
1553
1554
Chris Lattnerdf986172009-01-02 07:01:27 +00001555/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001556/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001557/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001558/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001559/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001560/// ::= '<' '{' Type (',' Type)* '}' '>'
1561bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 assert(Lex.getKind() == lltok::lbrace);
1563 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattner1afcace2011-07-09 17:41:24 +00001565 // Handle the empty struct.
1566 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001567 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001568
Chris Lattnera9a9e072009-03-09 04:49:14 +00001569 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001570 Type *Ty = 0;
1571 if (ParseType(Ty)) return true;
1572 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001573
Chris Lattner1afcace2011-07-09 17:41:24 +00001574 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001575 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001577 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001578 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001579 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001580
Chris Lattner1afcace2011-07-09 17:41:24 +00001581 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001582 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Chris Lattner1afcace2011-07-09 17:41:24 +00001584 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001585 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattner1afcace2011-07-09 17:41:24 +00001587 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001588}
1589
1590/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1591/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001592/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001593/// ::= '[' APSINTVAL 'x' Types ']'
1594/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001595bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001596 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1597 Lex.getAPSIntVal().getBitWidth() > 64)
1598 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001599
Chris Lattnerdf986172009-01-02 07:01:27 +00001600 LocTy SizeLoc = Lex.getLoc();
1601 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001602 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001603
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001604 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1605 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001606
1607 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001608 Type *EltTy = 0;
1609 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001610
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001611 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1612 "expected end of sequential type"))
1613 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001614
Chris Lattnerdf986172009-01-02 07:01:27 +00001615 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001616 if (Size == 0)
1617 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001618 if ((unsigned)Size != Size)
1619 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001620 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001621 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001622 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001624 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001626 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001627 }
1628 return false;
1629}
1630
1631//===----------------------------------------------------------------------===//
1632// Function Semantic Analysis.
1633//===----------------------------------------------------------------------===//
1634
Chris Lattner09d9ef42009-10-28 03:39:23 +00001635LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1636 int functionNumber)
1637 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001638
1639 // Insert unnamed arguments into the NumberedVals list.
1640 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1641 AI != E; ++AI)
1642 if (!AI->hasName())
1643 NumberedVals.push_back(AI);
1644}
1645
1646LLParser::PerFunctionState::~PerFunctionState() {
1647 // If there were any forward referenced non-basicblock values, delete them.
1648 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1649 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1650 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001651 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001652 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 delete I->second.first;
1654 I->second.first = 0;
1655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1658 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1659 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001660 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001661 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001662 delete I->second.first;
1663 I->second.first = 0;
1664 }
1665}
1666
Chris Lattner09d9ef42009-10-28 03:39:23 +00001667bool LLParser::PerFunctionState::FinishFunction() {
1668 // Check to see if someone took the address of labels in this block.
1669 if (!P.ForwardRefBlockAddresses.empty()) {
1670 ValID FunctionID;
1671 if (!F.getName().empty()) {
1672 FunctionID.Kind = ValID::t_GlobalName;
1673 FunctionID.StrVal = F.getName();
1674 } else {
1675 FunctionID.Kind = ValID::t_GlobalID;
1676 FunctionID.UIntVal = FunctionNumber;
1677 }
1678
1679 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1680 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1681 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1682 // Resolve all these references.
1683 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1684 return true;
1685
1686 P.ForwardRefBlockAddresses.erase(FRBAI);
1687 }
1688 }
1689
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 if (!ForwardRefVals.empty())
1691 return P.Error(ForwardRefVals.begin()->second.second,
1692 "use of undefined value '%" + ForwardRefVals.begin()->first +
1693 "'");
1694 if (!ForwardRefValIDs.empty())
1695 return P.Error(ForwardRefValIDs.begin()->second.second,
1696 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001697 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001698 return false;
1699}
1700
1701
1702/// GetVal - Get a value with the specified name or ID, creating a
1703/// forward reference record if needed. This can return null if the value
1704/// exists but does not have the right type.
1705Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001706 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001707 // Look this name up in the normal function symbol table.
1708 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 // If this is a forward reference for the value, see if we already created a
1711 // forward ref record.
1712 if (Val == 0) {
1713 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1714 I = ForwardRefVals.find(Name);
1715 if (I != ForwardRefVals.end())
1716 Val = I->second.first;
1717 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001718
Chris Lattnerdf986172009-01-02 07:01:27 +00001719 // If we have the value in the symbol table or fwd-ref table, return it.
1720 if (Val) {
1721 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001722 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 P.Error(Loc, "'%" + Name + "' is not a basic block");
1724 else
1725 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001726 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001727 return 0;
1728 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001729
Chris Lattnerdf986172009-01-02 07:01:27 +00001730 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001731 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 P.Error(Loc, "invalid use of a non-first-class type");
1733 return 0;
1734 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001735
Chris Lattnerdf986172009-01-02 07:01:27 +00001736 // Otherwise, create a new forward reference for this value and remember it.
1737 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001738 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001739 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001740 else
1741 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1744 return FwdVal;
1745}
1746
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001747Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001748 LocTy Loc) {
1749 // Look this name up in the normal function symbol table.
1750 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 // If this is a forward reference for the value, see if we already created a
1753 // forward ref record.
1754 if (Val == 0) {
1755 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1756 I = ForwardRefValIDs.find(ID);
1757 if (I != ForwardRefValIDs.end())
1758 Val = I->second.first;
1759 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001760
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 // If we have the value in the symbol table or fwd-ref table, return it.
1762 if (Val) {
1763 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001764 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001765 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001766 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001767 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001768 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 return 0;
1770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001771
Chris Lattner1afcace2011-07-09 17:41:24 +00001772 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001773 P.Error(Loc, "invalid use of a non-first-class type");
1774 return 0;
1775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001776
Chris Lattnerdf986172009-01-02 07:01:27 +00001777 // Otherwise, create a new forward reference for this value and remember it.
1778 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001779 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001780 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 else
1782 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001783
Chris Lattnerdf986172009-01-02 07:01:27 +00001784 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1785 return FwdVal;
1786}
1787
1788/// SetInstName - After an instruction is parsed and inserted into its
1789/// basic block, this installs its name.
1790bool LLParser::PerFunctionState::SetInstName(int NameID,
1791 const std::string &NameStr,
1792 LocTy NameLoc, Instruction *Inst) {
1793 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001794 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001795 if (NameID != -1 || !NameStr.empty())
1796 return P.Error(NameLoc, "instructions returning void cannot have a name");
1797 return false;
1798 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001799
Chris Lattnerdf986172009-01-02 07:01:27 +00001800 // If this was a numbered instruction, verify that the instruction is the
1801 // expected value and resolve any forward references.
1802 if (NameStr.empty()) {
1803 // If neither a name nor an ID was specified, just use the next ID.
1804 if (NameID == -1)
1805 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 if (unsigned(NameID) != NumberedVals.size())
1808 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001809 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001810
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1812 ForwardRefValIDs.find(NameID);
1813 if (FI != ForwardRefValIDs.end()) {
1814 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001816 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001818 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 ForwardRefValIDs.erase(FI);
1820 }
1821
1822 NumberedVals.push_back(Inst);
1823 return false;
1824 }
1825
1826 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1827 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1828 FI = ForwardRefVals.find(NameStr);
1829 if (FI != ForwardRefVals.end()) {
1830 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001832 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001834 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001835 ForwardRefVals.erase(FI);
1836 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001837
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 // Set the name on the instruction.
1839 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001840
Benjamin Krameraf812352010-10-16 11:28:23 +00001841 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001843 NameStr + "'");
1844 return false;
1845}
1846
1847/// GetBB - Get a basic block with the specified name or ID, creating a
1848/// forward reference record if needed.
1849BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1850 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001851 return cast_or_null<BasicBlock>(GetVal(Name,
1852 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001853}
1854
1855BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001856 return cast_or_null<BasicBlock>(GetVal(ID,
1857 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001858}
1859
1860/// DefineBB - Define the specified basic block, which is either named or
1861/// unnamed. If there is an error, this returns null otherwise it returns
1862/// the block being defined.
1863BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1864 LocTy Loc) {
1865 BasicBlock *BB;
1866 if (Name.empty())
1867 BB = GetBB(NumberedVals.size(), Loc);
1868 else
1869 BB = GetBB(Name, Loc);
1870 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 // Move the block to the end of the function. Forward ref'd blocks are
1873 // inserted wherever they happen to be referenced.
1874 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001875
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 // Remove the block from forward ref sets.
1877 if (Name.empty()) {
1878 ForwardRefValIDs.erase(NumberedVals.size());
1879 NumberedVals.push_back(BB);
1880 } else {
1881 // BB forward references are already in the function symbol table.
1882 ForwardRefVals.erase(Name);
1883 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001884
Chris Lattnerdf986172009-01-02 07:01:27 +00001885 return BB;
1886}
1887
1888//===----------------------------------------------------------------------===//
1889// Constants.
1890//===----------------------------------------------------------------------===//
1891
1892/// ParseValID - Parse an abstract value that doesn't necessarily have a
1893/// type implied. For example, if we parse "4" we don't know what integer type
1894/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001895/// sanity. PFS is used to convert function-local operands of metadata (since
1896/// metadata operands are not just parsed here but also converted to values).
1897/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001898bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001899 ID.Loc = Lex.getLoc();
1900 switch (Lex.getKind()) {
1901 default: return TokError("expected value token");
1902 case lltok::GlobalID: // @42
1903 ID.UIntVal = Lex.getUIntVal();
1904 ID.Kind = ValID::t_GlobalID;
1905 break;
1906 case lltok::GlobalVar: // @foo
1907 ID.StrVal = Lex.getStrVal();
1908 ID.Kind = ValID::t_GlobalName;
1909 break;
1910 case lltok::LocalVarID: // %42
1911 ID.UIntVal = Lex.getUIntVal();
1912 ID.Kind = ValID::t_LocalID;
1913 break;
1914 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001915 ID.StrVal = Lex.getStrVal();
1916 ID.Kind = ValID::t_LocalName;
1917 break;
Dan Gohman83448032010-07-14 18:26:50 +00001918 case lltok::exclaim: // !42, !{...}, or !"foo"
1919 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001920 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 ID.Kind = ValID::t_APSInt;
1923 break;
1924 case lltok::APFloat:
1925 ID.APFloatVal = Lex.getAPFloatVal();
1926 ID.Kind = ValID::t_APFloat;
1927 break;
1928 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001929 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001930 ID.Kind = ValID::t_Constant;
1931 break;
1932 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001933 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001934 ID.Kind = ValID::t_Constant;
1935 break;
1936 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1937 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1938 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 case lltok::lbrace: {
1941 // ValID ::= '{' ConstVector '}'
1942 Lex.Lex();
1943 SmallVector<Constant*, 16> Elts;
1944 if (ParseGlobalValueVector(Elts) ||
1945 ParseToken(lltok::rbrace, "expected end of struct constant"))
1946 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947
Chris Lattner1afcace2011-07-09 17:41:24 +00001948 ID.ConstantStructElts = new Constant*[Elts.size()];
1949 ID.UIntVal = Elts.size();
1950 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1951 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 return false;
1953 }
1954 case lltok::less: {
1955 // ValID ::= '<' ConstVector '>' --> Vector.
1956 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1957 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001958 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 SmallVector<Constant*, 16> Elts;
1961 LocTy FirstEltLoc = Lex.getLoc();
1962 if (ParseGlobalValueVector(Elts) ||
1963 (isPackedStruct &&
1964 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1965 ParseToken(lltok::greater, "expected end of constant"))
1966 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001967
Chris Lattnerdf986172009-01-02 07:01:27 +00001968 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001969 ID.ConstantStructElts = new Constant*[Elts.size()];
1970 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1971 ID.UIntVal = Elts.size();
1972 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 return false;
1974 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001975
Chris Lattnerdf986172009-01-02 07:01:27 +00001976 if (Elts.empty())
1977 return Error(ID.Loc, "constant vector must not be empty");
1978
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001979 if (!Elts[0]->getType()->isIntegerTy() &&
1980 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001981 return Error(FirstEltLoc,
1982 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001983
Chris Lattnerdf986172009-01-02 07:01:27 +00001984 // Verify that all the vector elements have the same type.
1985 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1986 if (Elts[i]->getType() != Elts[0]->getType())
1987 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001988 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001989 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Chris Lattner2ca5c862011-02-15 00:14:00 +00001991 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00001992 ID.Kind = ValID::t_Constant;
1993 return false;
1994 }
1995 case lltok::lsquare: { // Array Constant
1996 Lex.Lex();
1997 SmallVector<Constant*, 16> Elts;
1998 LocTy FirstEltLoc = Lex.getLoc();
1999 if (ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rsquare, "expected end of array constant"))
2001 return true;
2002
2003 // Handle empty element.
2004 if (Elts.empty()) {
2005 // Use undef instead of an array because it's inconvenient to determine
2006 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002007 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 return false;
2009 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002012 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002013 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002014
Owen Andersondebcb012009-07-29 22:17:13 +00002015 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002018 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 if (Elts[i]->getType() != Elts[0]->getType())
2020 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002021 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002022 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Jay Foad26701082011-06-22 09:24:39 +00002025 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002026 ID.Kind = ValID::t_Constant;
2027 return false;
2028 }
2029 case lltok::kw_c: // c "foo"
2030 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002031 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2033 ID.Kind = ValID::t_Constant;
2034 return false;
2035
2036 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002037 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2038 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 Lex.Lex();
2040 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002041 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002042 ParseStringConstant(ID.StrVal) ||
2043 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 ParseToken(lltok::StringConstant, "expected constraint string"))
2045 return true;
2046 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002047 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 ID.Kind = ValID::t_InlineAsm;
2049 return false;
2050 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Chris Lattner09d9ef42009-10-28 03:39:23 +00002052 case lltok::kw_blockaddress: {
2053 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2054 Lex.Lex();
2055
2056 ValID Fn, Label;
2057 LocTy FnLoc, LabelLoc;
2058
2059 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2060 ParseValID(Fn) ||
2061 ParseToken(lltok::comma, "expected comma in block address expression")||
2062 ParseValID(Label) ||
2063 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2064 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002065
Chris Lattner09d9ef42009-10-28 03:39:23 +00002066 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2067 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002068 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002069 return Error(Label.Loc, "expected basic block name in blockaddress");
2070
2071 // Make a global variable as a placeholder for this reference.
2072 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2073 false, GlobalValue::InternalLinkage,
2074 0, "");
2075 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2076 ID.ConstantVal = FwdRef;
2077 ID.Kind = ValID::t_Constant;
2078 return false;
2079 }
2080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 case lltok::kw_trunc:
2082 case lltok::kw_zext:
2083 case lltok::kw_sext:
2084 case lltok::kw_fptrunc:
2085 case lltok::kw_fpext:
2086 case lltok::kw_bitcast:
2087 case lltok::kw_uitofp:
2088 case lltok::kw_sitofp:
2089 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002090 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002094 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 Constant *SrcVal;
2096 Lex.Lex();
2097 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2098 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002099 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 ParseType(DestTy) ||
2101 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2102 return true;
2103 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2104 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002105 getTypeString(SrcVal->getType()) + "' to '" +
2106 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002108 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002109 ID.Kind = ValID::t_Constant;
2110 return false;
2111 }
2112 case lltok::kw_extractvalue: {
2113 Lex.Lex();
2114 Constant *Val;
2115 SmallVector<unsigned, 4> Indices;
2116 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2117 ParseGlobalTypeAndValue(Val) ||
2118 ParseIndexList(Indices) ||
2119 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2120 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002121
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002122 if (!Val->getType()->isAggregateType())
2123 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002124 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002126 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002127 ID.Kind = ValID::t_Constant;
2128 return false;
2129 }
2130 case lltok::kw_insertvalue: {
2131 Lex.Lex();
2132 Constant *Val0, *Val1;
2133 SmallVector<unsigned, 4> Indices;
2134 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2135 ParseGlobalTypeAndValue(Val0) ||
2136 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2137 ParseGlobalTypeAndValue(Val1) ||
2138 ParseIndexList(Indices) ||
2139 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2140 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002141 if (!Val0->getType()->isAggregateType())
2142 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002143 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002145 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 ID.Kind = ValID::t_Constant;
2147 return false;
2148 }
2149 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002150 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 unsigned PredVal, Opc = Lex.getUIntVal();
2152 Constant *Val0, *Val1;
2153 Lex.Lex();
2154 if (ParseCmpPredicate(PredVal, Opc) ||
2155 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2156 ParseGlobalTypeAndValue(Val0) ||
2157 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2158 ParseGlobalTypeAndValue(Val1) ||
2159 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2160 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002161
Chris Lattnerdf986172009-01-02 07:01:27 +00002162 if (Val0->getType() != Val1->getType())
2163 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002164
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002166
Chris Lattnerdf986172009-01-02 07:01:27 +00002167 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002168 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002170 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002171 } else {
2172 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002173 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002174 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002176 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 }
2178 ID.Kind = ValID::t_Constant;
2179 return false;
2180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002181
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 // Binary Operators.
2183 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002184 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002186 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002187 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002188 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002189 case lltok::kw_udiv:
2190 case lltok::kw_sdiv:
2191 case lltok::kw_fdiv:
2192 case lltok::kw_urem:
2193 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002194 case lltok::kw_frem:
2195 case lltok::kw_shl:
2196 case lltok::kw_lshr:
2197 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002198 bool NUW = false;
2199 bool NSW = false;
2200 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 unsigned Opc = Lex.getUIntVal();
2202 Constant *Val0, *Val1;
2203 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002204 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002205 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2206 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002207 if (EatIfPresent(lltok::kw_nuw))
2208 NUW = true;
2209 if (EatIfPresent(lltok::kw_nsw)) {
2210 NSW = true;
2211 if (EatIfPresent(lltok::kw_nuw))
2212 NUW = true;
2213 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002214 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2215 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002216 if (EatIfPresent(lltok::kw_exact))
2217 Exact = true;
2218 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002219 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2220 ParseGlobalTypeAndValue(Val0) ||
2221 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2222 ParseGlobalTypeAndValue(Val1) ||
2223 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2224 return true;
2225 if (Val0->getType() != Val1->getType())
2226 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002227 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002228 if (NUW)
2229 return Error(ModifierLoc, "nuw only applies to integer operations");
2230 if (NSW)
2231 return Error(ModifierLoc, "nsw only applies to integer operations");
2232 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002233 // Check that the type is valid for the operator.
2234 switch (Opc) {
2235 case Instruction::Add:
2236 case Instruction::Sub:
2237 case Instruction::Mul:
2238 case Instruction::UDiv:
2239 case Instruction::SDiv:
2240 case Instruction::URem:
2241 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002242 case Instruction::Shl:
2243 case Instruction::AShr:
2244 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002245 if (!Val0->getType()->isIntOrIntVectorTy())
2246 return Error(ID.Loc, "constexpr requires integer operands");
2247 break;
2248 case Instruction::FAdd:
2249 case Instruction::FSub:
2250 case Instruction::FMul:
2251 case Instruction::FDiv:
2252 case Instruction::FRem:
2253 if (!Val0->getType()->isFPOrFPVectorTy())
2254 return Error(ID.Loc, "constexpr requires fp operands");
2255 break;
2256 default: llvm_unreachable("Unknown binary operator!");
2257 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002258 unsigned Flags = 0;
2259 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2260 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002261 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002262 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002263 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 ID.Kind = ValID::t_Constant;
2265 return false;
2266 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002267
Chris Lattnerdf986172009-01-02 07:01:27 +00002268 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002269 case lltok::kw_and:
2270 case lltok::kw_or:
2271 case lltok::kw_xor: {
2272 unsigned Opc = Lex.getUIntVal();
2273 Constant *Val0, *Val1;
2274 Lex.Lex();
2275 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2276 ParseGlobalTypeAndValue(Val0) ||
2277 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2278 ParseGlobalTypeAndValue(Val1) ||
2279 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2280 return true;
2281 if (Val0->getType() != Val1->getType())
2282 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002283 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 return Error(ID.Loc,
2285 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002286 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 ID.Kind = ValID::t_Constant;
2288 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002289 }
2290
Chris Lattnerdf986172009-01-02 07:01:27 +00002291 case lltok::kw_getelementptr:
2292 case lltok::kw_shufflevector:
2293 case lltok::kw_insertelement:
2294 case lltok::kw_extractelement:
2295 case lltok::kw_select: {
2296 unsigned Opc = Lex.getUIntVal();
2297 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002298 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002300 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002301 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2303 ParseGlobalValueVector(Elts) ||
2304 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2305 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002306
Chris Lattnerdf986172009-01-02 07:01:27 +00002307 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002308 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002310
Jay Foaddab3d292011-07-21 14:31:17 +00002311 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002312 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002313 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002314 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2315 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 } else if (Opc == Instruction::Select) {
2317 if (Elts.size() != 3)
2318 return Error(ID.Loc, "expected three operands to select");
2319 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2320 Elts[2]))
2321 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002322 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 } else if (Opc == Instruction::ShuffleVector) {
2324 if (Elts.size() != 3)
2325 return Error(ID.Loc, "expected three operands to shufflevector");
2326 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2327 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002328 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002329 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002330 } else if (Opc == Instruction::ExtractElement) {
2331 if (Elts.size() != 2)
2332 return Error(ID.Loc, "expected two operands to extractelement");
2333 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2334 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002335 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002336 } else {
2337 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2338 if (Elts.size() != 3)
2339 return Error(ID.Loc, "expected three operands to insertelement");
2340 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2341 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002342 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002343 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345
Chris Lattnerdf986172009-01-02 07:01:27 +00002346 ID.Kind = ValID::t_Constant;
2347 return false;
2348 }
2349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002350
Chris Lattnerdf986172009-01-02 07:01:27 +00002351 Lex.Lex();
2352 return false;
2353}
2354
2355/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002356bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002357 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002359 Value *V = NULL;
2360 bool Parsed = ParseValID(ID) ||
2361 ConvertValIDToValue(Ty, ID, V, NULL);
2362 if (V && !(C = dyn_cast<Constant>(V)))
2363 return Error(ID.Loc, "global values must be constants");
2364 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002365}
2366
Victor Hernandez92f238d2010-01-11 22:31:58 +00002367bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002368 Type *Ty = 0;
2369 return ParseType(Ty) ||
2370 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002371}
2372
2373/// ParseGlobalValueVector
2374/// ::= /*empty*/
2375/// ::= TypeAndValue (',' TypeAndValue)*
2376bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2377 // Empty list.
2378 if (Lex.getKind() == lltok::rbrace ||
2379 Lex.getKind() == lltok::rsquare ||
2380 Lex.getKind() == lltok::greater ||
2381 Lex.getKind() == lltok::rparen)
2382 return false;
2383
2384 Constant *C;
2385 if (ParseGlobalTypeAndValue(C)) return true;
2386 Elts.push_back(C);
2387
2388 while (EatIfPresent(lltok::comma)) {
2389 if (ParseGlobalTypeAndValue(C)) return true;
2390 Elts.push_back(C);
2391 }
2392
2393 return false;
2394}
2395
Dan Gohman309b3af2010-08-24 02:24:03 +00002396bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2397 assert(Lex.getKind() == lltok::lbrace);
2398 Lex.Lex();
2399
2400 SmallVector<Value*, 16> Elts;
2401 if (ParseMDNodeVector(Elts, PFS) ||
2402 ParseToken(lltok::rbrace, "expected end of metadata node"))
2403 return true;
2404
Jay Foadec9186b2011-04-21 19:59:31 +00002405 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002406 ID.Kind = ValID::t_MDNode;
2407 return false;
2408}
2409
Dan Gohman83448032010-07-14 18:26:50 +00002410/// ParseMetadataValue
2411/// ::= !42
2412/// ::= !{...}
2413/// ::= !"string"
2414bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2415 assert(Lex.getKind() == lltok::exclaim);
2416 Lex.Lex();
2417
2418 // MDNode:
2419 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002420 if (Lex.getKind() == lltok::lbrace)
2421 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002422
2423 // Standalone metadata reference
2424 // !42
2425 if (Lex.getKind() == lltok::APSInt) {
2426 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2427 ID.Kind = ValID::t_MDNode;
2428 return false;
2429 }
2430
2431 // MDString:
2432 // ::= '!' STRINGCONSTANT
2433 if (ParseMDString(ID.MDStringVal)) return true;
2434 ID.Kind = ValID::t_MDString;
2435 return false;
2436}
2437
Victor Hernandez92f238d2010-01-11 22:31:58 +00002438
2439//===----------------------------------------------------------------------===//
2440// Function Parsing.
2441//===----------------------------------------------------------------------===//
2442
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002443bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002444 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002445 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002447
Chris Lattnerdf986172009-01-02 07:01:27 +00002448 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002451 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2452 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2453 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002454 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002455 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2456 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2457 return (V == 0);
2458 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002459 PointerType *PTy = dyn_cast<PointerType>(Ty);
2460 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002461 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2462 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2463 return Error(ID.Loc, "invalid type for inline asm constraint string");
2464 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2465 return false;
2466 }
2467 case ValID::t_MDNode:
2468 if (!Ty->isMetadataTy())
2469 return Error(ID.Loc, "metadata value must have metadata type");
2470 V = ID.MDNodeVal;
2471 return false;
2472 case ValID::t_MDString:
2473 if (!Ty->isMetadataTy())
2474 return Error(ID.Loc, "metadata value must have metadata type");
2475 V = ID.MDStringVal;
2476 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002477 case ValID::t_GlobalName:
2478 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2479 return V == 0;
2480 case ValID::t_GlobalID:
2481 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2482 return V == 0;
2483 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002484 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002485 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002486 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002487 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002488 return false;
2489 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002490 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002491 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2492 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002493
Chris Lattnerdf986172009-01-02 07:01:27 +00002494 // The lexer has no type info, so builds all float and double FP constants
2495 // as double. Fix this here. Long double does not need this.
2496 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002497 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002498 bool Ignored;
2499 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2500 &Ignored);
2501 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002502 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002503
Chris Lattner959873d2009-01-05 18:24:23 +00002504 if (V->getType() != Ty)
2505 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002506 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002507
Chris Lattnerdf986172009-01-02 07:01:27 +00002508 return false;
2509 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002510 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002511 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002512 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002513 return false;
2514 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002515 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002516 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002517 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002518 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002520 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002521 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002522 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002523 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002524 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002525 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002526 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002527 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002528 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002529 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002530 return false;
2531 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002532 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002533 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002534
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 V = ID.ConstantVal;
2536 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002537 case ValID::t_ConstantStruct:
2538 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002539 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002540 if (ST->getNumElements() != ID.UIntVal)
2541 return Error(ID.Loc,
2542 "initializer with struct type has wrong # elements");
2543 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2544 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2545
2546 // Verify that the elements are compatible with the structtype.
2547 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2548 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2549 return Error(ID.Loc, "element " + Twine(i) +
2550 " of struct initializer doesn't match struct element type");
2551
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002552 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2553 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002554 } else
2555 return Error(ID.Loc, "constant expression type mismatch");
2556 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002557 }
2558}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002559
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002560bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002561 V = 0;
2562 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002563 return ParseValID(ID, PFS) ||
2564 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002565}
2566
Chris Lattner1afcace2011-07-09 17:41:24 +00002567bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2568 Type *Ty = 0;
2569 return ParseType(Ty) ||
2570 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002571}
2572
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002573bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2574 PerFunctionState &PFS) {
2575 Value *V;
2576 Loc = Lex.getLoc();
2577 if (ParseTypeAndValue(V, PFS)) return true;
2578 if (!isa<BasicBlock>(V))
2579 return Error(Loc, "expected a basic block");
2580 BB = cast<BasicBlock>(V);
2581 return false;
2582}
2583
2584
Chris Lattnerdf986172009-01-02 07:01:27 +00002585/// FunctionHeader
2586/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002587/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002588/// OptionalAlign OptGC
2589bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2590 // Parse the linkage.
2591 LocTy LinkageLoc = Lex.getLoc();
2592 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002593
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002594 unsigned Visibility, RetAttrs;
2595 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002596 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 LocTy RetTypeLoc = Lex.getLoc();
2598 if (ParseOptionalLinkage(Linkage) ||
2599 ParseOptionalVisibility(Visibility) ||
2600 ParseOptionalCallingConv(CC) ||
2601 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002602 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002603 return true;
2604
2605 // Verify that the linkage is ok.
2606 switch ((GlobalValue::LinkageTypes)Linkage) {
2607 case GlobalValue::ExternalLinkage:
2608 break; // always ok.
2609 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002610 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 if (isDefine)
2612 return Error(LinkageLoc, "invalid linkage for function definition");
2613 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002614 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002615 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002616 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002617 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002619 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002620 case GlobalValue::LinkOnceAnyLinkage:
2621 case GlobalValue::LinkOnceODRLinkage:
2622 case GlobalValue::WeakAnyLinkage:
2623 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 case GlobalValue::DLLExportLinkage:
2625 if (!isDefine)
2626 return Error(LinkageLoc, "invalid linkage for function declaration");
2627 break;
2628 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002629 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 return Error(LinkageLoc, "invalid function linkage type");
2631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattner1afcace2011-07-09 17:41:24 +00002633 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002635
Chris Lattnerdf986172009-01-02 07:01:27 +00002636 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002637
2638 std::string FunctionName;
2639 if (Lex.getKind() == lltok::GlobalVar) {
2640 FunctionName = Lex.getStrVal();
2641 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2642 unsigned NameID = Lex.getUIntVal();
2643
2644 if (NameID != NumberedVals.size())
2645 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002646 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002647 } else {
2648 return TokError("expected function name");
2649 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002650
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002651 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002652
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002653 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002654 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002655
Chris Lattner1afcace2011-07-09 17:41:24 +00002656 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002657 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002658 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002659 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002660 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002661 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002662 bool UnnamedAddr;
2663 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002664
Chris Lattner1afcace2011-07-09 17:41:24 +00002665 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002666 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2667 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002668 ParseOptionalAttrs(FuncAttrs, 2) ||
2669 (EatIfPresent(lltok::kw_section) &&
2670 ParseStringConstant(Section)) ||
2671 ParseOptionalAlignment(Alignment) ||
2672 (EatIfPresent(lltok::kw_gc) &&
2673 ParseStringConstant(GC)))
2674 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002675
2676 // If the alignment was parsed as an attribute, move to the alignment field.
2677 if (FuncAttrs & Attribute::Alignment) {
2678 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2679 FuncAttrs &= ~Attribute::Alignment;
2680 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002681
Chris Lattnerdf986172009-01-02 07:01:27 +00002682 // Okay, if we got here, the function is syntactically valid. Convert types
2683 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002684 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002685 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002686
Chris Lattnerdf986172009-01-02 07:01:27 +00002687 if (RetAttrs != Attribute::None)
2688 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002689
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002691 ParamTypeList.push_back(ArgList[i].Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 if (ArgList[i].Attrs != Attribute::None)
2693 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2694 }
2695
2696 if (FuncAttrs != Attribute::None)
2697 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2698
2699 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002700
Benjamin Kramerf0127052010-01-05 13:12:22 +00002701 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002702 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2703
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002704 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002705 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002706 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002707
2708 Fn = 0;
2709 if (!FunctionName.empty()) {
2710 // If this was a definition of a forward reference, remove the definition
2711 // from the forward reference table and fill in the forward ref.
2712 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2713 ForwardRefVals.find(FunctionName);
2714 if (FRVI != ForwardRefVals.end()) {
2715 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002716 if (Fn->getType() != PFT)
2717 return Error(FRVI->second.second, "invalid forward reference to "
2718 "function '" + FunctionName + "' with wrong type!");
2719
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 ForwardRefVals.erase(FRVI);
2721 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002722 // Reject redefinitions.
2723 return Error(NameLoc, "invalid redefinition of function '" +
2724 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002725 } else if (M->getNamedValue(FunctionName)) {
2726 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002728
Dan Gohman41905542009-08-29 23:37:49 +00002729 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 // If this is a definition of a forward referenced function, make sure the
2731 // types agree.
2732 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2733 = ForwardRefValIDs.find(NumberedVals.size());
2734 if (I != ForwardRefValIDs.end()) {
2735 Fn = cast<Function>(I->second.first);
2736 if (Fn->getType() != PFT)
2737 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002738 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002739 ForwardRefValIDs.erase(I);
2740 }
2741 }
2742
2743 if (Fn == 0)
2744 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2745 else // Move the forward-reference to the correct spot in the module.
2746 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2747
2748 if (FunctionName.empty())
2749 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002750
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2752 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2753 Fn->setCallingConv(CC);
2754 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002755 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002756 Fn->setAlignment(Alignment);
2757 Fn->setSection(Section);
2758 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002759
Chris Lattnerdf986172009-01-02 07:01:27 +00002760 // Add all of the arguments we parsed to the function.
2761 Function::arg_iterator ArgIt = Fn->arg_begin();
2762 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2763 // If the argument has a name, insert it into the argument symbol table.
2764 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 // Set the name, if it conflicted, it will be auto-renamed.
2767 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002768
Benjamin Krameraf812352010-10-16 11:28:23 +00002769 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2771 ArgList[i].Name + "'");
2772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002773
Chris Lattnerdf986172009-01-02 07:01:27 +00002774 return false;
2775}
2776
2777
2778/// ParseFunctionBody
2779/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002780///
2781bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002782 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002783 return TokError("expected '{' in function body");
2784 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002785
Chris Lattner09d9ef42009-10-28 03:39:23 +00002786 int FunctionNumber = -1;
2787 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2788
2789 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002790
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002791 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002792 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002793 return TokError("function body requires at least one basic block");
2794
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002795 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Eat the }.
2799 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002800
Chris Lattnerdf986172009-01-02 07:01:27 +00002801 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002802 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002803}
2804
2805/// ParseBasicBlock
2806/// ::= LabelStr? Instruction*
2807bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2808 // If this basic block starts out with a name, remember it.
2809 std::string Name;
2810 LocTy NameLoc = Lex.getLoc();
2811 if (Lex.getKind() == lltok::LabelStr) {
2812 Name = Lex.getStrVal();
2813 Lex.Lex();
2814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2817 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002818
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002820
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 // Parse the instructions in this block until we get a terminator.
2822 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002823 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 do {
2825 // This instruction may have three possibilities for a name: a) none
2826 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2827 LocTy NameLoc = Lex.getLoc();
2828 int NameID = -1;
2829 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002830
Chris Lattnerdf986172009-01-02 07:01:27 +00002831 if (Lex.getKind() == lltok::LocalVarID) {
2832 NameID = Lex.getUIntVal();
2833 Lex.Lex();
2834 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2835 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002836 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 NameStr = Lex.getStrVal();
2838 Lex.Lex();
2839 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2840 return true;
2841 }
Devang Patelf633a062009-09-17 23:04:48 +00002842
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002843 switch (ParseInstruction(Inst, BB, PFS)) {
2844 default: assert(0 && "Unknown ParseInstruction result!");
2845 case InstError: return true;
2846 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002847 BB->getInstList().push_back(Inst);
2848
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002849 // With a normal result, we check to see if the instruction is followed by
2850 // a comma and metadata.
2851 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002852 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002853 return true;
2854 break;
2855 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002856 BB->getInstList().push_back(Inst);
2857
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002858 // If the instruction parser ate an extra comma at the end of it, it
2859 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002860 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002861 return true;
2862 break;
2863 }
Devang Patelf633a062009-09-17 23:04:48 +00002864
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 // Set the name on the instruction.
2866 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2867 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 return false;
2870}
2871
2872//===----------------------------------------------------------------------===//
2873// Instruction Parsing.
2874//===----------------------------------------------------------------------===//
2875
2876/// ParseInstruction - Parse one of the many different instructions.
2877///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002878int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2879 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 lltok::Kind Token = Lex.getKind();
2881 if (Token == lltok::Eof)
2882 return TokError("found end of file when expecting more instructions");
2883 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002884 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002886
Chris Lattnerdf986172009-01-02 07:01:27 +00002887 switch (Token) {
2888 default: return Error(Loc, "expected instruction opcode");
2889 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002890 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2891 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002892 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2893 case lltok::kw_br: return ParseBr(Inst, PFS);
2894 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002895 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002897 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002898 // Binary Operators.
2899 case lltok::kw_add:
2900 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002901 case lltok::kw_mul:
2902 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002903 bool NUW = EatIfPresent(lltok::kw_nuw);
2904 bool NSW = EatIfPresent(lltok::kw_nsw);
2905 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2906
2907 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2908
2909 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2910 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2911 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002912 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002913 case lltok::kw_fadd:
2914 case lltok::kw_fsub:
2915 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2916
Chris Lattner35bda892011-02-06 21:44:57 +00002917 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002918 case lltok::kw_udiv:
2919 case lltok::kw_lshr:
2920 case lltok::kw_ashr: {
2921 bool Exact = EatIfPresent(lltok::kw_exact);
2922
2923 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2924 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2925 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002926 }
2927
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002929 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002930 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002931 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002932 case lltok::kw_and:
2933 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002934 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002935 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002936 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002937 // Casts.
2938 case lltok::kw_trunc:
2939 case lltok::kw_zext:
2940 case lltok::kw_sext:
2941 case lltok::kw_fptrunc:
2942 case lltok::kw_fpext:
2943 case lltok::kw_bitcast:
2944 case lltok::kw_uitofp:
2945 case lltok::kw_sitofp:
2946 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002947 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002948 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002949 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002950 // Other.
2951 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002952 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2954 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2955 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2956 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002957 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2959 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2960 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002961 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00002962 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2963 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2964 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
2965 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00002966 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002967 case lltok::kw_volatile:
Eli Friedmanf03bb262011-08-12 22:50:01 +00002968 // For compatibility; canonical location is after load
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002969 if (EatIfPresent(lltok::kw_load))
Eli Friedmanf03bb262011-08-12 22:50:01 +00002970 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002971 else if (EatIfPresent(lltok::kw_store))
Eli Friedmanf03bb262011-08-12 22:50:01 +00002972 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002973 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002975 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2976 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2977 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2978 }
2979}
2980
2981/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2982bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002983 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002984 switch (Lex.getKind()) {
2985 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2986 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2987 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2988 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2989 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2990 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2991 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2992 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2993 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2994 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2995 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2996 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2997 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2998 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2999 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3000 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3001 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3002 }
3003 } else {
3004 switch (Lex.getKind()) {
3005 default: TokError("expected icmp predicate (e.g. 'eq')");
3006 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3007 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3008 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3009 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3010 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3011 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3012 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3013 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3014 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3015 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3016 }
3017 }
3018 Lex.Lex();
3019 return false;
3020}
3021
3022//===----------------------------------------------------------------------===//
3023// Terminator Instructions.
3024//===----------------------------------------------------------------------===//
3025
3026/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003027/// ::= 'ret' void (',' !dbg, !1)*
3028/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003029bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003030 PerFunctionState &PFS) {
3031 SMLoc TypeLoc = Lex.getLoc();
3032 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003033 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003034
Chris Lattner1afcace2011-07-09 17:41:24 +00003035 Type *ResType = PFS.getFunction().getReturnType();
3036
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003037 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003038 if (!ResType->isVoidTy())
3039 return Error(TypeLoc, "value doesn't match function result type '" +
3040 getTypeString(ResType) + "'");
3041
Owen Anderson1d0be152009-08-13 21:58:54 +00003042 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003043 return false;
3044 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003045
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 Value *RV;
3047 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003048
Chris Lattner1afcace2011-07-09 17:41:24 +00003049 if (ResType != RV->getType())
3050 return Error(TypeLoc, "value doesn't match function result type '" +
3051 getTypeString(ResType) + "'");
3052
Owen Anderson1d0be152009-08-13 21:58:54 +00003053 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003054 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003055}
3056
3057
3058/// ParseBr
3059/// ::= 'br' TypeAndValue
3060/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3061bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3062 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003063 Value *Op0;
3064 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003066
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3068 Inst = BranchInst::Create(BB);
3069 return false;
3070 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003071
Owen Anderson1d0be152009-08-13 21:58:54 +00003072 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003073 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003074
Chris Lattnerdf986172009-01-02 07:01:27 +00003075 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003076 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003078 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003080
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003081 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 return false;
3083}
3084
3085/// ParseSwitch
3086/// Instruction
3087/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3088/// JumpTable
3089/// ::= (TypeAndValue ',' TypeAndValue)*
3090bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3091 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003092 Value *Cond;
3093 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3095 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003096 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3098 return true;
3099
Duncan Sands1df98592010-02-16 11:11:14 +00003100 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003101 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003102
Chris Lattnerdf986172009-01-02 07:01:27 +00003103 // Parse the jump table pairs.
3104 SmallPtrSet<Value*, 32> SeenCases;
3105 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3106 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003107 Value *Constant;
3108 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003109
Chris Lattnerdf986172009-01-02 07:01:27 +00003110 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3111 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003112 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003113 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003114
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 if (!SeenCases.insert(Constant))
3116 return Error(CondLoc, "duplicate case value in switch");
3117 if (!isa<ConstantInt>(Constant))
3118 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003119
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003120 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003121 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003122
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003124
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003125 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003126 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3127 SI->addCase(Table[i].first, Table[i].second);
3128 Inst = SI;
3129 return false;
3130}
3131
Chris Lattnerab21db72009-10-28 00:19:10 +00003132/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003133/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003134/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3135bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003136 LocTy AddrLoc;
3137 Value *Address;
3138 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003139 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3140 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003141 return true;
3142
Duncan Sands1df98592010-02-16 11:11:14 +00003143 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003144 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003145
3146 // Parse the destination list.
3147 SmallVector<BasicBlock*, 16> DestList;
3148
3149 if (Lex.getKind() != lltok::rsquare) {
3150 BasicBlock *DestBB;
3151 if (ParseTypeAndBasicBlock(DestBB, PFS))
3152 return true;
3153 DestList.push_back(DestBB);
3154
3155 while (EatIfPresent(lltok::comma)) {
3156 if (ParseTypeAndBasicBlock(DestBB, PFS))
3157 return true;
3158 DestList.push_back(DestBB);
3159 }
3160 }
3161
3162 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3163 return true;
3164
Chris Lattnerab21db72009-10-28 00:19:10 +00003165 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3167 IBI->addDestination(DestList[i]);
3168 Inst = IBI;
3169 return false;
3170}
3171
3172
Chris Lattnerdf986172009-01-02 07:01:27 +00003173/// ParseInvoke
3174/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3175/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3176bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3177 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003178 unsigned RetAttrs, FnAttrs;
3179 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003180 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003181 LocTy RetTypeLoc;
3182 ValID CalleeID;
3183 SmallVector<ParamInfo, 16> ArgList;
3184
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003185 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 if (ParseOptionalCallingConv(CC) ||
3187 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003188 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 ParseValID(CalleeID) ||
3190 ParseParameterList(ArgList, PFS) ||
3191 ParseOptionalAttrs(FnAttrs, 2) ||
3192 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003193 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003194 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003195 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003197
Chris Lattnerdf986172009-01-02 07:01:27 +00003198 // If RetType is a non-function pointer type, then this is the short syntax
3199 // for the call, which means that RetType is just the return type. Infer the
3200 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003201 PointerType *PFTy = 0;
3202 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3204 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3205 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003206 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3208 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 if (!FunctionType::isValidReturnType(RetType))
3211 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003212
Owen Andersondebcb012009-07-29 22:17:13 +00003213 Ty = FunctionType::get(RetType, ParamTypes, false);
3214 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003216
Chris Lattnerdf986172009-01-02 07:01:27 +00003217 // Look up the callee.
3218 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003219 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003220
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 // Set up the Attributes for the function.
3222 SmallVector<AttributeWithIndex, 8> Attrs;
3223 if (RetAttrs != Attribute::None)
3224 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003225
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003227
Chris Lattnerdf986172009-01-02 07:01:27 +00003228 // Loop through FunctionType's arguments and ensure they are specified
3229 // correctly. Also, gather any parameter attributes.
3230 FunctionType::param_iterator I = Ty->param_begin();
3231 FunctionType::param_iterator E = Ty->param_end();
3232 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003233 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003234 if (I != E) {
3235 ExpectedTy = *I++;
3236 } else if (!Ty->isVarArg()) {
3237 return Error(ArgList[i].Loc, "too many arguments specified");
3238 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003239
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3241 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003242 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 Args.push_back(ArgList[i].V);
3244 if (ArgList[i].Attrs != Attribute::None)
3245 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3246 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003247
Chris Lattnerdf986172009-01-02 07:01:27 +00003248 if (I != E)
3249 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003250
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 if (FnAttrs != Attribute::None)
3252 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003253
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 // Finish off the Attributes and check them
3255 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Jay Foada3efbb12011-07-15 08:37:34 +00003257 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003258 II->setCallingConv(CC);
3259 II->setAttributes(PAL);
3260 Inst = II;
3261 return false;
3262}
3263
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003264/// ParseResume
3265/// ::= 'resume' TypeAndValue
3266bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3267 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003268 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3269 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003270
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003271 ResumeInst *RI = ResumeInst::Create(Exn);
3272 Inst = RI;
3273 return false;
3274}
Chris Lattnerdf986172009-01-02 07:01:27 +00003275
3276//===----------------------------------------------------------------------===//
3277// Binary Operators.
3278//===----------------------------------------------------------------------===//
3279
3280/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003281/// ::= ArithmeticOps TypeAndValue ',' Value
3282///
3283/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3284/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003285bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003286 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003287 LocTy Loc; Value *LHS, *RHS;
3288 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3289 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3290 ParseValue(LHS->getType(), RHS, PFS))
3291 return true;
3292
Chris Lattnere914b592009-01-05 08:24:46 +00003293 bool Valid;
3294 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003295 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003296 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003297 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3298 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003299 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003300 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3301 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003302 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003303
Chris Lattnere914b592009-01-05 08:24:46 +00003304 if (!Valid)
3305 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003306
Chris Lattnerdf986172009-01-02 07:01:27 +00003307 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3308 return false;
3309}
3310
3311/// ParseLogical
3312/// ::= ArithmeticOps TypeAndValue ',' Value {
3313bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3314 unsigned Opc) {
3315 LocTy Loc; Value *LHS, *RHS;
3316 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3317 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3318 ParseValue(LHS->getType(), RHS, PFS))
3319 return true;
3320
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003321 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 return Error(Loc,"instruction requires integer or integer vector operands");
3323
3324 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3325 return false;
3326}
3327
3328
3329/// ParseCompare
3330/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3331/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003332bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3333 unsigned Opc) {
3334 // Parse the integer/fp comparison predicate.
3335 LocTy Loc;
3336 unsigned Pred;
3337 Value *LHS, *RHS;
3338 if (ParseCmpPredicate(Pred, Opc) ||
3339 ParseTypeAndValue(LHS, Loc, PFS) ||
3340 ParseToken(lltok::comma, "expected ',' after compare value") ||
3341 ParseValue(LHS->getType(), RHS, PFS))
3342 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003343
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003345 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003347 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003348 } else {
3349 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003350 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003351 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003353 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 }
3355 return false;
3356}
3357
3358//===----------------------------------------------------------------------===//
3359// Other Instructions.
3360//===----------------------------------------------------------------------===//
3361
3362
3363/// ParseCast
3364/// ::= CastOpc TypeAndValue 'to' Type
3365bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3366 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003367 LocTy Loc;
3368 Value *Op;
3369 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 if (ParseTypeAndValue(Op, Loc, PFS) ||
3371 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3372 ParseType(DestTy))
3373 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003374
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003375 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3376 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003377 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003378 getTypeString(Op->getType()) + "' to '" +
3379 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003380 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3382 return false;
3383}
3384
3385/// ParseSelect
3386/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3387bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3388 LocTy Loc;
3389 Value *Op0, *Op1, *Op2;
3390 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3391 ParseToken(lltok::comma, "expected ',' after select condition") ||
3392 ParseTypeAndValue(Op1, PFS) ||
3393 ParseToken(lltok::comma, "expected ',' after select value") ||
3394 ParseTypeAndValue(Op2, PFS))
3395 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003396
Chris Lattnerdf986172009-01-02 07:01:27 +00003397 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3398 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003399
Chris Lattnerdf986172009-01-02 07:01:27 +00003400 Inst = SelectInst::Create(Op0, Op1, Op2);
3401 return false;
3402}
3403
Chris Lattner0088a5c2009-01-05 08:18:44 +00003404/// ParseVA_Arg
3405/// ::= 'va_arg' TypeAndValue ',' Type
3406bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003407 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003408 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003409 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 if (ParseTypeAndValue(Op, PFS) ||
3411 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003412 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003413 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003414
Chris Lattner0088a5c2009-01-05 08:18:44 +00003415 if (!EltTy->isFirstClassType())
3416 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003417
3418 Inst = new VAArgInst(Op, EltTy);
3419 return false;
3420}
3421
3422/// ParseExtractElement
3423/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3424bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3425 LocTy Loc;
3426 Value *Op0, *Op1;
3427 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3428 ParseToken(lltok::comma, "expected ',' after extract value") ||
3429 ParseTypeAndValue(Op1, PFS))
3430 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003431
Chris Lattnerdf986172009-01-02 07:01:27 +00003432 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3433 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003434
Eric Christophera3500da2009-07-25 02:28:41 +00003435 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003436 return false;
3437}
3438
3439/// ParseInsertElement
3440/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3441bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3442 LocTy Loc;
3443 Value *Op0, *Op1, *Op2;
3444 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3446 ParseTypeAndValue(Op1, PFS) ||
3447 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3448 ParseTypeAndValue(Op2, PFS))
3449 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003450
Chris Lattnerdf986172009-01-02 07:01:27 +00003451 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003452 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003453
Chris Lattnerdf986172009-01-02 07:01:27 +00003454 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3455 return false;
3456}
3457
3458/// ParseShuffleVector
3459/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3460bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3461 LocTy Loc;
3462 Value *Op0, *Op1, *Op2;
3463 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3464 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3465 ParseTypeAndValue(Op1, PFS) ||
3466 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3467 ParseTypeAndValue(Op2, PFS))
3468 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003469
Chris Lattnerdf986172009-01-02 07:01:27 +00003470 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3471 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003472
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3474 return false;
3475}
3476
3477/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003478/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003479int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003480 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003482
Chris Lattner1afcace2011-07-09 17:41:24 +00003483 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003484 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3485 ParseValue(Ty, Op0, PFS) ||
3486 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003487 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003488 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3489 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003490
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003491 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003492 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3493 while (1) {
3494 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003495
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003496 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003497 break;
3498
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003499 if (Lex.getKind() == lltok::MetadataVar) {
3500 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003501 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003502 }
Devang Patela43d46f2009-10-16 18:45:49 +00003503
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003504 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003505 ParseValue(Ty, Op0, PFS) ||
3506 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003507 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3509 return true;
3510 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003511
Chris Lattnerdf986172009-01-02 07:01:27 +00003512 if (!Ty->isFirstClassType())
3513 return Error(TypeLoc, "phi node must have first class type");
3514
Jay Foad3ecfc862011-03-30 11:28:46 +00003515 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003516 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3517 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3518 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003519 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003520}
3521
Bill Wendlinge6e88262011-08-12 20:24:12 +00003522/// ParseLandingPad
3523/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3524/// Clause
3525/// ::= 'catch' TypeAndValue
3526/// ::= 'filter'
3527/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3528bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3529 Type *Ty = 0; LocTy TyLoc;
3530 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003531
3532 if (ParseType(Ty, TyLoc) ||
3533 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3534 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3535 return true;
3536
3537 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3538 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3539
3540 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3541 LandingPadInst::ClauseType CT;
3542 if (EatIfPresent(lltok::kw_catch))
3543 CT = LandingPadInst::Catch;
3544 else if (EatIfPresent(lltok::kw_filter))
3545 CT = LandingPadInst::Filter;
3546 else
3547 return TokError("expected 'catch' or 'filter' clause type");
3548
3549 Value *V; LocTy VLoc;
3550 if (ParseTypeAndValue(V, VLoc, PFS)) {
3551 delete LP;
3552 return true;
3553 }
3554
Bill Wendling746c8822011-08-12 20:52:25 +00003555 // A 'catch' type expects a non-array constant. A filter clause expects an
3556 // array constant.
3557 if (CT == LandingPadInst::Catch) {
3558 if (isa<ArrayType>(V->getType()))
3559 Error(VLoc, "'catch' clause has an invalid type");
3560 } else {
3561 if (!isa<ArrayType>(V->getType()))
3562 Error(VLoc, "'filter' clause has an invalid type");
3563 }
3564
Bill Wendlinge6e88262011-08-12 20:24:12 +00003565 LP->addClause(V);
3566 }
3567
3568 Inst = LP;
3569 return false;
3570}
3571
Chris Lattnerdf986172009-01-02 07:01:27 +00003572/// ParseCall
3573/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3574/// ParameterList OptionalAttrs
3575bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3576 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003577 unsigned RetAttrs, FnAttrs;
3578 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003579 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 LocTy RetTypeLoc;
3581 ValID CalleeID;
3582 SmallVector<ParamInfo, 16> ArgList;
3583 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003584
Chris Lattnerdf986172009-01-02 07:01:27 +00003585 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3586 ParseOptionalCallingConv(CC) ||
3587 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003588 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003589 ParseValID(CalleeID) ||
3590 ParseParameterList(ArgList, PFS) ||
3591 ParseOptionalAttrs(FnAttrs, 2))
3592 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003593
Chris Lattnerdf986172009-01-02 07:01:27 +00003594 // If RetType is a non-function pointer type, then this is the short syntax
3595 // for the call, which means that RetType is just the return type. Infer the
3596 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003597 PointerType *PFTy = 0;
3598 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003599 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3600 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3601 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003602 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003603 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3604 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003605
Chris Lattnerdf986172009-01-02 07:01:27 +00003606 if (!FunctionType::isValidReturnType(RetType))
3607 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003608
Owen Andersondebcb012009-07-29 22:17:13 +00003609 Ty = FunctionType::get(RetType, ParamTypes, false);
3610 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003611 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003612
Chris Lattnerdf986172009-01-02 07:01:27 +00003613 // Look up the callee.
3614 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003615 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003616
Chris Lattnerdf986172009-01-02 07:01:27 +00003617 // Set up the Attributes for the function.
3618 SmallVector<AttributeWithIndex, 8> Attrs;
3619 if (RetAttrs != Attribute::None)
3620 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003621
Chris Lattnerdf986172009-01-02 07:01:27 +00003622 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003623
Chris Lattnerdf986172009-01-02 07:01:27 +00003624 // Loop through FunctionType's arguments and ensure they are specified
3625 // correctly. Also, gather any parameter attributes.
3626 FunctionType::param_iterator I = Ty->param_begin();
3627 FunctionType::param_iterator E = Ty->param_end();
3628 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003629 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003630 if (I != E) {
3631 ExpectedTy = *I++;
3632 } else if (!Ty->isVarArg()) {
3633 return Error(ArgList[i].Loc, "too many arguments specified");
3634 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003635
Chris Lattnerdf986172009-01-02 07:01:27 +00003636 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3637 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003638 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 Args.push_back(ArgList[i].V);
3640 if (ArgList[i].Attrs != Attribute::None)
3641 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3642 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003643
Chris Lattnerdf986172009-01-02 07:01:27 +00003644 if (I != E)
3645 return Error(CallLoc, "not enough parameters specified for call");
3646
3647 if (FnAttrs != Attribute::None)
3648 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3649
3650 // Finish off the Attributes and check them
3651 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003652
Jay Foada3efbb12011-07-15 08:37:34 +00003653 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003654 CI->setTailCall(isTail);
3655 CI->setCallingConv(CC);
3656 CI->setAttributes(PAL);
3657 Inst = CI;
3658 return false;
3659}
3660
3661//===----------------------------------------------------------------------===//
3662// Memory Instructions.
3663//===----------------------------------------------------------------------===//
3664
3665/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003666/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003667int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003669 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003670 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003671 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003672 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003673
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003674 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003675 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003676 if (Lex.getKind() == lltok::kw_align) {
3677 if (ParseOptionalAlignment(Alignment)) return true;
3678 } else if (Lex.getKind() == lltok::MetadataVar) {
3679 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003680 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003681 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3682 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3683 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003684 }
3685 }
3686
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003687 if (Size && !Size->getType()->isIntegerTy())
3688 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003689
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003690 Inst = new AllocaInst(Ty, Size, Alignment);
3691 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003692}
3693
3694/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003695/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3696/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3697/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3698/// Compatibility:
3699/// ::= 'volatile' 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003700int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
Eli Friedmanf03bb262011-08-12 22:50:01 +00003701 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003702 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003703 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003704 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003705 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003706 AtomicOrdering Ordering = NotAtomic;
3707 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003708
3709 if (Lex.getKind() == lltok::kw_atomic) {
3710 if (isVolatile)
3711 return TokError("mixing atomic with old volatile placement");
3712 isAtomic = true;
3713 Lex.Lex();
3714 }
3715
3716 if (Lex.getKind() == lltok::kw_volatile) {
3717 if (isVolatile)
3718 return TokError("duplicate volatile before and after store");
3719 isVolatile = true;
3720 Lex.Lex();
3721 }
3722
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003723 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003724 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003725 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3726 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003727
Duncan Sands1df98592010-02-16 11:11:14 +00003728 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3730 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003731 if (isAtomic && !Alignment)
3732 return Error(Loc, "atomic load must have explicit non-zero alignment");
3733 if (Ordering == Release || Ordering == AcquireRelease)
3734 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003735
Eli Friedman21006d42011-08-09 23:02:53 +00003736 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003737 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003738}
3739
3740/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003741
3742/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3743/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003744/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Eli Friedmanf03bb262011-08-12 22:50:01 +00003745/// Compatibility:
3746/// ::= 'volatile' 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003747int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
Eli Friedmanf03bb262011-08-12 22:50:01 +00003748 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003749 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003750 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003751 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003752 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003753 AtomicOrdering Ordering = NotAtomic;
3754 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003755
3756 if (Lex.getKind() == lltok::kw_atomic) {
3757 if (isVolatile)
3758 return TokError("mixing atomic with old volatile placement");
3759 isAtomic = true;
3760 Lex.Lex();
3761 }
3762
3763 if (Lex.getKind() == lltok::kw_volatile) {
3764 if (isVolatile)
3765 return TokError("duplicate volatile before and after store");
3766 isVolatile = true;
3767 Lex.Lex();
3768 }
3769
Chris Lattnerdf986172009-01-02 07:01:27 +00003770 if (ParseTypeAndValue(Val, Loc, PFS) ||
3771 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003772 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003773 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003774 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003775 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003776
Duncan Sands1df98592010-02-16 11:11:14 +00003777 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003778 return Error(PtrLoc, "store operand must be a pointer");
3779 if (!Val->getType()->isFirstClassType())
3780 return Error(Loc, "store operand must be a first class value");
3781 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3782 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003783 if (isAtomic && !Alignment)
3784 return Error(Loc, "atomic store must have explicit non-zero alignment");
3785 if (Ordering == Acquire || Ordering == AcquireRelease)
3786 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003787
Eli Friedman21006d42011-08-09 23:02:53 +00003788 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003789 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003790}
3791
Eli Friedmanff030482011-07-28 21:48:00 +00003792/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003793/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3794/// 'singlethread'? AtomicOrdering
3795int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003796 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3797 bool AteExtraComma = false;
3798 AtomicOrdering Ordering = NotAtomic;
3799 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003800 bool isVolatile = false;
3801
3802 if (EatIfPresent(lltok::kw_volatile))
3803 isVolatile = true;
3804
Eli Friedmanff030482011-07-28 21:48:00 +00003805 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3806 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3807 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3808 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3809 ParseTypeAndValue(New, NewLoc, PFS) ||
3810 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3811 return true;
3812
3813 if (Ordering == Unordered)
3814 return TokError("cmpxchg cannot be unordered");
3815 if (!Ptr->getType()->isPointerTy())
3816 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3817 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3818 return Error(CmpLoc, "compare value and pointer type do not match");
3819 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3820 return Error(NewLoc, "new value and pointer type do not match");
3821 if (!New->getType()->isIntegerTy())
3822 return Error(NewLoc, "cmpxchg operand must be an integer");
3823 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3824 if (Size < 8 || (Size & (Size - 1)))
3825 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3826 " integer");
3827
3828 AtomicCmpXchgInst *CXI =
3829 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3830 CXI->setVolatile(isVolatile);
3831 Inst = CXI;
3832 return AteExtraComma ? InstExtraComma : InstNormal;
3833}
3834
3835/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003836/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3837/// 'singlethread'? AtomicOrdering
3838int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003839 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3840 bool AteExtraComma = false;
3841 AtomicOrdering Ordering = NotAtomic;
3842 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003843 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003844 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003845
3846 if (EatIfPresent(lltok::kw_volatile))
3847 isVolatile = true;
3848
Eli Friedmanff030482011-07-28 21:48:00 +00003849 switch (Lex.getKind()) {
3850 default: return TokError("expected binary operation in atomicrmw");
3851 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3852 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3853 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3854 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3855 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3856 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3857 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3858 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3859 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3860 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3861 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3862 }
3863 Lex.Lex(); // Eat the operation.
3864
3865 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3866 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3867 ParseTypeAndValue(Val, ValLoc, PFS) ||
3868 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3869 return true;
3870
3871 if (Ordering == Unordered)
3872 return TokError("atomicrmw cannot be unordered");
3873 if (!Ptr->getType()->isPointerTy())
3874 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3875 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3876 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3877 if (!Val->getType()->isIntegerTy())
3878 return Error(ValLoc, "atomicrmw operand must be an integer");
3879 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3880 if (Size < 8 || (Size & (Size - 1)))
3881 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3882 " integer");
3883
3884 AtomicRMWInst *RMWI =
3885 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3886 RMWI->setVolatile(isVolatile);
3887 Inst = RMWI;
3888 return AteExtraComma ? InstExtraComma : InstNormal;
3889}
3890
Eli Friedman47f35132011-07-25 23:16:38 +00003891/// ParseFence
3892/// ::= 'fence' 'singlethread'? AtomicOrdering
3893int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3894 AtomicOrdering Ordering = NotAtomic;
3895 SynchronizationScope Scope = CrossThread;
3896 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3897 return true;
3898
3899 if (Ordering == Unordered)
3900 return TokError("fence cannot be unordered");
3901 if (Ordering == Monotonic)
3902 return TokError("fence cannot be monotonic");
3903
3904 Inst = new FenceInst(Context, Ordering, Scope);
3905 return InstNormal;
3906}
3907
Chris Lattnerdf986172009-01-02 07:01:27 +00003908/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003909/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003910int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003911 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003912
Dan Gohmandcb40a32009-07-29 15:58:36 +00003913 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003914
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003915 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003916
Duncan Sands1df98592010-02-16 11:11:14 +00003917 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003918 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003919
Chris Lattnerdf986172009-01-02 07:01:27 +00003920 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003921 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003922 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003923 if (Lex.getKind() == lltok::MetadataVar) {
3924 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003925 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003926 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003927 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003928 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003929 return Error(EltLoc, "getelementptr index must be an integer");
3930 Indices.push_back(Val);
3931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003932
Jay Foada9203102011-07-25 09:48:08 +00003933 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003934 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00003935 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003936 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003937 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003938 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003939}
3940
3941/// ParseExtractValue
3942/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003943int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003944 Value *Val; LocTy Loc;
3945 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003946 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003947 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003948 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003949 return true;
3950
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003951 if (!Val->getType()->isAggregateType())
3952 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003953
Jay Foadfc6d3a42011-07-13 10:26:04 +00003954 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003955 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003956 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003957 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003958}
3959
3960/// ParseInsertValue
3961/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003962int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003963 Value *Val0, *Val1; LocTy Loc0, Loc1;
3964 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003965 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003966 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3967 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3968 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003969 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003970 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003971
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003972 if (!Val0->getType()->isAggregateType())
3973 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003974
Jay Foadfc6d3a42011-07-13 10:26:04 +00003975 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003976 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003977 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003978 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003979}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003980
3981//===----------------------------------------------------------------------===//
3982// Embedded metadata.
3983//===----------------------------------------------------------------------===//
3984
3985/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003986/// ::= Element (',' Element)*
3987/// Element
3988/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003989bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003990 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003991 // Check for an empty list.
3992 if (Lex.getKind() == lltok::rbrace)
3993 return false;
3994
Nick Lewycky21cc4462009-04-04 07:22:01 +00003995 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003996 // Null is a special case since it is typeless.
3997 if (EatIfPresent(lltok::kw_null)) {
3998 Elts.push_back(0);
3999 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004000 }
Chris Lattnera7352392009-12-30 04:42:57 +00004001
4002 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004003 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004004 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004005 } while (EatIfPresent(lltok::comma));
4006
4007 return false;
4008}