blob: 28ee499662ac06ef7a9e6e3ed64489271eb51d8c [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"
27using namespace llvm;
28
Chris Lattner0cd0d882011-06-18 21:18:23 +000029static std::string getTypeString(const Type *T) {
30 std::string Result;
31 raw_string_ostream Tmp(Result);
32 Tmp << *T;
33 return Tmp.str();
34}
35
Chris Lattner3ed88ef2009-01-02 08:05:26 +000036/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000037bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000038 // Prime the lexer.
39 Lex.Lex();
40
Chris Lattnerad7d1e22009-01-04 20:44:11 +000041 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000043}
44
45/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46/// module.
47bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000048 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52 I != E; ++I) {
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
55
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
58
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000061 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000062 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63 }
64 }
65 ForwardRefInstMetadata.clear();
66 }
67
68
Chris Lattner09d9ef42009-10-28 03:39:23 +000069 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
73 Function *TheFn = 0;
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
79
80 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
82
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
88
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
91
92
Chris Lattnerdf986172009-01-02 07:01:27 +000093 if (!ForwardRefTypes.empty())
94 return Error(ForwardRefTypes.begin()->second.second,
95 "use of undefined type named '" +
96 ForwardRefTypes.begin()->first + "'");
97 if (!ForwardRefTypeIDs.empty())
98 return Error(ForwardRefTypeIDs.begin()->second.second,
99 "use of undefined type '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000100 Twine(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000101
Chris Lattnerdf986172009-01-02 07:01:27 +0000102 if (!ForwardRefVals.empty())
103 return Error(ForwardRefVals.begin()->second.second,
104 "use of undefined value '@" + ForwardRefVals.begin()->first +
105 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000106
Chris Lattnerdf986172009-01-02 07:01:27 +0000107 if (!ForwardRefValIDs.empty())
108 return Error(ForwardRefValIDs.begin()->second.second,
109 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000110 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000111
Devang Patel1c7eea62009-07-08 19:23:54 +0000112 if (!ForwardRefMDNodes.empty())
113 return Error(ForwardRefMDNodes.begin()->second.second,
114 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000115 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000116
Devang Patel1c7eea62009-07-08 19:23:54 +0000117
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 // Look for intrinsic functions and CallInst that need to be upgraded
119 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
120 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000121
Devang Patele4b27562009-08-28 23:24:31 +0000122 // Check debug info intrinsics.
123 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000124 return false;
125}
126
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
128 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
129 PerFunctionState *PFS) {
130 // Loop over all the references, resolving them.
131 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
132 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000133 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000134 if (Refs[i].first.Kind == ValID::t_LocalName)
135 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000136 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000137 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
138 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
139 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000140 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000141 } else {
142 Res = dyn_cast_or_null<BasicBlock>(
143 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
144 }
145
Chris Lattnercdfc9402009-11-01 01:27:45 +0000146 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000147 return Error(Refs[i].first.Loc,
148 "referenced value is not a basic block");
149
150 // Get the BlockAddress for this and update references to use it.
151 BlockAddress *BA = BlockAddress::get(TheFn, Res);
152 Refs[i].second->replaceAllUsesWith(BA);
153 Refs[i].second->eraseFromParent();
154 }
155 return false;
156}
157
158
Chris Lattnerdf986172009-01-02 07:01:27 +0000159//===----------------------------------------------------------------------===//
160// Top-Level Entities
161//===----------------------------------------------------------------------===//
162
163bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000164 while (1) {
165 switch (Lex.getKind()) {
166 default: return TokError("expected top-level entity");
167 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 case lltok::kw_declare: if (ParseDeclare()) return true; break;
169 case lltok::kw_define: if (ParseDefine()) return true; break;
170 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
171 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
172 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Chris Lattneredcaca82011-06-18 23:51:31 +0000173 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000174 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000176 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000177 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000178 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000179 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000180
181 // The Global variable production with no name can have many different
182 // optional leading prefixes, the production is:
183 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000184 // OptionalAddrSpace OptionalUnNammedAddr
185 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000186 case lltok::kw_private: // OptionalLinkage
187 case lltok::kw_linker_private: // OptionalLinkage
188 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000189 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000190 case lltok::kw_internal: // OptionalLinkage
191 case lltok::kw_weak: // OptionalLinkage
192 case lltok::kw_weak_odr: // OptionalLinkage
193 case lltok::kw_linkonce: // OptionalLinkage
194 case lltok::kw_linkonce_odr: // OptionalLinkage
195 case lltok::kw_appending: // OptionalLinkage
196 case lltok::kw_dllexport: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_dllimport: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000201 unsigned Linkage, Visibility;
202 if (ParseOptionalLinkage(Linkage) ||
203 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000204 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return true;
206 break;
207 }
208 case lltok::kw_default: // OptionalVisibility
209 case lltok::kw_hidden: // OptionalVisibility
210 case lltok::kw_protected: { // OptionalVisibility
211 unsigned Visibility;
212 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000213 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 return true;
215 break;
216 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000217
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000222 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000223 break;
224 }
225 }
226}
227
228
229/// toplevelentity
230/// ::= 'module' 'asm' STRINGCONSTANT
231bool LLParser::ParseModuleAsm() {
232 assert(Lex.getKind() == lltok::kw_module);
233 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000234
235 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000236 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
237 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000238
Rafael Espindola38c4e532011-03-02 04:14:42 +0000239 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000240 return false;
241}
242
243/// toplevelentity
244/// ::= 'target' 'triple' '=' STRINGCONSTANT
245/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
246bool LLParser::ParseTargetDefinition() {
247 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000249 switch (Lex.Lex()) {
250 default: return TokError("unknown target property");
251 case lltok::kw_triple:
252 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
254 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000256 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 return false;
258 case lltok::kw_datalayout:
259 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000260 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
261 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000262 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000263 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000264 return false;
265 }
266}
267
268/// toplevelentity
269/// ::= 'deplibs' '=' '[' ']'
270/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
271bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000273 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000274 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
275 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
276 return true;
277
278 if (EatIfPresent(lltok::rsquare))
279 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000281 std::string Str;
282 if (ParseStringConstant(Str)) return true;
283 M->addLibrary(Str);
284
285 while (EatIfPresent(lltok::comma)) {
286 if (ParseStringConstant(Str)) return true;
287 M->addLibrary(Str);
288 }
289
290 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000291}
292
Dan Gohman3845e502009-08-12 23:32:33 +0000293/// ParseUnnamedType:
Chris Lattneredcaca82011-06-18 23:51:31 +0000294/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000295/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000296bool LLParser::ParseUnnamedType() {
Chris Lattner8dd72b82011-06-18 23:38:57 +0000297 unsigned TypeID = NumberedTypes.size();
Chris Lattner8dd72b82011-06-18 23:38:57 +0000298
Chris Lattneredcaca82011-06-18 23:51:31 +0000299 // Handle the LocalVarID form.
300 if (Lex.getKind() == lltok::LocalVarID) {
301 if (Lex.getUIntVal() != TypeID)
302 return Error(Lex.getLoc(), "type expected to be numbered '%" +
303 Twine(TypeID) + "'");
304 Lex.Lex(); // eat LocalVarID;
305
306 if (ParseToken(lltok::equal, "expected '=' after name"))
307 return true;
308 }
309
310 LocTy TypeLoc = Lex.getLoc();
311 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000312
Owen Anderson1d0be152009-08-13 21:58:54 +0000313 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000314 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000315
Chris Lattnerdf986172009-01-02 07:01:27 +0000316 // See if this type was previously referenced.
317 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
318 FI = ForwardRefTypeIDs.find(TypeID);
319 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000320 if (FI->second.first.get() == Ty)
321 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerdf986172009-01-02 07:01:27 +0000323 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
324 Ty = FI->second.first.get();
325 ForwardRefTypeIDs.erase(FI);
326 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327
Chris Lattnerdf986172009-01-02 07:01:27 +0000328 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000329
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 return false;
331}
332
333/// toplevelentity
334/// ::= LocalVar '=' 'type' type
335bool LLParser::ParseNamedType() {
336 std::string Name = Lex.getStrVal();
337 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000338 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339
Owen Anderson1d0be152009-08-13 21:58:54 +0000340 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000341
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000342 if (ParseToken(lltok::equal, "expected '=' after name") ||
343 ParseToken(lltok::kw_type, "expected 'type' after name") ||
344 ParseType(Ty))
345 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000346
Chris Lattnerdf986172009-01-02 07:01:27 +0000347 // Set the type name, checking for conflicts as we do so.
348 bool AlreadyExists = M->addTypeName(Name, Ty);
349 if (!AlreadyExists) return false;
350
351 // See if this type is a forward reference. We need to eagerly resolve
352 // types to allow recursive type redefinitions below.
353 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
354 FI = ForwardRefTypes.find(Name);
355 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000356 if (FI->second.first.get() == Ty)
357 return Error(NameLoc, "self referential type is invalid");
358
Chris Lattnerdf986172009-01-02 07:01:27 +0000359 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
360 Ty = FI->second.first.get();
361 ForwardRefTypes.erase(FI);
Chris Lattnerd5890992011-06-17 07:06:44 +0000362 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000364
Chris Lattnerdf986172009-01-02 07:01:27 +0000365 // Inserting a name that is already defined, get the existing name.
Matt Beaumont-Gayd3e724a2011-06-17 22:21:12 +0000366 assert(M->getTypeByName(Name) && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Chris Lattnerd5890992011-06-17 07:06:44 +0000368 // Otherwise, this is an attempt to redefine a type, report the error.
Chris Lattnerdf986172009-01-02 07:01:27 +0000369 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000370 getTypeString(Ty) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000371}
372
373
374/// toplevelentity
375/// ::= 'declare' FunctionHeader
376bool LLParser::ParseDeclare() {
377 assert(Lex.getKind() == lltok::kw_declare);
378 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 Function *F;
381 return ParseFunctionHeader(F, false);
382}
383
384/// toplevelentity
385/// ::= 'define' FunctionHeader '{' ...
386bool LLParser::ParseDefine() {
387 assert(Lex.getKind() == lltok::kw_define);
388 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000391 return ParseFunctionHeader(F, true) ||
392 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000393}
394
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000395/// ParseGlobalType
396/// ::= 'constant'
397/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000398bool LLParser::ParseGlobalType(bool &IsConstant) {
399 if (Lex.getKind() == lltok::kw_constant)
400 IsConstant = true;
401 else if (Lex.getKind() == lltok::kw_global)
402 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000403 else {
404 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000405 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000406 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000407 Lex.Lex();
408 return false;
409}
410
Dan Gohman3845e502009-08-12 23:32:33 +0000411/// ParseUnnamedGlobal:
412/// OptionalVisibility ALIAS ...
413/// OptionalLinkage OptionalVisibility ... -> global variable
414/// GlobalID '=' OptionalVisibility ALIAS ...
415/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
416bool LLParser::ParseUnnamedGlobal() {
417 unsigned VarID = NumberedVals.size();
418 std::string Name;
419 LocTy NameLoc = Lex.getLoc();
420
421 // Handle the GlobalID form.
422 if (Lex.getKind() == lltok::GlobalID) {
423 if (Lex.getUIntVal() != VarID)
424 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000425 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000426 Lex.Lex(); // eat GlobalID;
427
428 if (ParseToken(lltok::equal, "expected '=' after name"))
429 return true;
430 }
431
432 bool HasLinkage;
433 unsigned Linkage, Visibility;
434 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
435 ParseOptionalVisibility(Visibility))
436 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Dan Gohman3845e502009-08-12 23:32:33 +0000438 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
439 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
440 return ParseAlias(Name, NameLoc, Visibility);
441}
442
Chris Lattnerdf986172009-01-02 07:01:27 +0000443/// ParseNamedGlobal:
444/// GlobalVar '=' OptionalVisibility ALIAS ...
445/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
446bool LLParser::ParseNamedGlobal() {
447 assert(Lex.getKind() == lltok::GlobalVar);
448 LocTy NameLoc = Lex.getLoc();
449 std::string Name = Lex.getStrVal();
450 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattnerdf986172009-01-02 07:01:27 +0000452 bool HasLinkage;
453 unsigned Linkage, Visibility;
454 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455 ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Chris Lattnerdf986172009-01-02 07:01:27 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Devang Patel256be962009-07-20 19:00:08 +0000464// MDString:
465// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000466bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000467 std::string Str;
468 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000469 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000470 return false;
471}
472
473// MDNode:
474// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000475//
476/// This version of ParseMDNodeID returns the slot number and null in the case
477/// of a forward reference.
478bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
479 // !{ ..., !42, ... }
480 if (ParseUInt32(SlotNo)) return true;
481
482 // Check existing MDNode.
483 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
484 Result = NumberedMetadata[SlotNo];
485 else
486 Result = 0;
487 return false;
488}
489
Chris Lattner4a72efc2009-12-30 04:15:23 +0000490bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000491 // !{ ..., !42, ... }
492 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000493 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000494
Chris Lattner449c3102010-04-01 05:14:45 +0000495 // If not a forward reference, just return it now.
496 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000497
Chris Lattner449c3102010-04-01 05:14:45 +0000498 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000499 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000500 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000501
502 if (NumberedMetadata.size() <= MID)
503 NumberedMetadata.resize(MID+1);
504 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000505 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000506 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000507}
Devang Patel256be962009-07-20 19:00:08 +0000508
Chris Lattner84d03b12009-12-29 22:35:39 +0000509/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000510/// !foo = !{ !1, !2 }
511bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000512 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000513 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000514 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000515
Chris Lattner84d03b12009-12-29 22:35:39 +0000516 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000517 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000518 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000519 return true;
520
Dan Gohman17aa92c2010-07-21 23:38:33 +0000521 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000522 if (Lex.getKind() != lltok::rbrace)
523 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000524 if (ParseToken(lltok::exclaim, "Expected '!' here"))
525 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000526
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000527 MDNode *N = 0;
528 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000529 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000530 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000531
532 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
533 return true;
534
Devang Pateleff2ab62009-07-29 00:34:02 +0000535 return false;
536}
537
Devang Patel923078c2009-07-01 19:21:12 +0000538/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000539/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000540bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000541 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000542 Lex.Lex();
543 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000544
545 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000546 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000547 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000548 if (ParseUInt32(MetadataID) ||
549 ParseToken(lltok::equal, "expected '=' here") ||
550 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000551 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000552 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000553 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000554 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000555 return true;
556
Jay Foadec9186b2011-04-21 19:59:31 +0000557 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000558
559 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000560 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000561 FI = ForwardRefMDNodes.find(MetadataID);
562 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000563 MDNode *Temp = FI->second.first;
564 Temp->replaceAllUsesWith(Init);
565 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000566 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000567
568 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
569 } else {
570 if (MetadataID >= NumberedMetadata.size())
571 NumberedMetadata.resize(MetadataID+1);
572
573 if (NumberedMetadata[MetadataID] != 0)
574 return TokError("Metadata id is already used");
575 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000576 }
577
Devang Patel923078c2009-07-01 19:21:12 +0000578 return false;
579}
580
Chris Lattnerdf986172009-01-02 07:01:27 +0000581/// ParseAlias:
582/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
583/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000584/// ::= TypeAndValue
585/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000586/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000587///
588/// Everything through visibility has already been parsed.
589///
590bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
591 unsigned Visibility) {
592 assert(Lex.getKind() == lltok::kw_alias);
593 Lex.Lex();
594 unsigned Linkage;
595 LocTy LinkageLoc = Lex.getLoc();
596 if (ParseOptionalLinkage(Linkage))
597 return true;
598
599 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000600 Linkage != GlobalValue::WeakAnyLinkage &&
601 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000602 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000603 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000604 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000605 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
606 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000607 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
Chris Lattnerdf986172009-01-02 07:01:27 +0000609 Constant *Aliasee;
610 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000611 if (Lex.getKind() != lltok::kw_bitcast &&
612 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000613 if (ParseGlobalTypeAndValue(Aliasee)) return true;
614 } else {
615 // The bitcast dest type is not present, it is implied by the dest type.
616 ValID ID;
617 if (ParseValID(ID)) return true;
618 if (ID.Kind != ValID::t_Constant)
619 return Error(AliaseeLoc, "invalid aliasee");
620 Aliasee = ID.ConstantVal;
621 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000622
Duncan Sands1df98592010-02-16 11:11:14 +0000623 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000624 return Error(AliaseeLoc, "alias must have pointer type");
625
626 // Okay, create the alias but do not insert it into the module yet.
627 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
628 (GlobalValue::LinkageTypes)Linkage, Name,
629 Aliasee);
630 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000631
Chris Lattnerdf986172009-01-02 07:01:27 +0000632 // See if this value already exists in the symbol table. If so, it is either
633 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000634 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 // See if this was a redefinition. If so, there is no entry in
636 // ForwardRefVals.
637 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
638 I = ForwardRefVals.find(Name);
639 if (I == ForwardRefVals.end())
640 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
641
642 // Otherwise, this was a definition of forward ref. Verify that types
643 // agree.
644 if (Val->getType() != GA->getType())
645 return Error(NameLoc,
646 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000647
Chris Lattnerdf986172009-01-02 07:01:27 +0000648 // If they agree, just RAUW the old value with the alias and remove the
649 // forward ref info.
650 Val->replaceAllUsesWith(GA);
651 Val->eraseFromParent();
652 ForwardRefVals.erase(I);
653 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000654
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 // Insert into the module, we know its name won't collide now.
656 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000657 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000658
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 return false;
660}
661
662/// ParseGlobal
663/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000664/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000665/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000666/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000667///
668/// Everything through visibility has been parsed already.
669///
670bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
671 unsigned Linkage, bool HasLinkage,
672 unsigned Visibility) {
673 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000674 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000675 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000677
Owen Anderson1d0be152009-08-13 21:58:54 +0000678 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000679 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
680 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000681 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
682 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000683 ParseGlobalType(IsConstant) ||
684 ParseType(Ty, TyLoc))
685 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000686
Chris Lattnerdf986172009-01-02 07:01:27 +0000687 // If the linkage is specified and is external, then no initializer is
688 // present.
689 Constant *Init = 0;
690 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000691 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000692 Linkage != GlobalValue::ExternalLinkage)) {
693 if (ParseGlobalValue(Ty, Init))
694 return true;
695 }
696
Duncan Sands1df98592010-02-16 11:11:14 +0000697 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000698 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000699
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 GlobalVariable *GV = 0;
701
702 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000703 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000704 if (GlobalValue *GVal = M->getNamedValue(Name)) {
705 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
706 return Error(NameLoc, "redefinition of global '@" + Name + "'");
707 GV = cast<GlobalVariable>(GVal);
708 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 } else {
710 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
711 I = ForwardRefValIDs.find(NumberedVals.size());
712 if (I != ForwardRefValIDs.end()) {
713 GV = cast<GlobalVariable>(I->second.first);
714 ForwardRefValIDs.erase(I);
715 }
716 }
717
718 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000719 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000720 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000721 } else {
722 if (GV->getType()->getElementType() != Ty)
723 return Error(TyLoc,
724 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000725
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 // Move the forward-reference to the correct spot in the module.
727 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
728 }
729
730 if (Name.empty())
731 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000732
Chris Lattnerdf986172009-01-02 07:01:27 +0000733 // Set the parsed properties on the global.
734 if (Init)
735 GV->setInitializer(Init);
736 GV->setConstant(IsConstant);
737 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
738 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
739 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000740 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000741
Chris Lattnerdf986172009-01-02 07:01:27 +0000742 // Parse attributes on the global.
743 while (Lex.getKind() == lltok::comma) {
744 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000745
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 if (Lex.getKind() == lltok::kw_section) {
747 Lex.Lex();
748 GV->setSection(Lex.getStrVal());
749 if (ParseToken(lltok::StringConstant, "expected global section string"))
750 return true;
751 } else if (Lex.getKind() == lltok::kw_align) {
752 unsigned Alignment;
753 if (ParseOptionalAlignment(Alignment)) return true;
754 GV->setAlignment(Alignment);
755 } else {
756 TokError("unknown global variable property!");
757 }
758 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerdf986172009-01-02 07:01:27 +0000760 return false;
761}
762
763
764//===----------------------------------------------------------------------===//
765// GlobalValue Reference/Resolution Routines.
766//===----------------------------------------------------------------------===//
767
768/// GetGlobalVal - Get a value with the specified name or ID, creating a
769/// forward reference record if needed. This can return null if the value
770/// exists but does not have the right type.
771GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
772 LocTy Loc) {
773 const PointerType *PTy = dyn_cast<PointerType>(Ty);
774 if (PTy == 0) {
775 Error(Loc, "global variable reference must have pointer type");
776 return 0;
777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000778
Chris Lattnerdf986172009-01-02 07:01:27 +0000779 // Look this name up in the normal function symbol table.
780 GlobalValue *Val =
781 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Chris Lattnerdf986172009-01-02 07:01:27 +0000783 // If this is a forward reference for the value, see if we already created a
784 // forward ref record.
785 if (Val == 0) {
786 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
787 I = ForwardRefVals.find(Name);
788 if (I != ForwardRefVals.end())
789 Val = I->second.first;
790 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000791
Chris Lattnerdf986172009-01-02 07:01:27 +0000792 // If we have the value in the symbol table or fwd-ref table, return it.
793 if (Val) {
794 if (Val->getType() == Ty) return Val;
795 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000796 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 return 0;
798 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000799
Chris Lattnerdf986172009-01-02 07:01:27 +0000800 // Otherwise, create a new forward reference for this value and remember it.
801 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000802 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
803 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000804 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000805 Error(Loc, "function may not return opaque type");
806 return 0;
807 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000808
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000809 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000810 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000811 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
812 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000814
Chris Lattnerdf986172009-01-02 07:01:27 +0000815 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
816 return FwdVal;
817}
818
819GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
820 const PointerType *PTy = dyn_cast<PointerType>(Ty);
821 if (PTy == 0) {
822 Error(Loc, "global variable reference must have pointer type");
823 return 0;
824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000825
Chris Lattnerdf986172009-01-02 07:01:27 +0000826 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000827
Chris Lattnerdf986172009-01-02 07:01:27 +0000828 // If this is a forward reference for the value, see if we already created a
829 // forward ref record.
830 if (Val == 0) {
831 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
832 I = ForwardRefValIDs.find(ID);
833 if (I != ForwardRefValIDs.end())
834 Val = I->second.first;
835 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000836
Chris Lattnerdf986172009-01-02 07:01:27 +0000837 // If we have the value in the symbol table or fwd-ref table, return it.
838 if (Val) {
839 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000840 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000841 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000842 return 0;
843 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000844
Chris Lattnerdf986172009-01-02 07:01:27 +0000845 // Otherwise, create a new forward reference for this value and remember it.
846 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000847 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
848 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000849 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000850 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000851 return 0;
852 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000853 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000854 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000855 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
856 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000857 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000858
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
860 return FwdVal;
861}
862
863
864//===----------------------------------------------------------------------===//
865// Helper Routines.
866//===----------------------------------------------------------------------===//
867
868/// ParseToken - If the current token has the specified kind, eat it and return
869/// success. Otherwise, emit the specified error and return failure.
870bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
871 if (Lex.getKind() != T)
872 return TokError(ErrMsg);
873 Lex.Lex();
874 return false;
875}
876
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000877/// ParseStringConstant
878/// ::= StringConstant
879bool LLParser::ParseStringConstant(std::string &Result) {
880 if (Lex.getKind() != lltok::StringConstant)
881 return TokError("expected string constant");
882 Result = Lex.getStrVal();
883 Lex.Lex();
884 return false;
885}
886
887/// ParseUInt32
888/// ::= uint32
889bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000890 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
891 return TokError("expected integer");
892 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
893 if (Val64 != unsigned(Val64))
894 return TokError("expected 32-bit integer (too large)");
895 Val = Val64;
896 Lex.Lex();
897 return false;
898}
899
900
901/// ParseOptionalAddrSpace
902/// := /*empty*/
903/// := 'addrspace' '(' uint32 ')'
904bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
905 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000906 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000907 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000908 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000909 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000911}
Chris Lattnerdf986172009-01-02 07:01:27 +0000912
913/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
914/// indicates what kind of attribute list this is: 0: function arg, 1: result,
915/// 2: function attr.
916bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
917 Attrs = Attribute::None;
918 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000919
Chris Lattnerdf986172009-01-02 07:01:27 +0000920 while (1) {
921 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000922 default: // End of attributes.
923 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
924 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000926 // As a hack, we allow "align 2" on functions as a synonym for
927 // "alignstack 2".
928 if (AttrKind == 2 &&
929 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
930 return Error(AttrLoc, "invalid use of attribute on a function");
931
932 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000934
Chris Lattnerdf986172009-01-02 07:01:27 +0000935 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000936 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
937 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
938 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
939 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
940 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
941 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
942 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
943 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000944
Devang Patel578efa92009-06-05 21:57:13 +0000945 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
946 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000947 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Devang Patel578efa92009-06-05 21:57:13 +0000948 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
949 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
950 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000951 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000952 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
953 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
954 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
955 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
956 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
957 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000958 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000959 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
John McCall3a3465b2011-06-15 20:36:13 +0000960 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000961
Charles Davis1e063d12010-02-12 00:31:15 +0000962 case lltok::kw_alignstack: {
963 unsigned Alignment;
964 if (ParseOptionalStackAlignment(Alignment))
965 return true;
966 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
967 continue;
968 }
969
Chris Lattnerdf986172009-01-02 07:01:27 +0000970 case lltok::kw_align: {
971 unsigned Alignment;
972 if (ParseOptionalAlignment(Alignment))
973 return true;
974 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
975 continue;
976 }
Charles Davis1e063d12010-02-12 00:31:15 +0000977
Chris Lattnerdf986172009-01-02 07:01:27 +0000978 }
979 Lex.Lex();
980 }
981}
982
983/// ParseOptionalLinkage
984/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000985/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000986/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000987/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000988/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000989/// ::= 'internal'
990/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000991/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000992/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000993/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000994/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000995/// ::= 'appending'
996/// ::= 'dllexport'
997/// ::= 'common'
998/// ::= 'dllimport'
999/// ::= 'extern_weak'
1000/// ::= 'external'
1001bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1002 HasLinkage = false;
1003 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001004 default: Res=GlobalValue::ExternalLinkage; return false;
1005 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1006 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001007 case lltok::kw_linker_private_weak:
1008 Res = GlobalValue::LinkerPrivateWeakLinkage;
1009 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001010 case lltok::kw_linker_private_weak_def_auto:
1011 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1012 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001013 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1014 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1015 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1016 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1017 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001018 case lltok::kw_available_externally:
1019 Res = GlobalValue::AvailableExternallyLinkage;
1020 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001021 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1022 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1023 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1024 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1025 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1026 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001027 }
1028 Lex.Lex();
1029 HasLinkage = true;
1030 return false;
1031}
1032
1033/// ParseOptionalVisibility
1034/// ::= /*empty*/
1035/// ::= 'default'
1036/// ::= 'hidden'
1037/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001038///
Chris Lattnerdf986172009-01-02 07:01:27 +00001039bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1040 switch (Lex.getKind()) {
1041 default: Res = GlobalValue::DefaultVisibility; return false;
1042 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1043 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1044 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1045 }
1046 Lex.Lex();
1047 return false;
1048}
1049
1050/// ParseOptionalCallingConv
1051/// ::= /*empty*/
1052/// ::= 'ccc'
1053/// ::= 'fastcc'
1054/// ::= 'coldcc'
1055/// ::= 'x86_stdcallcc'
1056/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001057/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001058/// ::= 'arm_apcscc'
1059/// ::= 'arm_aapcscc'
1060/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001061/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001062/// ::= 'ptx_kernel'
1063/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001064/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001065///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001066bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001067 switch (Lex.getKind()) {
1068 default: CC = CallingConv::C; return false;
1069 case lltok::kw_ccc: CC = CallingConv::C; break;
1070 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1071 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1072 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1073 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001074 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001075 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1076 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1077 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001078 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001079 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1080 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001081 case lltok::kw_cc: {
1082 unsigned ArbitraryCC;
1083 Lex.Lex();
1084 if (ParseUInt32(ArbitraryCC)) {
1085 return true;
1086 } else
1087 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1088 return false;
1089 }
1090 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001092
Chris Lattnerdf986172009-01-02 07:01:27 +00001093 Lex.Lex();
1094 return false;
1095}
1096
Chris Lattnerb8c46862009-12-30 05:31:19 +00001097/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001098/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001099bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1100 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001101 do {
1102 if (Lex.getKind() != lltok::MetadataVar)
1103 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001104
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001105 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001106 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001107 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001108
Chris Lattner442ffa12009-12-29 21:53:55 +00001109 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001110 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001111
1112 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001113 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001114
Dan Gohman68261142010-08-24 14:35:45 +00001115 // This code is similar to that of ParseMetadataValue, however it needs to
1116 // have special-case code for a forward reference; see the comments on
1117 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1118 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001119 if (Lex.getKind() == lltok::lbrace) {
1120 ValID ID;
1121 if (ParseMetadataListValue(ID, PFS))
1122 return true;
1123 assert(ID.Kind == ValID::t_MDNode);
1124 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001125 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001126 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001127 if (ParseMDNodeID(Node, NodeID))
1128 return true;
1129 if (Node) {
1130 // If we got the node, add it to the instruction.
1131 Inst->setMetadata(MDK, Node);
1132 } else {
1133 MDRef R = { Loc, MDK, NodeID };
1134 // Otherwise, remember that this should be resolved later.
1135 ForwardRefInstMetadata[Inst].push_back(R);
1136 }
Chris Lattner449c3102010-04-01 05:14:45 +00001137 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001138
1139 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001140 } while (EatIfPresent(lltok::comma));
1141 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001142}
1143
Chris Lattnerdf986172009-01-02 07:01:27 +00001144/// ParseOptionalAlignment
1145/// ::= /* empty */
1146/// ::= 'align' 4
1147bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1148 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001149 if (!EatIfPresent(lltok::kw_align))
1150 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001151 LocTy AlignLoc = Lex.getLoc();
1152 if (ParseUInt32(Alignment)) return true;
1153 if (!isPowerOf2_32(Alignment))
1154 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001155 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001156 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001157 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001158}
1159
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001160/// ParseOptionalCommaAlign
1161/// ::=
1162/// ::= ',' align 4
1163///
1164/// This returns with AteExtraComma set to true if it ate an excess comma at the
1165/// end.
1166bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1167 bool &AteExtraComma) {
1168 AteExtraComma = false;
1169 while (EatIfPresent(lltok::comma)) {
1170 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001171 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001172 AteExtraComma = true;
1173 return false;
1174 }
1175
Chris Lattner093eed12010-04-23 00:50:50 +00001176 if (Lex.getKind() != lltok::kw_align)
1177 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001178
Chris Lattner093eed12010-04-23 00:50:50 +00001179 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Devang Patelf633a062009-09-17 23:04:48 +00001182 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001183}
1184
Charles Davis1e063d12010-02-12 00:31:15 +00001185/// ParseOptionalStackAlignment
1186/// ::= /* empty */
1187/// ::= 'alignstack' '(' 4 ')'
1188bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1189 Alignment = 0;
1190 if (!EatIfPresent(lltok::kw_alignstack))
1191 return false;
1192 LocTy ParenLoc = Lex.getLoc();
1193 if (!EatIfPresent(lltok::lparen))
1194 return Error(ParenLoc, "expected '('");
1195 LocTy AlignLoc = Lex.getLoc();
1196 if (ParseUInt32(Alignment)) return true;
1197 ParenLoc = Lex.getLoc();
1198 if (!EatIfPresent(lltok::rparen))
1199 return Error(ParenLoc, "expected ')'");
1200 if (!isPowerOf2_32(Alignment))
1201 return Error(AlignLoc, "stack alignment is not a power of two");
1202 return false;
1203}
Devang Patelf633a062009-09-17 23:04:48 +00001204
Chris Lattner628c13a2009-12-30 05:14:00 +00001205/// ParseIndexList - This parses the index list for an insert/extractvalue
1206/// instruction. This sets AteExtraComma in the case where we eat an extra
1207/// comma at the end of the line and find that it is followed by metadata.
1208/// Clients that don't allow metadata can call the version of this function that
1209/// only takes one argument.
1210///
Chris Lattnerdf986172009-01-02 07:01:27 +00001211/// ParseIndexList
1212/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001213///
1214bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1215 bool &AteExtraComma) {
1216 AteExtraComma = false;
1217
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 if (Lex.getKind() != lltok::comma)
1219 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001220
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001221 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001222 if (Lex.getKind() == lltok::MetadataVar) {
1223 AteExtraComma = true;
1224 return false;
1225 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001226 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001227 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001228 Indices.push_back(Idx);
1229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001230
Chris Lattnerdf986172009-01-02 07:01:27 +00001231 return false;
1232}
1233
1234//===----------------------------------------------------------------------===//
1235// Type Parsing.
1236//===----------------------------------------------------------------------===//
1237
1238/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001239bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1240 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001242
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 // Verify no unresolved uprefs.
1244 if (!UpRefs.empty())
1245 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001247 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001248 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001249
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 return false;
1251}
1252
1253/// HandleUpRefs - Every time we finish a new layer of types, this function is
1254/// called. It loops through the UpRefs vector, which is a list of the
1255/// currently active types. For each type, if the up-reference is contained in
1256/// the newly completed type, we decrement the level count. When the level
1257/// count reaches zero, the up-referenced type is the type that is passed in:
1258/// thus we can complete the cycle.
1259///
1260PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1261 // If Ty isn't abstract, or if there are no up-references in it, then there is
1262 // nothing to resolve here.
1263 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001264
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 PATypeHolder Ty(ty);
1266#if 0
Chris Lattner0cd0d882011-06-18 21:18:23 +00001267 dbgs() << "Type '" << *Ty
Chris Lattnerdf986172009-01-02 07:01:27 +00001268 << "' newly formed. Resolving upreferences.\n"
1269 << UpRefs.size() << " upreferences active!\n";
1270#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1273 // to zero), we resolve them all together before we resolve them to Ty. At
1274 // the end of the loop, if there is anything to resolve to Ty, it will be in
1275 // this variable.
1276 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Chris Lattnerdf986172009-01-02 07:01:27 +00001278 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1279 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1280 bool ContainsType =
1281 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1282 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001283
Chris Lattnerdf986172009-01-02 07:01:27 +00001284#if 0
Chris Lattner0cd0d882011-06-18 21:18:23 +00001285 dbgs() << " UR#" << i << " - TypeContains(" << *Ty << ", "
1286 << *UpRefs[i].LastContainedTy << ") = "
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 << (ContainsType ? "true" : "false")
1288 << " level=" << UpRefs[i].NestingLevel << "\n";
1289#endif
1290 if (!ContainsType)
1291 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001292
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 // Decrement level of upreference
1294 unsigned Level = --UpRefs[i].NestingLevel;
1295 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001296
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1298 if (Level != 0)
1299 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001300
Chris Lattnerdf986172009-01-02 07:01:27 +00001301#if 0
David Greene0e28d762009-12-23 23:38:28 +00001302 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001303#endif
1304 if (!TypeToResolve)
1305 TypeToResolve = UpRefs[i].UpRefTy;
1306 else
1307 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1308 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1309 --i; // Do not skip the next element.
1310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 if (TypeToResolve)
1313 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001314
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 return Ty;
1316}
1317
1318
1319/// ParseTypeRec - The recursive function used to process the internal
1320/// implementation details of types.
1321bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1322 switch (Lex.getKind()) {
1323 default:
1324 return TokError("expected type");
1325 case lltok::Type:
1326 // TypeRec ::= 'float' | 'void' (etc)
1327 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001328 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 break;
1330 case lltok::kw_opaque:
1331 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001332 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001333 Lex.Lex();
1334 break;
1335 case lltok::lbrace:
1336 // TypeRec ::= '{' ... '}'
1337 if (ParseStructType(Result, false))
1338 return true;
1339 break;
1340 case lltok::lsquare:
1341 // TypeRec ::= '[' ... ']'
1342 Lex.Lex(); // eat the lsquare.
1343 if (ParseArrayVectorType(Result, false))
1344 return true;
1345 break;
1346 case lltok::less: // Either vector or packed struct.
1347 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001348 Lex.Lex();
1349 if (Lex.getKind() == lltok::lbrace) {
1350 if (ParseStructType(Result, true) ||
1351 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 } else if (ParseArrayVectorType(Result, true))
1354 return true;
1355 break;
1356 case lltok::LocalVar:
Chris Lattnerdf986172009-01-02 07:01:27 +00001357 // TypeRec ::= %foo
1358 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1359 Result = T;
1360 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001361 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1363 std::make_pair(Result,
1364 Lex.getLoc())));
1365 M->addTypeName(Lex.getStrVal(), Result.get());
1366 }
1367 Lex.Lex();
1368 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001369
Chris Lattnerdf986172009-01-02 07:01:27 +00001370 case lltok::LocalVarID:
1371 // TypeRec ::= %4
1372 if (Lex.getUIntVal() < NumberedTypes.size())
1373 Result = NumberedTypes[Lex.getUIntVal()];
1374 else {
1375 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1376 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1377 if (I != ForwardRefTypeIDs.end())
1378 Result = I->second.first;
1379 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001380 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001381 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1382 std::make_pair(Result,
1383 Lex.getLoc())));
1384 }
1385 }
1386 Lex.Lex();
1387 break;
1388 case lltok::backslash: {
1389 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001391 unsigned Val;
1392 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001393 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1395 Result = OT;
1396 break;
1397 }
1398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
1400 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 while (1) {
1402 switch (Lex.getKind()) {
1403 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001405
1406 // TypeRec ::= TypeRec '*'
1407 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001408 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001409 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001410 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001411 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001412 if (!PointerType::isValidElementType(Result.get()))
1413 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001414 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 Lex.Lex();
1416 break;
1417
1418 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1419 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001420 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001422 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001423 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001424 if (!PointerType::isValidElementType(Result.get()))
1425 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 unsigned AddrSpace;
1427 if (ParseOptionalAddrSpace(AddrSpace) ||
1428 ParseToken(lltok::star, "expected '*' in address space"))
1429 return true;
1430
Owen Andersondebcb012009-07-29 22:17:13 +00001431 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 break;
1433 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001434
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1436 case lltok::lparen:
1437 if (ParseFunctionType(Result))
1438 return true;
1439 break;
1440 }
1441 }
1442}
1443
1444/// ParseParameterList
1445/// ::= '(' ')'
1446/// ::= '(' Arg (',' Arg)* ')'
1447/// Arg
1448/// ::= Type OptionalAttributes Value OptionalAttributes
1449bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1450 PerFunctionState &PFS) {
1451 if (ParseToken(lltok::lparen, "expected '(' in call"))
1452 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001453
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 while (Lex.getKind() != lltok::rparen) {
1455 // If this isn't the first argument, we need a comma.
1456 if (!ArgList.empty() &&
1457 ParseToken(lltok::comma, "expected ',' in argument list"))
1458 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 // Parse the argument.
1461 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001462 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001463 unsigned ArgAttrs1 = Attribute::None;
1464 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001465 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001466 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001467 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001468
Chris Lattner287881d2009-12-30 02:11:14 +00001469 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001470 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001471 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001472 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1473 }
1474
1475 Lex.Lex(); // Lex the ')'.
1476 return false;
1477}
1478
1479
1480
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001481/// ParseArgumentList - Parse the argument list for a function type or function
1482/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001483/// ::= '(' ArgTypeListI ')'
1484/// ArgTypeListI
1485/// ::= /*empty*/
1486/// ::= '...'
1487/// ::= ArgTypeList ',' '...'
1488/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001489///
Chris Lattnerdf986172009-01-02 07:01:27 +00001490bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001491 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 isVarArg = false;
1493 assert(Lex.getKind() == lltok::lparen);
1494 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001495
Chris Lattnerdf986172009-01-02 07:01:27 +00001496 if (Lex.getKind() == lltok::rparen) {
1497 // empty
1498 } else if (Lex.getKind() == lltok::dotdotdot) {
1499 isVarArg = true;
1500 Lex.Lex();
1501 } else {
1502 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001503 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001505 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001507 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1508 // types (such as a function returning a pointer to itself). If parsing a
1509 // function prototype, we require fully resolved types.
1510 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001511 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001513 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001514 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001515
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001516 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001517 Name = Lex.getStrVal();
1518 Lex.Lex();
1519 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001520
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001521 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001522 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001528 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001529 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001530 break;
1531 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001532
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 // Otherwise must be an argument type.
1534 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001535 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001536 ParseOptionalAttrs(Attrs, 0)) return true;
1537
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001538 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001539 return Error(TypeLoc, "argument can not have void type");
1540
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001541 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 Name = Lex.getStrVal();
1543 Lex.Lex();
1544 } else {
1545 Name = "";
1546 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001547
Duncan Sands47c51882010-02-16 14:50:09 +00001548 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Chris Lattnerdf986172009-01-02 07:01:27 +00001551 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1552 }
1553 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001554
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001555 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001556}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001557
Chris Lattnerdf986172009-01-02 07:01:27 +00001558/// ParseFunctionType
1559/// ::= Type ArgumentList OptionalAttrs
1560bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1561 assert(Lex.getKind() == lltok::lparen);
1562
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001563 if (!FunctionType::isValidReturnType(Result))
1564 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001565
Chris Lattnerdf986172009-01-02 07:01:27 +00001566 std::vector<ArgInfo> ArgList;
1567 bool isVarArg;
Chris Lattnera16546a2011-06-17 17:37:13 +00001568 if (ParseArgumentList(ArgList, isVarArg, true))
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001570
Chris Lattnerdf986172009-01-02 07:01:27 +00001571 // Reject names on the arguments lists.
1572 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1573 if (!ArgList[i].Name.empty())
1574 return Error(ArgList[i].Loc, "argument name invalid in function type");
Chris Lattnera16546a2011-06-17 17:37:13 +00001575 if (ArgList[i].Attrs != 0)
1576 return Error(ArgList[i].Loc,
1577 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001578 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 std::vector<const Type*> ArgListTy;
1581 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1582 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Owen Andersondebcb012009-07-29 22:17:13 +00001584 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001585 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001586 return false;
1587}
1588
1589/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1590/// TypeRec
1591/// ::= '{' '}'
1592/// ::= '{' TypeRec (',' TypeRec)* '}'
1593/// ::= '<' '{' '}' '>'
1594/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1595bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1596 assert(Lex.getKind() == lltok::lbrace);
1597 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001598
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001599 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001600 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 return false;
1602 }
1603
1604 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001605 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001606 if (ParseTypeRec(Result)) return true;
1607 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001608
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001609 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001610 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001611 if (!StructType::isValidElementType(Result))
1612 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001614 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001615 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001618 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001619 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001620 if (!StructType::isValidElementType(Result))
1621 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 ParamsList.push_back(Result);
1624 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001625
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001626 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1627 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattnerdf986172009-01-02 07:01:27 +00001629 std::vector<const Type*> ParamsListTy;
1630 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1631 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001632 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001633 return false;
1634}
1635
1636/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1637/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001639/// ::= '[' APSINTVAL 'x' Types ']'
1640/// ::= '<' APSINTVAL 'x' Types '>'
1641bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1642 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1643 Lex.getAPSIntVal().getBitWidth() > 64)
1644 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001645
Chris Lattnerdf986172009-01-02 07:01:27 +00001646 LocTy SizeLoc = Lex.getLoc();
1647 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001648 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001650 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1651 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001652
1653 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001654 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001655 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001657 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001658 return Error(TypeLoc, "array and vector element type cannot be void");
1659
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001660 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1661 "expected end of sequential type"))
1662 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001665 if (Size == 0)
1666 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001667 if ((unsigned)Size != Size)
1668 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001669 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001671 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001672 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001673 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001674 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001675 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001676 }
1677 return false;
1678}
1679
1680//===----------------------------------------------------------------------===//
1681// Function Semantic Analysis.
1682//===----------------------------------------------------------------------===//
1683
Chris Lattner09d9ef42009-10-28 03:39:23 +00001684LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1685 int functionNumber)
1686 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001687
1688 // Insert unnamed arguments into the NumberedVals list.
1689 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1690 AI != E; ++AI)
1691 if (!AI->hasName())
1692 NumberedVals.push_back(AI);
1693}
1694
1695LLParser::PerFunctionState::~PerFunctionState() {
1696 // If there were any forward referenced non-basicblock values, delete them.
1697 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1698 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1699 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001700 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001701 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 delete I->second.first;
1703 I->second.first = 0;
1704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1707 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1708 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001709 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001710 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 delete I->second.first;
1712 I->second.first = 0;
1713 }
1714}
1715
Chris Lattner09d9ef42009-10-28 03:39:23 +00001716bool LLParser::PerFunctionState::FinishFunction() {
1717 // Check to see if someone took the address of labels in this block.
1718 if (!P.ForwardRefBlockAddresses.empty()) {
1719 ValID FunctionID;
1720 if (!F.getName().empty()) {
1721 FunctionID.Kind = ValID::t_GlobalName;
1722 FunctionID.StrVal = F.getName();
1723 } else {
1724 FunctionID.Kind = ValID::t_GlobalID;
1725 FunctionID.UIntVal = FunctionNumber;
1726 }
1727
1728 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1729 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1730 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1731 // Resolve all these references.
1732 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1733 return true;
1734
1735 P.ForwardRefBlockAddresses.erase(FRBAI);
1736 }
1737 }
1738
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 if (!ForwardRefVals.empty())
1740 return P.Error(ForwardRefVals.begin()->second.second,
1741 "use of undefined value '%" + ForwardRefVals.begin()->first +
1742 "'");
1743 if (!ForwardRefValIDs.empty())
1744 return P.Error(ForwardRefValIDs.begin()->second.second,
1745 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001746 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 return false;
1748}
1749
1750
1751/// GetVal - Get a value with the specified name or ID, creating a
1752/// forward reference record if needed. This can return null if the value
1753/// exists but does not have the right type.
1754Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1755 const Type *Ty, LocTy Loc) {
1756 // Look this name up in the normal function symbol table.
1757 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001758
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 // If this is a forward reference for the value, see if we already created a
1760 // forward ref record.
1761 if (Val == 0) {
1762 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1763 I = ForwardRefVals.find(Name);
1764 if (I != ForwardRefVals.end())
1765 Val = I->second.first;
1766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001767
Chris Lattnerdf986172009-01-02 07:01:27 +00001768 // If we have the value in the symbol table or fwd-ref table, return it.
1769 if (Val) {
1770 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001771 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 P.Error(Loc, "'%" + Name + "' is not a basic block");
1773 else
1774 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001775 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001776 return 0;
1777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001778
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001780 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 P.Error(Loc, "invalid use of a non-first-class type");
1782 return 0;
1783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 // Otherwise, create a new forward reference for this value and remember it.
1786 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001787 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001788 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 else
1790 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001791
Chris Lattnerdf986172009-01-02 07:01:27 +00001792 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1793 return FwdVal;
1794}
1795
1796Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1797 LocTy Loc) {
1798 // Look this name up in the normal function symbol table.
1799 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001800
Chris Lattnerdf986172009-01-02 07:01:27 +00001801 // If this is a forward reference for the value, see if we already created a
1802 // forward ref record.
1803 if (Val == 0) {
1804 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1805 I = ForwardRefValIDs.find(ID);
1806 if (I != ForwardRefValIDs.end())
1807 Val = I->second.first;
1808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001809
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 // If we have the value in the symbol table or fwd-ref table, return it.
1811 if (Val) {
1812 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001813 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001814 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001816 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001817 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001818 return 0;
1819 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001820
Duncan Sands47c51882010-02-16 14:50:09 +00001821 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 P.Error(Loc, "invalid use of a non-first-class type");
1823 return 0;
1824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 // Otherwise, create a new forward reference for this value and remember it.
1827 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001828 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001829 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 else
1831 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001832
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1834 return FwdVal;
1835}
1836
1837/// SetInstName - After an instruction is parsed and inserted into its
1838/// basic block, this installs its name.
1839bool LLParser::PerFunctionState::SetInstName(int NameID,
1840 const std::string &NameStr,
1841 LocTy NameLoc, Instruction *Inst) {
1842 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001843 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001844 if (NameID != -1 || !NameStr.empty())
1845 return P.Error(NameLoc, "instructions returning void cannot have a name");
1846 return false;
1847 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 // If this was a numbered instruction, verify that the instruction is the
1850 // expected value and resolve any forward references.
1851 if (NameStr.empty()) {
1852 // If neither a name nor an ID was specified, just use the next ID.
1853 if (NameID == -1)
1854 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001855
Chris Lattnerdf986172009-01-02 07:01:27 +00001856 if (unsigned(NameID) != NumberedVals.size())
1857 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001858 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1861 ForwardRefValIDs.find(NameID);
1862 if (FI != ForwardRefValIDs.end()) {
1863 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001864 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001865 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001866 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001867 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 ForwardRefValIDs.erase(FI);
1869 }
1870
1871 NumberedVals.push_back(Inst);
1872 return false;
1873 }
1874
1875 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1876 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1877 FI = ForwardRefVals.find(NameStr);
1878 if (FI != ForwardRefVals.end()) {
1879 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001880 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001881 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001883 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 ForwardRefVals.erase(FI);
1885 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 // Set the name on the instruction.
1888 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001889
Benjamin Krameraf812352010-10-16 11:28:23 +00001890 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001891 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 NameStr + "'");
1893 return false;
1894}
1895
1896/// GetBB - Get a basic block with the specified name or ID, creating a
1897/// forward reference record if needed.
1898BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1899 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001900 return cast_or_null<BasicBlock>(GetVal(Name,
1901 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001902}
1903
1904BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001905 return cast_or_null<BasicBlock>(GetVal(ID,
1906 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001907}
1908
1909/// DefineBB - Define the specified basic block, which is either named or
1910/// unnamed. If there is an error, this returns null otherwise it returns
1911/// the block being defined.
1912BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1913 LocTy Loc) {
1914 BasicBlock *BB;
1915 if (Name.empty())
1916 BB = GetBB(NumberedVals.size(), Loc);
1917 else
1918 BB = GetBB(Name, Loc);
1919 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 // Move the block to the end of the function. Forward ref'd blocks are
1922 // inserted wherever they happen to be referenced.
1923 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 // Remove the block from forward ref sets.
1926 if (Name.empty()) {
1927 ForwardRefValIDs.erase(NumberedVals.size());
1928 NumberedVals.push_back(BB);
1929 } else {
1930 // BB forward references are already in the function symbol table.
1931 ForwardRefVals.erase(Name);
1932 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001933
Chris Lattnerdf986172009-01-02 07:01:27 +00001934 return BB;
1935}
1936
1937//===----------------------------------------------------------------------===//
1938// Constants.
1939//===----------------------------------------------------------------------===//
1940
1941/// ParseValID - Parse an abstract value that doesn't necessarily have a
1942/// type implied. For example, if we parse "4" we don't know what integer type
1943/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001944/// sanity. PFS is used to convert function-local operands of metadata (since
1945/// metadata operands are not just parsed here but also converted to values).
1946/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001947bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001948 ID.Loc = Lex.getLoc();
1949 switch (Lex.getKind()) {
1950 default: return TokError("expected value token");
1951 case lltok::GlobalID: // @42
1952 ID.UIntVal = Lex.getUIntVal();
1953 ID.Kind = ValID::t_GlobalID;
1954 break;
1955 case lltok::GlobalVar: // @foo
1956 ID.StrVal = Lex.getStrVal();
1957 ID.Kind = ValID::t_GlobalName;
1958 break;
1959 case lltok::LocalVarID: // %42
1960 ID.UIntVal = Lex.getUIntVal();
1961 ID.Kind = ValID::t_LocalID;
1962 break;
1963 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 ID.StrVal = Lex.getStrVal();
1965 ID.Kind = ValID::t_LocalName;
1966 break;
Dan Gohman83448032010-07-14 18:26:50 +00001967 case lltok::exclaim: // !42, !{...}, or !"foo"
1968 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 ID.Kind = ValID::t_APSInt;
1972 break;
1973 case lltok::APFloat:
1974 ID.APFloatVal = Lex.getAPFloatVal();
1975 ID.Kind = ValID::t_APFloat;
1976 break;
1977 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001978 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 ID.Kind = ValID::t_Constant;
1980 break;
1981 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001982 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 ID.Kind = ValID::t_Constant;
1984 break;
1985 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1986 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1987 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 case lltok::lbrace: {
1990 // ValID ::= '{' ConstVector '}'
1991 Lex.Lex();
1992 SmallVector<Constant*, 16> Elts;
1993 if (ParseGlobalValueVector(Elts) ||
1994 ParseToken(lltok::rbrace, "expected end of struct constant"))
1995 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001996
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001997 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1998 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 ID.Kind = ValID::t_Constant;
2000 return false;
2001 }
2002 case lltok::less: {
2003 // ValID ::= '<' ConstVector '>' --> Vector.
2004 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2005 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002006 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002007
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 SmallVector<Constant*, 16> Elts;
2009 LocTy FirstEltLoc = Lex.getLoc();
2010 if (ParseGlobalValueVector(Elts) ||
2011 (isPackedStruct &&
2012 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2013 ParseToken(lltok::greater, "expected end of constant"))
2014 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002015
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002017 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002018 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 ID.Kind = ValID::t_Constant;
2020 return false;
2021 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 if (Elts.empty())
2024 return Error(ID.Loc, "constant vector must not be empty");
2025
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002026 if (!Elts[0]->getType()->isIntegerTy() &&
2027 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002028 return Error(FirstEltLoc,
2029 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002030
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 // Verify that all the vector elements have the same type.
2032 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2033 if (Elts[i]->getType() != Elts[0]->getType())
2034 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002035 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002036 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002037
Chris Lattner2ca5c862011-02-15 00:14:00 +00002038 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 ID.Kind = ValID::t_Constant;
2040 return false;
2041 }
2042 case lltok::lsquare: { // Array Constant
2043 Lex.Lex();
2044 SmallVector<Constant*, 16> Elts;
2045 LocTy FirstEltLoc = Lex.getLoc();
2046 if (ParseGlobalValueVector(Elts) ||
2047 ParseToken(lltok::rsquare, "expected end of array constant"))
2048 return true;
2049
2050 // Handle empty element.
2051 if (Elts.empty()) {
2052 // Use undef instead of an array because it's inconvenient to determine
2053 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002054 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 return false;
2056 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002057
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002059 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002060 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Owen Andersondebcb012009-07-29 22:17:13 +00002062 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002063
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002065 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 if (Elts[i]->getType() != Elts[0]->getType())
2067 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002068 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002069 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002070 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002071
Owen Anderson1fd70962009-07-28 18:32:17 +00002072 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 ID.Kind = ValID::t_Constant;
2074 return false;
2075 }
2076 case lltok::kw_c: // c "foo"
2077 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002078 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2080 ID.Kind = ValID::t_Constant;
2081 return false;
2082
2083 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002084 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2085 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 Lex.Lex();
2087 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002088 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002089 ParseStringConstant(ID.StrVal) ||
2090 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 ParseToken(lltok::StringConstant, "expected constraint string"))
2092 return true;
2093 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002094 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 ID.Kind = ValID::t_InlineAsm;
2096 return false;
2097 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098
Chris Lattner09d9ef42009-10-28 03:39:23 +00002099 case lltok::kw_blockaddress: {
2100 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2101 Lex.Lex();
2102
2103 ValID Fn, Label;
2104 LocTy FnLoc, LabelLoc;
2105
2106 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2107 ParseValID(Fn) ||
2108 ParseToken(lltok::comma, "expected comma in block address expression")||
2109 ParseValID(Label) ||
2110 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2111 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002112
Chris Lattner09d9ef42009-10-28 03:39:23 +00002113 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2114 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002115 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002116 return Error(Label.Loc, "expected basic block name in blockaddress");
2117
2118 // Make a global variable as a placeholder for this reference.
2119 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2120 false, GlobalValue::InternalLinkage,
2121 0, "");
2122 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2123 ID.ConstantVal = FwdRef;
2124 ID.Kind = ValID::t_Constant;
2125 return false;
2126 }
2127
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 case lltok::kw_trunc:
2129 case lltok::kw_zext:
2130 case lltok::kw_sext:
2131 case lltok::kw_fptrunc:
2132 case lltok::kw_fpext:
2133 case lltok::kw_bitcast:
2134 case lltok::kw_uitofp:
2135 case lltok::kw_sitofp:
2136 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002141 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 Constant *SrcVal;
2143 Lex.Lex();
2144 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2145 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002146 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 ParseType(DestTy) ||
2148 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2149 return true;
2150 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2151 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002152 getTypeString(SrcVal->getType()) + "' to '" +
2153 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002154 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002155 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 ID.Kind = ValID::t_Constant;
2157 return false;
2158 }
2159 case lltok::kw_extractvalue: {
2160 Lex.Lex();
2161 Constant *Val;
2162 SmallVector<unsigned, 4> Indices;
2163 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2164 ParseGlobalTypeAndValue(Val) ||
2165 ParseIndexList(Indices) ||
2166 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2167 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002168
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002169 if (!Val->getType()->isAggregateType())
2170 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2172 Indices.end()))
2173 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002174 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002175 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 ID.Kind = ValID::t_Constant;
2177 return false;
2178 }
2179 case lltok::kw_insertvalue: {
2180 Lex.Lex();
2181 Constant *Val0, *Val1;
2182 SmallVector<unsigned, 4> Indices;
2183 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2184 ParseGlobalTypeAndValue(Val0) ||
2185 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2186 ParseGlobalTypeAndValue(Val1) ||
2187 ParseIndexList(Indices) ||
2188 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2189 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002190 if (!Val0->getType()->isAggregateType())
2191 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2193 Indices.end()))
2194 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002195 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002196 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 ID.Kind = ValID::t_Constant;
2198 return false;
2199 }
2200 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002201 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002202 unsigned PredVal, Opc = Lex.getUIntVal();
2203 Constant *Val0, *Val1;
2204 Lex.Lex();
2205 if (ParseCmpPredicate(PredVal, Opc) ||
2206 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2207 ParseGlobalTypeAndValue(Val0) ||
2208 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2209 ParseGlobalTypeAndValue(Val1) ||
2210 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2211 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002212
Chris Lattnerdf986172009-01-02 07:01:27 +00002213 if (Val0->getType() != Val1->getType())
2214 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002215
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002219 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002221 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002222 } else {
2223 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002224 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002225 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002226 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002227 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 }
2229 ID.Kind = ValID::t_Constant;
2230 return false;
2231 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002232
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 // Binary Operators.
2234 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002235 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002237 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002238 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002239 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 case lltok::kw_udiv:
2241 case lltok::kw_sdiv:
2242 case lltok::kw_fdiv:
2243 case lltok::kw_urem:
2244 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002245 case lltok::kw_frem:
2246 case lltok::kw_shl:
2247 case lltok::kw_lshr:
2248 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002249 bool NUW = false;
2250 bool NSW = false;
2251 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 unsigned Opc = Lex.getUIntVal();
2253 Constant *Val0, *Val1;
2254 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002255 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002256 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2257 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002258 if (EatIfPresent(lltok::kw_nuw))
2259 NUW = true;
2260 if (EatIfPresent(lltok::kw_nsw)) {
2261 NSW = true;
2262 if (EatIfPresent(lltok::kw_nuw))
2263 NUW = true;
2264 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002265 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2266 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002267 if (EatIfPresent(lltok::kw_exact))
2268 Exact = true;
2269 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2271 ParseGlobalTypeAndValue(Val0) ||
2272 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2273 ParseGlobalTypeAndValue(Val1) ||
2274 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2275 return true;
2276 if (Val0->getType() != Val1->getType())
2277 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002278 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002279 if (NUW)
2280 return Error(ModifierLoc, "nuw only applies to integer operations");
2281 if (NSW)
2282 return Error(ModifierLoc, "nsw only applies to integer operations");
2283 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002284 // Check that the type is valid for the operator.
2285 switch (Opc) {
2286 case Instruction::Add:
2287 case Instruction::Sub:
2288 case Instruction::Mul:
2289 case Instruction::UDiv:
2290 case Instruction::SDiv:
2291 case Instruction::URem:
2292 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002293 case Instruction::Shl:
2294 case Instruction::AShr:
2295 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002296 if (!Val0->getType()->isIntOrIntVectorTy())
2297 return Error(ID.Loc, "constexpr requires integer operands");
2298 break;
2299 case Instruction::FAdd:
2300 case Instruction::FSub:
2301 case Instruction::FMul:
2302 case Instruction::FDiv:
2303 case Instruction::FRem:
2304 if (!Val0->getType()->isFPOrFPVectorTy())
2305 return Error(ID.Loc, "constexpr requires fp operands");
2306 break;
2307 default: llvm_unreachable("Unknown binary operator!");
2308 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002309 unsigned Flags = 0;
2310 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2311 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002312 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002313 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002314 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002315 ID.Kind = ValID::t_Constant;
2316 return false;
2317 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002318
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002320 case lltok::kw_and:
2321 case lltok::kw_or:
2322 case lltok::kw_xor: {
2323 unsigned Opc = Lex.getUIntVal();
2324 Constant *Val0, *Val1;
2325 Lex.Lex();
2326 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2327 ParseGlobalTypeAndValue(Val0) ||
2328 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2329 ParseGlobalTypeAndValue(Val1) ||
2330 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2331 return true;
2332 if (Val0->getType() != Val1->getType())
2333 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002334 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 return Error(ID.Loc,
2336 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002337 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002338 ID.Kind = ValID::t_Constant;
2339 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002340 }
2341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 case lltok::kw_getelementptr:
2343 case lltok::kw_shufflevector:
2344 case lltok::kw_insertelement:
2345 case lltok::kw_extractelement:
2346 case lltok::kw_select: {
2347 unsigned Opc = Lex.getUIntVal();
2348 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002349 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002351 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002352 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002353 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2354 ParseGlobalValueVector(Elts) ||
2355 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2356 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002357
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002359 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002360 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361
Chris Lattnerdf986172009-01-02 07:01:27 +00002362 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002363 (Value**)(Elts.data() + 1),
2364 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002366 ID.ConstantVal = InBounds ?
2367 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2368 Elts.data() + 1,
2369 Elts.size() - 1) :
2370 ConstantExpr::getGetElementPtr(Elts[0],
2371 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 } else if (Opc == Instruction::Select) {
2373 if (Elts.size() != 3)
2374 return Error(ID.Loc, "expected three operands to select");
2375 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2376 Elts[2]))
2377 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002378 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002379 } else if (Opc == Instruction::ShuffleVector) {
2380 if (Elts.size() != 3)
2381 return Error(ID.Loc, "expected three operands to shufflevector");
2382 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2383 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002384 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002385 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 } else if (Opc == Instruction::ExtractElement) {
2387 if (Elts.size() != 2)
2388 return Error(ID.Loc, "expected two operands to extractelement");
2389 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2390 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002391 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 } else {
2393 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2394 if (Elts.size() != 3)
2395 return Error(ID.Loc, "expected three operands to insertelement");
2396 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2397 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002398 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002399 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002401
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 ID.Kind = ValID::t_Constant;
2403 return false;
2404 }
2405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 Lex.Lex();
2408 return false;
2409}
2410
2411/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002412bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2413 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002415 Value *V = NULL;
2416 bool Parsed = ParseValID(ID) ||
2417 ConvertValIDToValue(Ty, ID, V, NULL);
2418 if (V && !(C = dyn_cast<Constant>(V)))
2419 return Error(ID.Loc, "global values must be constants");
2420 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002421}
2422
Victor Hernandez92f238d2010-01-11 22:31:58 +00002423bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2424 PATypeHolder Type(Type::getVoidTy(Context));
2425 return ParseType(Type) ||
2426 ParseGlobalValue(Type, V);
2427}
2428
2429/// ParseGlobalValueVector
2430/// ::= /*empty*/
2431/// ::= TypeAndValue (',' TypeAndValue)*
2432bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2433 // Empty list.
2434 if (Lex.getKind() == lltok::rbrace ||
2435 Lex.getKind() == lltok::rsquare ||
2436 Lex.getKind() == lltok::greater ||
2437 Lex.getKind() == lltok::rparen)
2438 return false;
2439
2440 Constant *C;
2441 if (ParseGlobalTypeAndValue(C)) return true;
2442 Elts.push_back(C);
2443
2444 while (EatIfPresent(lltok::comma)) {
2445 if (ParseGlobalTypeAndValue(C)) return true;
2446 Elts.push_back(C);
2447 }
2448
2449 return false;
2450}
2451
Dan Gohman309b3af2010-08-24 02:24:03 +00002452bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2453 assert(Lex.getKind() == lltok::lbrace);
2454 Lex.Lex();
2455
2456 SmallVector<Value*, 16> Elts;
2457 if (ParseMDNodeVector(Elts, PFS) ||
2458 ParseToken(lltok::rbrace, "expected end of metadata node"))
2459 return true;
2460
Jay Foadec9186b2011-04-21 19:59:31 +00002461 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002462 ID.Kind = ValID::t_MDNode;
2463 return false;
2464}
2465
Dan Gohman83448032010-07-14 18:26:50 +00002466/// ParseMetadataValue
2467/// ::= !42
2468/// ::= !{...}
2469/// ::= !"string"
2470bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2471 assert(Lex.getKind() == lltok::exclaim);
2472 Lex.Lex();
2473
2474 // MDNode:
2475 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002476 if (Lex.getKind() == lltok::lbrace)
2477 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002478
2479 // Standalone metadata reference
2480 // !42
2481 if (Lex.getKind() == lltok::APSInt) {
2482 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2483 ID.Kind = ValID::t_MDNode;
2484 return false;
2485 }
2486
2487 // MDString:
2488 // ::= '!' STRINGCONSTANT
2489 if (ParseMDString(ID.MDStringVal)) return true;
2490 ID.Kind = ValID::t_MDString;
2491 return false;
2492}
2493
Victor Hernandez92f238d2010-01-11 22:31:58 +00002494
2495//===----------------------------------------------------------------------===//
2496// Function Parsing.
2497//===----------------------------------------------------------------------===//
2498
2499bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2500 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002501 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002502 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002503
Chris Lattnerdf986172009-01-02 07:01:27 +00002504 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002505 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002506 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002507 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2508 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2509 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002511 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2512 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2513 return (V == 0);
2514 case ValID::t_InlineAsm: {
2515 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2516 const FunctionType *FTy =
2517 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2518 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2519 return Error(ID.Loc, "invalid type for inline asm constraint string");
2520 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2521 return false;
2522 }
2523 case ValID::t_MDNode:
2524 if (!Ty->isMetadataTy())
2525 return Error(ID.Loc, "metadata value must have metadata type");
2526 V = ID.MDNodeVal;
2527 return false;
2528 case ValID::t_MDString:
2529 if (!Ty->isMetadataTy())
2530 return Error(ID.Loc, "metadata value must have metadata type");
2531 V = ID.MDStringVal;
2532 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002533 case ValID::t_GlobalName:
2534 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2535 return V == 0;
2536 case ValID::t_GlobalID:
2537 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2538 return V == 0;
2539 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002540 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002542 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002543 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 return false;
2545 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002546 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2548 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002549
Chris Lattnerdf986172009-01-02 07:01:27 +00002550 // The lexer has no type info, so builds all float and double FP constants
2551 // as double. Fix this here. Long double does not need this.
2552 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002553 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 bool Ignored;
2555 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2556 &Ignored);
2557 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002558 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002559
Chris Lattner959873d2009-01-05 18:24:23 +00002560 if (V->getType() != Ty)
2561 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002562 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002563
Chris Lattnerdf986172009-01-02 07:01:27 +00002564 return false;
2565 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002566 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002567 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002568 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 return false;
2570 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002571 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002572 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002573 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002574 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002575 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002577 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002578 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002579 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002580 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002581 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002582 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002583 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002584 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002586 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 return false;
2588 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002589 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002591
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 V = ID.ConstantVal;
2593 return false;
2594 }
2595}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdf986172009-01-02 07:01:27 +00002597bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2598 V = 0;
2599 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002600 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002601 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002602}
2603
2604bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002605 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002606 return ParseType(T) ||
2607 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002608}
2609
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002610bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2611 PerFunctionState &PFS) {
2612 Value *V;
2613 Loc = Lex.getLoc();
2614 if (ParseTypeAndValue(V, PFS)) return true;
2615 if (!isa<BasicBlock>(V))
2616 return Error(Loc, "expected a basic block");
2617 BB = cast<BasicBlock>(V);
2618 return false;
2619}
2620
2621
Chris Lattnerdf986172009-01-02 07:01:27 +00002622/// FunctionHeader
2623/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002624/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002625/// OptionalAlign OptGC
2626bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2627 // Parse the linkage.
2628 LocTy LinkageLoc = Lex.getLoc();
2629 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002630
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002631 unsigned Visibility, RetAttrs;
2632 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002633 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 LocTy RetTypeLoc = Lex.getLoc();
2635 if (ParseOptionalLinkage(Linkage) ||
2636 ParseOptionalVisibility(Visibility) ||
2637 ParseOptionalCallingConv(CC) ||
2638 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002639 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 return true;
2641
2642 // Verify that the linkage is ok.
2643 switch ((GlobalValue::LinkageTypes)Linkage) {
2644 case GlobalValue::ExternalLinkage:
2645 break; // always ok.
2646 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002647 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 if (isDefine)
2649 return Error(LinkageLoc, "invalid linkage for function definition");
2650 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002651 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002652 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002653 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002654 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002655 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002656 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002657 case GlobalValue::LinkOnceAnyLinkage:
2658 case GlobalValue::LinkOnceODRLinkage:
2659 case GlobalValue::WeakAnyLinkage:
2660 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002661 case GlobalValue::DLLExportLinkage:
2662 if (!isDefine)
2663 return Error(LinkageLoc, "invalid linkage for function declaration");
2664 break;
2665 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002666 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002667 return Error(LinkageLoc, "invalid function linkage type");
2668 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002669
Chris Lattner99bb3152009-01-05 08:00:30 +00002670 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002671 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002672 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Chris Lattnerdf986172009-01-02 07:01:27 +00002674 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002675
2676 std::string FunctionName;
2677 if (Lex.getKind() == lltok::GlobalVar) {
2678 FunctionName = Lex.getStrVal();
2679 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2680 unsigned NameID = Lex.getUIntVal();
2681
2682 if (NameID != NumberedVals.size())
2683 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002684 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002685 } else {
2686 return TokError("expected function name");
2687 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002689 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002691 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002693
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 std::vector<ArgInfo> ArgList;
2695 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002697 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002699 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002700 bool UnnamedAddr;
2701 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002702
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002703 if (ParseArgumentList(ArgList, isVarArg, false) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002704 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2705 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002706 ParseOptionalAttrs(FuncAttrs, 2) ||
2707 (EatIfPresent(lltok::kw_section) &&
2708 ParseStringConstant(Section)) ||
2709 ParseOptionalAlignment(Alignment) ||
2710 (EatIfPresent(lltok::kw_gc) &&
2711 ParseStringConstant(GC)))
2712 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002713
2714 // If the alignment was parsed as an attribute, move to the alignment field.
2715 if (FuncAttrs & Attribute::Alignment) {
2716 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2717 FuncAttrs &= ~Attribute::Alignment;
2718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 // Okay, if we got here, the function is syntactically valid. Convert types
2721 // and do semantic checks.
2722 std::vector<const Type*> ParamTypeList;
2723 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 if (RetAttrs != Attribute::None)
2726 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2729 ParamTypeList.push_back(ArgList[i].Type);
2730 if (ArgList[i].Attrs != Attribute::None)
2731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2732 }
2733
2734 if (FuncAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2736
2737 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002738
Benjamin Kramerf0127052010-01-05 13:12:22 +00002739 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2741
Owen Andersonfba933c2009-07-01 23:57:11 +00002742 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002743 FunctionType::get(RetType, ParamTypeList, isVarArg);
2744 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002745
2746 Fn = 0;
2747 if (!FunctionName.empty()) {
2748 // If this was a definition of a forward reference, remove the definition
2749 // from the forward reference table and fill in the forward ref.
2750 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2751 ForwardRefVals.find(FunctionName);
2752 if (FRVI != ForwardRefVals.end()) {
2753 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002754 if (Fn->getType() != PFT)
2755 return Error(FRVI->second.second, "invalid forward reference to "
2756 "function '" + FunctionName + "' with wrong type!");
2757
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 ForwardRefVals.erase(FRVI);
2759 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002760 // Reject redefinitions.
2761 return Error(NameLoc, "invalid redefinition of function '" +
2762 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002763 } else if (M->getNamedValue(FunctionName)) {
2764 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Dan Gohman41905542009-08-29 23:37:49 +00002767 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002768 // If this is a definition of a forward referenced function, make sure the
2769 // types agree.
2770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2771 = ForwardRefValIDs.find(NumberedVals.size());
2772 if (I != ForwardRefValIDs.end()) {
2773 Fn = cast<Function>(I->second.first);
2774 if (Fn->getType() != PFT)
2775 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002776 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002777 ForwardRefValIDs.erase(I);
2778 }
2779 }
2780
2781 if (Fn == 0)
2782 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2783 else // Move the forward-reference to the correct spot in the module.
2784 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2785
2786 if (FunctionName.empty())
2787 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2790 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2791 Fn->setCallingConv(CC);
2792 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002793 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 Fn->setAlignment(Alignment);
2795 Fn->setSection(Section);
2796 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Add all of the arguments we parsed to the function.
2799 Function::arg_iterator ArgIt = Fn->arg_begin();
2800 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2801 // If the argument has a name, insert it into the argument symbol table.
2802 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002803
Chris Lattnerdf986172009-01-02 07:01:27 +00002804 // Set the name, if it conflicted, it will be auto-renamed.
2805 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806
Benjamin Krameraf812352010-10-16 11:28:23 +00002807 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2809 ArgList[i].Name + "'");
2810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002811
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 return false;
2813}
2814
2815
2816/// ParseFunctionBody
2817/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002818///
2819bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002820 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 return TokError("expected '{' in function body");
2822 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattner09d9ef42009-10-28 03:39:23 +00002824 int FunctionNumber = -1;
2825 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2826
2827 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002829 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002830 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002831 return TokError("function body requires at least one basic block");
2832
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002833 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002834 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002835
Chris Lattnerdf986172009-01-02 07:01:27 +00002836 // Eat the }.
2837 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002838
Chris Lattnerdf986172009-01-02 07:01:27 +00002839 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002840 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002841}
2842
2843/// ParseBasicBlock
2844/// ::= LabelStr? Instruction*
2845bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2846 // If this basic block starts out with a name, remember it.
2847 std::string Name;
2848 LocTy NameLoc = Lex.getLoc();
2849 if (Lex.getKind() == lltok::LabelStr) {
2850 Name = Lex.getStrVal();
2851 Lex.Lex();
2852 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002853
Chris Lattnerdf986172009-01-02 07:01:27 +00002854 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2855 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002856
Chris Lattnerdf986172009-01-02 07:01:27 +00002857 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002858
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 // Parse the instructions in this block until we get a terminator.
2860 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002861 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 do {
2863 // This instruction may have three possibilities for a name: a) none
2864 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2865 LocTy NameLoc = Lex.getLoc();
2866 int NameID = -1;
2867 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 if (Lex.getKind() == lltok::LocalVarID) {
2870 NameID = Lex.getUIntVal();
2871 Lex.Lex();
2872 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2873 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002874 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 NameStr = Lex.getStrVal();
2876 Lex.Lex();
2877 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2878 return true;
2879 }
Devang Patelf633a062009-09-17 23:04:48 +00002880
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002881 switch (ParseInstruction(Inst, BB, PFS)) {
2882 default: assert(0 && "Unknown ParseInstruction result!");
2883 case InstError: return true;
2884 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002885 BB->getInstList().push_back(Inst);
2886
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002887 // With a normal result, we check to see if the instruction is followed by
2888 // a comma and metadata.
2889 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002890 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002891 return true;
2892 break;
2893 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002894 BB->getInstList().push_back(Inst);
2895
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002896 // If the instruction parser ate an extra comma at the end of it, it
2897 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002898 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002899 return true;
2900 break;
2901 }
Devang Patelf633a062009-09-17 23:04:48 +00002902
Chris Lattnerdf986172009-01-02 07:01:27 +00002903 // Set the name on the instruction.
2904 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2905 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002906
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 return false;
2908}
2909
2910//===----------------------------------------------------------------------===//
2911// Instruction Parsing.
2912//===----------------------------------------------------------------------===//
2913
2914/// ParseInstruction - Parse one of the many different instructions.
2915///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002916int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2917 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 lltok::Kind Token = Lex.getKind();
2919 if (Token == lltok::Eof)
2920 return TokError("found end of file when expecting more instructions");
2921 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002922 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 switch (Token) {
2926 default: return Error(Loc, "expected instruction opcode");
2927 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002928 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2929 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2931 case lltok::kw_br: return ParseBr(Inst, PFS);
2932 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002933 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002934 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2935 // Binary Operators.
2936 case lltok::kw_add:
2937 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002938 case lltok::kw_mul:
2939 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002940 bool NUW = EatIfPresent(lltok::kw_nuw);
2941 bool NSW = EatIfPresent(lltok::kw_nsw);
2942 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2943
2944 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2945
2946 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2947 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2948 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002949 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002950 case lltok::kw_fadd:
2951 case lltok::kw_fsub:
2952 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2953
Chris Lattner35bda892011-02-06 21:44:57 +00002954 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002955 case lltok::kw_udiv:
2956 case lltok::kw_lshr:
2957 case lltok::kw_ashr: {
2958 bool Exact = EatIfPresent(lltok::kw_exact);
2959
2960 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2961 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2962 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002963 }
2964
Chris Lattnerdf986172009-01-02 07:01:27 +00002965 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002966 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002967 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002968 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002969 case lltok::kw_and:
2970 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002971 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002973 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 // Casts.
2975 case lltok::kw_trunc:
2976 case lltok::kw_zext:
2977 case lltok::kw_sext:
2978 case lltok::kw_fptrunc:
2979 case lltok::kw_fpext:
2980 case lltok::kw_bitcast:
2981 case lltok::kw_uitofp:
2982 case lltok::kw_sitofp:
2983 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002984 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002986 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002987 // Other.
2988 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002989 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2991 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2992 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2993 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2994 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2995 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2996 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002997 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002998 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2999 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3000 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003001 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003002 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003003 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003004 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003005 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003006 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003007 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3008 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3009 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3010 }
3011}
3012
3013/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3014bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003015 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 switch (Lex.getKind()) {
3017 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3018 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3019 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3020 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3021 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3022 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3023 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3024 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3025 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3026 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3027 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3028 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3029 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3030 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3031 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3032 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3033 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3034 }
3035 } else {
3036 switch (Lex.getKind()) {
3037 default: TokError("expected icmp predicate (e.g. 'eq')");
3038 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3039 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3040 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3041 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3042 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3043 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3044 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3045 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3046 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3047 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3048 }
3049 }
3050 Lex.Lex();
3051 return false;
3052}
3053
3054//===----------------------------------------------------------------------===//
3055// Terminator Instructions.
3056//===----------------------------------------------------------------------===//
3057
3058/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003059/// ::= 'ret' void (',' !dbg, !1)*
3060/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003061bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003062 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003063 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003064 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003065
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003066 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003067 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003068 return false;
3069 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003070
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 Value *RV;
3072 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003073
Owen Anderson1d0be152009-08-13 21:58:54 +00003074 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003075 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003076}
3077
3078
3079/// ParseBr
3080/// ::= 'br' TypeAndValue
3081/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3082bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3083 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003084 Value *Op0;
3085 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003087
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3089 Inst = BranchInst::Create(BB);
3090 return false;
3091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003092
Owen Anderson1d0be152009-08-13 21:58:54 +00003093 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003097 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003099 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003100 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003101
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003102 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003103 return false;
3104}
3105
3106/// ParseSwitch
3107/// Instruction
3108/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3109/// JumpTable
3110/// ::= (TypeAndValue ',' TypeAndValue)*
3111bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3112 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003113 Value *Cond;
3114 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3116 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003117 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003118 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3119 return true;
3120
Duncan Sands1df98592010-02-16 11:11:14 +00003121 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003122 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003123
Chris Lattnerdf986172009-01-02 07:01:27 +00003124 // Parse the jump table pairs.
3125 SmallPtrSet<Value*, 32> SeenCases;
3126 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3127 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003128 Value *Constant;
3129 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003130
Chris Lattnerdf986172009-01-02 07:01:27 +00003131 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3132 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003133 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003134 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003135
Chris Lattnerdf986172009-01-02 07:01:27 +00003136 if (!SeenCases.insert(Constant))
3137 return Error(CondLoc, "duplicate case value in switch");
3138 if (!isa<ConstantInt>(Constant))
3139 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003140
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003141 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003143
Chris Lattnerdf986172009-01-02 07:01:27 +00003144 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003145
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003146 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003147 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3148 SI->addCase(Table[i].first, Table[i].second);
3149 Inst = SI;
3150 return false;
3151}
3152
Chris Lattnerab21db72009-10-28 00:19:10 +00003153/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003154/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003155/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3156bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003157 LocTy AddrLoc;
3158 Value *Address;
3159 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003160 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3161 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003162 return true;
3163
Duncan Sands1df98592010-02-16 11:11:14 +00003164 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003165 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166
3167 // Parse the destination list.
3168 SmallVector<BasicBlock*, 16> DestList;
3169
3170 if (Lex.getKind() != lltok::rsquare) {
3171 BasicBlock *DestBB;
3172 if (ParseTypeAndBasicBlock(DestBB, PFS))
3173 return true;
3174 DestList.push_back(DestBB);
3175
3176 while (EatIfPresent(lltok::comma)) {
3177 if (ParseTypeAndBasicBlock(DestBB, PFS))
3178 return true;
3179 DestList.push_back(DestBB);
3180 }
3181 }
3182
3183 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3184 return true;
3185
Chris Lattnerab21db72009-10-28 00:19:10 +00003186 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003187 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3188 IBI->addDestination(DestList[i]);
3189 Inst = IBI;
3190 return false;
3191}
3192
3193
Chris Lattnerdf986172009-01-02 07:01:27 +00003194/// ParseInvoke
3195/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3196/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3197bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3198 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003199 unsigned RetAttrs, FnAttrs;
3200 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003201 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003202 LocTy RetTypeLoc;
3203 ValID CalleeID;
3204 SmallVector<ParamInfo, 16> ArgList;
3205
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003206 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 if (ParseOptionalCallingConv(CC) ||
3208 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003209 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 ParseValID(CalleeID) ||
3211 ParseParameterList(ArgList, PFS) ||
3212 ParseOptionalAttrs(FnAttrs, 2) ||
3213 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003214 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003216 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003217 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003218
Chris Lattnerdf986172009-01-02 07:01:27 +00003219 // If RetType is a non-function pointer type, then this is the short syntax
3220 // for the call, which means that RetType is just the return type. Infer the
3221 // rest of the function argument types from the arguments that are present.
3222 const PointerType *PFTy = 0;
3223 const FunctionType *Ty = 0;
3224 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3225 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3226 // Pull out the types of all of the arguments...
3227 std::vector<const Type*> ParamTypes;
3228 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3229 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003230
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 if (!FunctionType::isValidReturnType(RetType))
3232 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003233
Owen Andersondebcb012009-07-29 22:17:13 +00003234 Ty = FunctionType::get(RetType, ParamTypes, false);
3235 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003236 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 // Look up the callee.
3239 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003240 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 // Set up the Attributes for the function.
3243 SmallVector<AttributeWithIndex, 8> Attrs;
3244 if (RetAttrs != Attribute::None)
3245 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003246
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003248
Chris Lattnerdf986172009-01-02 07:01:27 +00003249 // Loop through FunctionType's arguments and ensure they are specified
3250 // correctly. Also, gather any parameter attributes.
3251 FunctionType::param_iterator I = Ty->param_begin();
3252 FunctionType::param_iterator E = Ty->param_end();
3253 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3254 const Type *ExpectedTy = 0;
3255 if (I != E) {
3256 ExpectedTy = *I++;
3257 } else if (!Ty->isVarArg()) {
3258 return Error(ArgList[i].Loc, "too many arguments specified");
3259 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003260
Chris Lattnerdf986172009-01-02 07:01:27 +00003261 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3262 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003263 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003264 Args.push_back(ArgList[i].V);
3265 if (ArgList[i].Attrs != Attribute::None)
3266 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3267 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003268
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 if (I != E)
3270 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003271
Chris Lattnerdf986172009-01-02 07:01:27 +00003272 if (FnAttrs != Attribute::None)
3273 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003274
Chris Lattnerdf986172009-01-02 07:01:27 +00003275 // Finish off the Attributes and check them
3276 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003277
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003278 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 Args.begin(), Args.end());
3280 II->setCallingConv(CC);
3281 II->setAttributes(PAL);
3282 Inst = II;
3283 return false;
3284}
3285
3286
3287
3288//===----------------------------------------------------------------------===//
3289// Binary Operators.
3290//===----------------------------------------------------------------------===//
3291
3292/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003293/// ::= ArithmeticOps TypeAndValue ',' Value
3294///
3295/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3296/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003297bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003298 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003299 LocTy Loc; Value *LHS, *RHS;
3300 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3301 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3302 ParseValue(LHS->getType(), RHS, PFS))
3303 return true;
3304
Chris Lattnere914b592009-01-05 08:24:46 +00003305 bool Valid;
3306 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003307 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003308 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003309 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3310 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003311 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003312 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3313 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003314 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003315
Chris Lattnere914b592009-01-05 08:24:46 +00003316 if (!Valid)
3317 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003318
Chris Lattnerdf986172009-01-02 07:01:27 +00003319 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3320 return false;
3321}
3322
3323/// ParseLogical
3324/// ::= ArithmeticOps TypeAndValue ',' Value {
3325bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3326 unsigned Opc) {
3327 LocTy Loc; Value *LHS, *RHS;
3328 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3329 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3330 ParseValue(LHS->getType(), RHS, PFS))
3331 return true;
3332
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003333 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003334 return Error(Loc,"instruction requires integer or integer vector operands");
3335
3336 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3337 return false;
3338}
3339
3340
3341/// ParseCompare
3342/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3343/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003344bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3345 unsigned Opc) {
3346 // Parse the integer/fp comparison predicate.
3347 LocTy Loc;
3348 unsigned Pred;
3349 Value *LHS, *RHS;
3350 if (ParseCmpPredicate(Pred, Opc) ||
3351 ParseTypeAndValue(LHS, Loc, PFS) ||
3352 ParseToken(lltok::comma, "expected ',' after compare value") ||
3353 ParseValue(LHS->getType(), RHS, PFS))
3354 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003355
Chris Lattnerdf986172009-01-02 07:01:27 +00003356 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003357 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003358 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003359 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003360 } else {
3361 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003362 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003363 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003365 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 }
3367 return false;
3368}
3369
3370//===----------------------------------------------------------------------===//
3371// Other Instructions.
3372//===----------------------------------------------------------------------===//
3373
3374
3375/// ParseCast
3376/// ::= CastOpc TypeAndValue 'to' Type
3377bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3378 unsigned Opc) {
3379 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003380 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 if (ParseTypeAndValue(Op, Loc, PFS) ||
3382 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3383 ParseType(DestTy))
3384 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003385
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003386 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3387 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003389 getTypeString(Op->getType()) + "' to '" +
3390 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003391 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003392 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3393 return false;
3394}
3395
3396/// ParseSelect
3397/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3398bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3399 LocTy Loc;
3400 Value *Op0, *Op1, *Op2;
3401 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3402 ParseToken(lltok::comma, "expected ',' after select condition") ||
3403 ParseTypeAndValue(Op1, PFS) ||
3404 ParseToken(lltok::comma, "expected ',' after select value") ||
3405 ParseTypeAndValue(Op2, PFS))
3406 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003407
Chris Lattnerdf986172009-01-02 07:01:27 +00003408 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3409 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003410
Chris Lattnerdf986172009-01-02 07:01:27 +00003411 Inst = SelectInst::Create(Op0, Op1, Op2);
3412 return false;
3413}
3414
Chris Lattner0088a5c2009-01-05 08:18:44 +00003415/// ParseVA_Arg
3416/// ::= 'va_arg' TypeAndValue ',' Type
3417bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003418 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003419 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003420 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003421 if (ParseTypeAndValue(Op, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003423 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003424 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003425
Chris Lattner0088a5c2009-01-05 08:18:44 +00003426 if (!EltTy->isFirstClassType())
3427 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003428
3429 Inst = new VAArgInst(Op, EltTy);
3430 return false;
3431}
3432
3433/// ParseExtractElement
3434/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3435bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3436 LocTy Loc;
3437 Value *Op0, *Op1;
3438 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3439 ParseToken(lltok::comma, "expected ',' after extract value") ||
3440 ParseTypeAndValue(Op1, PFS))
3441 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003442
Chris Lattnerdf986172009-01-02 07:01:27 +00003443 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3444 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003445
Eric Christophera3500da2009-07-25 02:28:41 +00003446 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 return false;
3448}
3449
3450/// ParseInsertElement
3451/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3452bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3453 LocTy Loc;
3454 Value *Op0, *Op1, *Op2;
3455 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3456 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3457 ParseTypeAndValue(Op1, PFS) ||
3458 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3459 ParseTypeAndValue(Op2, PFS))
3460 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003461
Chris Lattnerdf986172009-01-02 07:01:27 +00003462 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003463 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003464
Chris Lattnerdf986172009-01-02 07:01:27 +00003465 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3466 return false;
3467}
3468
3469/// ParseShuffleVector
3470/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3471bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3472 LocTy Loc;
3473 Value *Op0, *Op1, *Op2;
3474 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3475 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3476 ParseTypeAndValue(Op1, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3478 ParseTypeAndValue(Op2, PFS))
3479 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003480
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3482 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003483
Chris Lattnerdf986172009-01-02 07:01:27 +00003484 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3485 return false;
3486}
3487
3488/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003489/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003490int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003491 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003492 Value *Op0, *Op1;
3493 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003494
Chris Lattnerdf986172009-01-02 07:01:27 +00003495 if (ParseType(Ty) ||
3496 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3497 ParseValue(Ty, Op0, PFS) ||
3498 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003499 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3501 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003502
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003503 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3505 while (1) {
3506 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003507
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003508 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003509 break;
3510
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003511 if (Lex.getKind() == lltok::MetadataVar) {
3512 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003513 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003514 }
Devang Patela43d46f2009-10-16 18:45:49 +00003515
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003516 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003517 ParseValue(Ty, Op0, PFS) ||
3518 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003519 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003520 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3521 return true;
3522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003523
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 if (!Ty->isFirstClassType())
3525 return Error(TypeLoc, "phi node must have first class type");
3526
Jay Foad3ecfc862011-03-30 11:28:46 +00003527 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3529 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3530 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003531 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003532}
3533
3534/// ParseCall
3535/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3536/// ParameterList OptionalAttrs
3537bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3538 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003539 unsigned RetAttrs, FnAttrs;
3540 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003541 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 LocTy RetTypeLoc;
3543 ValID CalleeID;
3544 SmallVector<ParamInfo, 16> ArgList;
3545 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003546
Chris Lattnerdf986172009-01-02 07:01:27 +00003547 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3548 ParseOptionalCallingConv(CC) ||
3549 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003550 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003551 ParseValID(CalleeID) ||
3552 ParseParameterList(ArgList, PFS) ||
3553 ParseOptionalAttrs(FnAttrs, 2))
3554 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003555
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 // If RetType is a non-function pointer type, then this is the short syntax
3557 // for the call, which means that RetType is just the return type. Infer the
3558 // rest of the function argument types from the arguments that are present.
3559 const PointerType *PFTy = 0;
3560 const FunctionType *Ty = 0;
3561 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3562 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3563 // Pull out the types of all of the arguments...
3564 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3566 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003567
Chris Lattnerdf986172009-01-02 07:01:27 +00003568 if (!FunctionType::isValidReturnType(RetType))
3569 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003570
Owen Andersondebcb012009-07-29 22:17:13 +00003571 Ty = FunctionType::get(RetType, ParamTypes, false);
3572 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003573 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003574
Chris Lattnerdf986172009-01-02 07:01:27 +00003575 // Look up the callee.
3576 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003577 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003578
Chris Lattnerdf986172009-01-02 07:01:27 +00003579 // Set up the Attributes for the function.
3580 SmallVector<AttributeWithIndex, 8> Attrs;
3581 if (RetAttrs != Attribute::None)
3582 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003583
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003585
Chris Lattnerdf986172009-01-02 07:01:27 +00003586 // Loop through FunctionType's arguments and ensure they are specified
3587 // correctly. Also, gather any parameter attributes.
3588 FunctionType::param_iterator I = Ty->param_begin();
3589 FunctionType::param_iterator E = Ty->param_end();
3590 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3591 const Type *ExpectedTy = 0;
3592 if (I != E) {
3593 ExpectedTy = *I++;
3594 } else if (!Ty->isVarArg()) {
3595 return Error(ArgList[i].Loc, "too many arguments specified");
3596 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003597
Chris Lattnerdf986172009-01-02 07:01:27 +00003598 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3599 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003600 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003601 Args.push_back(ArgList[i].V);
3602 if (ArgList[i].Attrs != Attribute::None)
3603 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3604 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003605
Chris Lattnerdf986172009-01-02 07:01:27 +00003606 if (I != E)
3607 return Error(CallLoc, "not enough parameters specified for call");
3608
3609 if (FnAttrs != Attribute::None)
3610 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3611
3612 // Finish off the Attributes and check them
3613 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003614
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3616 CI->setTailCall(isTail);
3617 CI->setCallingConv(CC);
3618 CI->setAttributes(PAL);
3619 Inst = CI;
3620 return false;
3621}
3622
3623//===----------------------------------------------------------------------===//
3624// Memory Instructions.
3625//===----------------------------------------------------------------------===//
3626
3627/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003628/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003629int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003630 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003631 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003632 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003633 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003634 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003635
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003636 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003637 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003638 if (Lex.getKind() == lltok::kw_align) {
3639 if (ParseOptionalAlignment(Alignment)) return true;
3640 } else if (Lex.getKind() == lltok::MetadataVar) {
3641 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003642 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003643 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3644 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3645 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003646 }
3647 }
3648
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003649 if (Size && !Size->getType()->isIntegerTy())
3650 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003651
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003652 Inst = new AllocaInst(Ty, Size, Alignment);
3653 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003654}
3655
3656/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003657/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003658int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3659 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003660 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003661 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003662 bool AteExtraComma = false;
3663 if (ParseTypeAndValue(Val, Loc, PFS) ||
3664 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3665 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003666
Duncan Sands1df98592010-02-16 11:11:14 +00003667 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3669 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003670
Chris Lattnerdf986172009-01-02 07:01:27 +00003671 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003672 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003673}
3674
3675/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003676/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003677int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3678 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003679 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003680 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003681 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003682 if (ParseTypeAndValue(Val, Loc, PFS) ||
3683 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003684 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3685 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003686 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003687
Duncan Sands1df98592010-02-16 11:11:14 +00003688 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003689 return Error(PtrLoc, "store operand must be a pointer");
3690 if (!Val->getType()->isFirstClassType())
3691 return Error(Loc, "store operand must be a first class value");
3692 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3693 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003694
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003696 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003697}
3698
Chris Lattnerdf986172009-01-02 07:01:27 +00003699/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003700/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003701int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003702 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003703
Dan Gohmandcb40a32009-07-29 15:58:36 +00003704 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003705
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003706 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003707
Duncan Sands1df98592010-02-16 11:11:14 +00003708 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003709 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003710
Chris Lattnerdf986172009-01-02 07:01:27 +00003711 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003712 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003713 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003714 if (Lex.getKind() == lltok::MetadataVar) {
3715 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003716 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003717 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003718 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003719 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003720 return Error(EltLoc, "getelementptr index must be an integer");
3721 Indices.push_back(Val);
3722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003723
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3725 Indices.begin(), Indices.end()))
3726 return Error(Loc, "invalid getelementptr indices");
3727 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003728 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003729 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003730 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003731}
3732
3733/// ParseExtractValue
3734/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003735int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003736 Value *Val; LocTy Loc;
3737 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003738 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003739 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003740 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003741 return true;
3742
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003743 if (!Val->getType()->isAggregateType())
3744 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003745
3746 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3747 Indices.end()))
3748 return Error(Loc, "invalid indices for extractvalue");
3749 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003750 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003751}
3752
3753/// ParseInsertValue
3754/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003755int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003756 Value *Val0, *Val1; LocTy Loc0, Loc1;
3757 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003758 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003759 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3760 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3761 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003762 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003763 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003764
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003765 if (!Val0->getType()->isAggregateType())
3766 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003767
Chris Lattnerdf986172009-01-02 07:01:27 +00003768 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3769 Indices.end()))
3770 return Error(Loc0, "invalid indices for insertvalue");
3771 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003772 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003773}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003774
3775//===----------------------------------------------------------------------===//
3776// Embedded metadata.
3777//===----------------------------------------------------------------------===//
3778
3779/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003780/// ::= Element (',' Element)*
3781/// Element
3782/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003783bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003784 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003785 // Check for an empty list.
3786 if (Lex.getKind() == lltok::rbrace)
3787 return false;
3788
Nick Lewycky21cc4462009-04-04 07:22:01 +00003789 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003790 // Null is a special case since it is typeless.
3791 if (EatIfPresent(lltok::kw_null)) {
3792 Elts.push_back(0);
3793 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003794 }
Chris Lattnera7352392009-12-30 04:42:57 +00003795
3796 Value *V = 0;
3797 PATypeHolder Ty(Type::getVoidTy(Context));
3798 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003799 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003800 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003801 return true;
3802
Nick Lewyckycb337992009-05-10 20:57:05 +00003803 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003804 } while (EatIfPresent(lltok::comma));
3805
3806 return false;
3807}