blob: 9dbd78c558ecb00750b617f6d01dfdfd1f76ad41 [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"
Owen Andersonfba933c2009-07-01 23:57:11 +000021#include "llvm/LLVMContext.h"
Devang Patel0a9f7b92009-07-28 21:49:47 +000022#include "llvm/Metadata.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000024#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000025#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000029#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000033bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000034 // Prime the lexer.
35 Lex.Lex();
36
Chris Lattnerad7d1e22009-01-04 20:44:11 +000037 return ParseTopLevelEntities() ||
38 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000039}
40
41/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
42/// module.
43bool LLParser::ValidateEndOfModule() {
Victor Hernandez68afa542009-10-21 19:11:40 +000044 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000045 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000046 if (MallocF) {
47 MallocF->setName("malloc");
48 // If setName() does not set the name to "malloc", then there is already a
49 // declaration of "malloc". In that case, iterate over all calls to MallocF
50 // and get them to call the declared "malloc" instead.
51 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000052 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000053 if (RealMallocF->getType() != MallocF->getType())
54 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
55 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000056 MallocF->eraseFromParent();
57 MallocF = NULL;
58 }
59 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000060
61
62 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
66 Function *TheFn = 0;
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
72
73 if (TheFn == 0)
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
75
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
79 0))
80 return true;
81
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
83 }
84
85
Chris Lattnerdf986172009-01-02 07:01:27 +000086 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
93 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000094
Chris Lattnerdf986172009-01-02 07:01:27 +000095 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
98 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000099
Chris Lattnerdf986172009-01-02 07:01:27 +0000100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
103 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000104
Devang Patel1c7eea62009-07-08 19:23:54 +0000105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
108 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000109
Devang Patel1c7eea62009-07-08 19:23:54 +0000110
Chris Lattnerdf986172009-01-02 07:01:27 +0000111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000114
Devang Patele4b27562009-08-28 23:24:31 +0000115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000117 return false;
118}
119
Chris Lattner09d9ef42009-10-28 03:39:23 +0000120bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
125 BasicBlock *Res;
Chris Lattner7d83ebc2009-10-31 20:08:37 +0000126 if (Refs[i].first.Kind == ValID::t_Null)
127 Res = 0;
128 else if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000129 if (Refs[i].first.Kind == ValID::t_LocalName)
130 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattner7d83ebc2009-10-31 20:08:37 +0000131 else {
132 assert(Refs[i].first.Kind == ValID::t_LocalID);
Chris Lattner09d9ef42009-10-28 03:39:23 +0000133 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
Chris Lattner7d83ebc2009-10-31 20:08:37 +0000134 }
Chris Lattner09d9ef42009-10-28 03:39:23 +0000135 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
136 return Error(Refs[i].first.Loc,
137 "cannot take address of numeric label after it the function is defined");
138 } else {
Chris Lattner7d83ebc2009-10-31 20:08:37 +0000139 assert(Refs[i].first.Kind == ValID::t_LocalName);
Chris Lattner09d9ef42009-10-28 03:39:23 +0000140 Res = dyn_cast_or_null<BasicBlock>(
141 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
142 }
143
Chris Lattner7d83ebc2009-10-31 20:08:37 +0000144 if (Res == 0 && Refs[i].first.Kind != ValID::t_Null)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000145 return Error(Refs[i].first.Loc,
146 "referenced value is not a basic block");
147
148 // Get the BlockAddress for this and update references to use it.
149 BlockAddress *BA = BlockAddress::get(TheFn, Res);
150 Refs[i].second->replaceAllUsesWith(BA);
151 Refs[i].second->eraseFromParent();
152 }
153 return false;
154}
155
156
Chris Lattnerdf986172009-01-02 07:01:27 +0000157//===----------------------------------------------------------------------===//
158// Top-Level Entities
159//===----------------------------------------------------------------------===//
160
161bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000162 while (1) {
163 switch (Lex.getKind()) {
164 default: return TokError("expected top-level entity");
165 case lltok::Eof: return false;
166 //case lltok::kw_define:
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000173 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000174 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
175 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;
Devang Patel923078c2009-07-01 19:21:12 +0000178 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Patel0475c912009-09-29 00:01:14 +0000179 case lltok::NamedOrCustomMD: 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
184 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000185 case lltok::kw_private : // OptionalLinkage
186 case lltok::kw_linker_private: // OptionalLinkage
187 case lltok::kw_internal: // OptionalLinkage
188 case lltok::kw_weak: // OptionalLinkage
189 case lltok::kw_weak_odr: // OptionalLinkage
190 case lltok::kw_linkonce: // OptionalLinkage
191 case lltok::kw_linkonce_odr: // OptionalLinkage
192 case lltok::kw_appending: // OptionalLinkage
193 case lltok::kw_dllexport: // OptionalLinkage
194 case lltok::kw_common: // OptionalLinkage
195 case lltok::kw_dllimport: // OptionalLinkage
196 case lltok::kw_extern_weak: // OptionalLinkage
197 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 unsigned Linkage, Visibility;
199 if (ParseOptionalLinkage(Linkage) ||
200 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000201 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000202 return true;
203 break;
204 }
205 case lltok::kw_default: // OptionalVisibility
206 case lltok::kw_hidden: // OptionalVisibility
207 case lltok::kw_protected: { // OptionalVisibility
208 unsigned Visibility;
209 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000210 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000211 return true;
212 break;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
Chris Lattnerdf986172009-01-02 07:01:27 +0000215 case lltok::kw_thread_local: // OptionalThreadLocal
216 case lltok::kw_addrspace: // OptionalAddrSpace
217 case lltok::kw_constant: // GlobalType
218 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000219 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000220 break;
221 }
222 }
223}
224
225
226/// toplevelentity
227/// ::= 'module' 'asm' STRINGCONSTANT
228bool LLParser::ParseModuleAsm() {
229 assert(Lex.getKind() == lltok::kw_module);
230 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000231
232 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000233 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
234 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000235
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 const std::string &AsmSoFar = M->getModuleInlineAsm();
237 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000238 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000239 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000240 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000241 return false;
242}
243
244/// toplevelentity
245/// ::= 'target' 'triple' '=' STRINGCONSTANT
246/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
247bool LLParser::ParseTargetDefinition() {
248 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000249 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000250 switch (Lex.Lex()) {
251 default: return TokError("unknown target property");
252 case lltok::kw_triple:
253 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
255 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000257 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000258 return false;
259 case lltok::kw_datalayout:
260 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
262 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000263 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000264 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 return false;
266 }
267}
268
269/// toplevelentity
270/// ::= 'deplibs' '=' '[' ']'
271/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
272bool LLParser::ParseDepLibs() {
273 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000274 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000275 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
276 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
277 return true;
278
279 if (EatIfPresent(lltok::rsquare))
280 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000281
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000282 std::string Str;
283 if (ParseStringConstant(Str)) return true;
284 M->addLibrary(Str);
285
286 while (EatIfPresent(lltok::comma)) {
287 if (ParseStringConstant(Str)) return true;
288 M->addLibrary(Str);
289 }
290
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000292}
293
Dan Gohman3845e502009-08-12 23:32:33 +0000294/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000295/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000296/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000297bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000298 unsigned TypeID = NumberedTypes.size();
299
300 // Handle the LocalVarID form.
301 if (Lex.getKind() == lltok::LocalVarID) {
302 if (Lex.getUIntVal() != TypeID)
303 return Error(Lex.getLoc(), "type expected to be numbered '%" +
304 utostr(TypeID) + "'");
305 Lex.Lex(); // eat LocalVarID;
306
307 if (ParseToken(lltok::equal, "expected '=' after name"))
308 return true;
309 }
310
Chris Lattnerdf986172009-01-02 07:01:27 +0000311 assert(Lex.getKind() == lltok::kw_type);
312 LocTy TypeLoc = Lex.getLoc();
313 Lex.Lex(); // eat kw_type
314
Owen Anderson1d0be152009-08-13 21:58:54 +0000315 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000316 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerdf986172009-01-02 07:01:27 +0000318 // See if this type was previously referenced.
319 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
320 FI = ForwardRefTypeIDs.find(TypeID);
321 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000322 if (FI->second.first.get() == Ty)
323 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerdf986172009-01-02 07:01:27 +0000325 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
326 Ty = FI->second.first.get();
327 ForwardRefTypeIDs.erase(FI);
328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000329
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 return false;
333}
334
335/// toplevelentity
336/// ::= LocalVar '=' 'type' type
337bool LLParser::ParseNamedType() {
338 std::string Name = Lex.getStrVal();
339 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000340 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000341
Owen Anderson1d0be152009-08-13 21:58:54 +0000342 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000343
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000344 if (ParseToken(lltok::equal, "expected '=' after name") ||
345 ParseToken(lltok::kw_type, "expected 'type' after name") ||
346 ParseType(Ty))
347 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000348
Chris Lattnerdf986172009-01-02 07:01:27 +0000349 // Set the type name, checking for conflicts as we do so.
350 bool AlreadyExists = M->addTypeName(Name, Ty);
351 if (!AlreadyExists) return false;
352
353 // See if this type is a forward reference. We need to eagerly resolve
354 // types to allow recursive type redefinitions below.
355 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
356 FI = ForwardRefTypes.find(Name);
357 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000358 if (FI->second.first.get() == Ty)
359 return Error(NameLoc, "self referential type is invalid");
360
Chris Lattnerdf986172009-01-02 07:01:27 +0000361 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
362 Ty = FI->second.first.get();
363 ForwardRefTypes.erase(FI);
364 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000365
Chris Lattnerdf986172009-01-02 07:01:27 +0000366 // Inserting a name that is already defined, get the existing name.
367 const Type *Existing = M->getTypeByName(Name);
368 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000369
Chris Lattnerdf986172009-01-02 07:01:27 +0000370 // Otherwise, this is an attempt to redefine a type. That's okay if
371 // the redefinition is identical to the original.
372 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
373 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000374
Chris Lattnerdf986172009-01-02 07:01:27 +0000375 // Any other kind of (non-equivalent) redefinition is an error.
376 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
377 Ty->getDescription() + "'");
378}
379
380
381/// toplevelentity
382/// ::= 'declare' FunctionHeader
383bool LLParser::ParseDeclare() {
384 assert(Lex.getKind() == lltok::kw_declare);
385 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000386
Chris Lattnerdf986172009-01-02 07:01:27 +0000387 Function *F;
388 return ParseFunctionHeader(F, false);
389}
390
391/// toplevelentity
392/// ::= 'define' FunctionHeader '{' ...
393bool LLParser::ParseDefine() {
394 assert(Lex.getKind() == lltok::kw_define);
395 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000396
Chris Lattnerdf986172009-01-02 07:01:27 +0000397 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000398 return ParseFunctionHeader(F, true) ||
399 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000400}
401
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000402/// ParseGlobalType
403/// ::= 'constant'
404/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000405bool LLParser::ParseGlobalType(bool &IsConstant) {
406 if (Lex.getKind() == lltok::kw_constant)
407 IsConstant = true;
408 else if (Lex.getKind() == lltok::kw_global)
409 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000410 else {
411 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000412 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000413 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000414 Lex.Lex();
415 return false;
416}
417
Dan Gohman3845e502009-08-12 23:32:33 +0000418/// ParseUnnamedGlobal:
419/// OptionalVisibility ALIAS ...
420/// OptionalLinkage OptionalVisibility ... -> global variable
421/// GlobalID '=' OptionalVisibility ALIAS ...
422/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
423bool LLParser::ParseUnnamedGlobal() {
424 unsigned VarID = NumberedVals.size();
425 std::string Name;
426 LocTy NameLoc = Lex.getLoc();
427
428 // Handle the GlobalID form.
429 if (Lex.getKind() == lltok::GlobalID) {
430 if (Lex.getUIntVal() != VarID)
431 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
432 utostr(VarID) + "'");
433 Lex.Lex(); // eat GlobalID;
434
435 if (ParseToken(lltok::equal, "expected '=' after name"))
436 return true;
437 }
438
439 bool HasLinkage;
440 unsigned Linkage, Visibility;
441 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
442 ParseOptionalVisibility(Visibility))
443 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000444
Dan Gohman3845e502009-08-12 23:32:33 +0000445 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
446 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
447 return ParseAlias(Name, NameLoc, Visibility);
448}
449
Chris Lattnerdf986172009-01-02 07:01:27 +0000450/// ParseNamedGlobal:
451/// GlobalVar '=' OptionalVisibility ALIAS ...
452/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
453bool LLParser::ParseNamedGlobal() {
454 assert(Lex.getKind() == lltok::GlobalVar);
455 LocTy NameLoc = Lex.getLoc();
456 std::string Name = Lex.getStrVal();
457 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Chris Lattnerdf986172009-01-02 07:01:27 +0000459 bool HasLinkage;
460 unsigned Linkage, Visibility;
461 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
462 ParseOptionalLinkage(Linkage, HasLinkage) ||
463 ParseOptionalVisibility(Visibility))
464 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000465
Chris Lattnerdf986172009-01-02 07:01:27 +0000466 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
467 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
468 return ParseAlias(Name, NameLoc, Visibility);
469}
470
Devang Patel256be962009-07-20 19:00:08 +0000471// MDString:
472// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000473bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000474 std::string Str;
475 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000476 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000477 return false;
478}
479
480// MDNode:
481// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000482bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000483 // !{ ..., !42, ... }
484 unsigned MID = 0;
485 if (ParseUInt32(MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000486
Devang Patel256be962009-07-20 19:00:08 +0000487 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000488 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000489 if (I != MetadataCache.end()) {
490 Node = I->second;
491 return false;
492 }
493
494 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000495 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000496 FI = ForwardRefMDNodes.find(MID);
497 if (FI != ForwardRefMDNodes.end()) {
498 Node = FI->second.first;
499 return false;
500 }
501
502 // Create MDNode forward reference
503 SmallVector<Value *, 1> Elts;
504 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000505 Elts.push_back(MDString::get(Context, FwdRefName));
506 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000507 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
508 Node = FwdNode;
509 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000510}
Devang Patel256be962009-07-20 19:00:08 +0000511
Devang Pateleff2ab62009-07-29 00:34:02 +0000512///ParseNamedMetadata:
513/// !foo = !{ !1, !2 }
514bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000515 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000516 Lex.Lex();
517 std::string Name = Lex.getStrVal();
518
519 if (ParseToken(lltok::equal, "expected '=' here"))
520 return true;
521
522 if (Lex.getKind() != lltok::Metadata)
523 return TokError("Expected '!' here");
524 Lex.Lex();
525
526 if (Lex.getKind() != lltok::lbrace)
527 return TokError("Expected '{' here");
528 Lex.Lex();
529 SmallVector<MetadataBase *, 8> Elts;
530 do {
531 if (Lex.getKind() != lltok::Metadata)
532 return TokError("Expected '!' here");
533 Lex.Lex();
534 MetadataBase *N = 0;
535 if (ParseMDNode(N)) return true;
536 Elts.push_back(N);
537 } while (EatIfPresent(lltok::comma));
538
539 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
540 return true;
541
Owen Anderson1d0be152009-08-13 21:58:54 +0000542 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000543 return false;
544}
545
Devang Patel923078c2009-07-01 19:21:12 +0000546/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000547/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000548bool LLParser::ParseStandaloneMetadata() {
549 assert(Lex.getKind() == lltok::Metadata);
550 Lex.Lex();
551 unsigned MetadataID = 0;
552 if (ParseUInt32(MetadataID))
553 return true;
554 if (MetadataCache.find(MetadataID) != MetadataCache.end())
555 return TokError("Metadata id is already used");
556 if (ParseToken(lltok::equal, "expected '=' here"))
557 return true;
558
559 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000561 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000562 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000563
Devang Patel104cf9e2009-07-23 01:07:34 +0000564 if (Lex.getKind() != lltok::Metadata)
565 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000566
Devang Patel104cf9e2009-07-23 01:07:34 +0000567 Lex.Lex();
568 if (Lex.getKind() != lltok::lbrace)
569 return TokError("Expected '{' here");
570
571 SmallVector<Value *, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000572 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000573 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000574 return true;
575
Owen Anderson647e3012009-07-31 21:35:40 +0000576 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000577 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000578 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000579 FI = ForwardRefMDNodes.find(MetadataID);
580 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000581 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000582 FwdNode->replaceAllUsesWith(Init);
583 ForwardRefMDNodes.erase(FI);
584 }
585
Devang Patel923078c2009-07-01 19:21:12 +0000586 return false;
587}
588
Chris Lattnerdf986172009-01-02 07:01:27 +0000589/// ParseAlias:
590/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
591/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000592/// ::= TypeAndValue
593/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000594/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000595///
596/// Everything through visibility has already been parsed.
597///
598bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
599 unsigned Visibility) {
600 assert(Lex.getKind() == lltok::kw_alias);
601 Lex.Lex();
602 unsigned Linkage;
603 LocTy LinkageLoc = Lex.getLoc();
604 if (ParseOptionalLinkage(Linkage))
605 return true;
606
607 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000608 Linkage != GlobalValue::WeakAnyLinkage &&
609 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000610 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000611 Linkage != GlobalValue::PrivateLinkage &&
612 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000613 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000614
Chris Lattnerdf986172009-01-02 07:01:27 +0000615 Constant *Aliasee;
616 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000617 if (Lex.getKind() != lltok::kw_bitcast &&
618 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000619 if (ParseGlobalTypeAndValue(Aliasee)) return true;
620 } else {
621 // The bitcast dest type is not present, it is implied by the dest type.
622 ValID ID;
623 if (ParseValID(ID)) return true;
624 if (ID.Kind != ValID::t_Constant)
625 return Error(AliaseeLoc, "invalid aliasee");
626 Aliasee = ID.ConstantVal;
627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000628
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 if (!isa<PointerType>(Aliasee->getType()))
630 return Error(AliaseeLoc, "alias must have pointer type");
631
632 // Okay, create the alias but do not insert it into the module yet.
633 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
634 (GlobalValue::LinkageTypes)Linkage, Name,
635 Aliasee);
636 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000637
Chris Lattnerdf986172009-01-02 07:01:27 +0000638 // See if this value already exists in the symbol table. If so, it is either
639 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000640 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000641 // See if this was a redefinition. If so, there is no entry in
642 // ForwardRefVals.
643 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
644 I = ForwardRefVals.find(Name);
645 if (I == ForwardRefVals.end())
646 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
647
648 // Otherwise, this was a definition of forward ref. Verify that types
649 // agree.
650 if (Val->getType() != GA->getType())
651 return Error(NameLoc,
652 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 // If they agree, just RAUW the old value with the alias and remove the
655 // forward ref info.
656 Val->replaceAllUsesWith(GA);
657 Val->eraseFromParent();
658 ForwardRefVals.erase(I);
659 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000660
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 // Insert into the module, we know its name won't collide now.
662 M->getAliasList().push_back(GA);
663 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000664
Chris Lattnerdf986172009-01-02 07:01:27 +0000665 return false;
666}
667
668/// ParseGlobal
669/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
670/// OptionalAddrSpace GlobalType Type Const
671/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
672/// OptionalAddrSpace GlobalType Type Const
673///
674/// Everything through visibility has been parsed already.
675///
676bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
677 unsigned Linkage, bool HasLinkage,
678 unsigned Visibility) {
679 unsigned AddrSpace;
680 bool ThreadLocal, IsConstant;
681 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000682
Owen Anderson1d0be152009-08-13 21:58:54 +0000683 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000684 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
685 ParseOptionalAddrSpace(AddrSpace) ||
686 ParseGlobalType(IsConstant) ||
687 ParseType(Ty, TyLoc))
688 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000689
Chris Lattnerdf986172009-01-02 07:01:27 +0000690 // If the linkage is specified and is external, then no initializer is
691 // present.
692 Constant *Init = 0;
693 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000694 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000695 Linkage != GlobalValue::ExternalLinkage)) {
696 if (ParseGlobalValue(Ty, Init))
697 return true;
698 }
699
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000700 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000701 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000702
Chris Lattnerdf986172009-01-02 07:01:27 +0000703 GlobalVariable *GV = 0;
704
705 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000706 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000707 if (GlobalValue *GVal = M->getNamedValue(Name)) {
708 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
709 return Error(NameLoc, "redefinition of global '@" + Name + "'");
710 GV = cast<GlobalVariable>(GVal);
711 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000712 } else {
713 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
714 I = ForwardRefValIDs.find(NumberedVals.size());
715 if (I != ForwardRefValIDs.end()) {
716 GV = cast<GlobalVariable>(I->second.first);
717 ForwardRefValIDs.erase(I);
718 }
719 }
720
721 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000722 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000723 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 } else {
725 if (GV->getType()->getElementType() != Ty)
726 return Error(TyLoc,
727 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000728
Chris Lattnerdf986172009-01-02 07:01:27 +0000729 // Move the forward-reference to the correct spot in the module.
730 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
731 }
732
733 if (Name.empty())
734 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattnerdf986172009-01-02 07:01:27 +0000736 // Set the parsed properties on the global.
737 if (Init)
738 GV->setInitializer(Init);
739 GV->setConstant(IsConstant);
740 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
741 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
742 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743
Chris Lattnerdf986172009-01-02 07:01:27 +0000744 // Parse attributes on the global.
745 while (Lex.getKind() == lltok::comma) {
746 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000747
Chris Lattnerdf986172009-01-02 07:01:27 +0000748 if (Lex.getKind() == lltok::kw_section) {
749 Lex.Lex();
750 GV->setSection(Lex.getStrVal());
751 if (ParseToken(lltok::StringConstant, "expected global section string"))
752 return true;
753 } else if (Lex.getKind() == lltok::kw_align) {
754 unsigned Alignment;
755 if (ParseOptionalAlignment(Alignment)) return true;
756 GV->setAlignment(Alignment);
757 } else {
758 TokError("unknown global variable property!");
759 }
760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000761
Chris Lattnerdf986172009-01-02 07:01:27 +0000762 return false;
763}
764
765
766//===----------------------------------------------------------------------===//
767// GlobalValue Reference/Resolution Routines.
768//===----------------------------------------------------------------------===//
769
770/// GetGlobalVal - Get a value with the specified name or ID, creating a
771/// forward reference record if needed. This can return null if the value
772/// exists but does not have the right type.
773GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
774 LocTy Loc) {
775 const PointerType *PTy = dyn_cast<PointerType>(Ty);
776 if (PTy == 0) {
777 Error(Loc, "global variable reference must have pointer type");
778 return 0;
779 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000780
Chris Lattnerdf986172009-01-02 07:01:27 +0000781 // Look this name up in the normal function symbol table.
782 GlobalValue *Val =
783 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 // If this is a forward reference for the value, see if we already created a
786 // forward ref record.
787 if (Val == 0) {
788 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
789 I = ForwardRefVals.find(Name);
790 if (I != ForwardRefVals.end())
791 Val = I->second.first;
792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Chris Lattnerdf986172009-01-02 07:01:27 +0000794 // If we have the value in the symbol table or fwd-ref table, return it.
795 if (Val) {
796 if (Val->getType() == Ty) return Val;
797 Error(Loc, "'@" + Name + "' defined with type '" +
798 Val->getType()->getDescription() + "'");
799 return 0;
800 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000801
Chris Lattnerdf986172009-01-02 07:01:27 +0000802 // Otherwise, create a new forward reference for this value and remember it.
803 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000804 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
805 // Function types can return opaque but functions can't.
806 if (isa<OpaqueType>(FT->getReturnType())) {
807 Error(Loc, "function may not return opaque type");
808 return 0;
809 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000810
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000811 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000812 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000813 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
814 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000816
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
818 return FwdVal;
819}
820
821GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
822 const PointerType *PTy = dyn_cast<PointerType>(Ty);
823 if (PTy == 0) {
824 Error(Loc, "global variable reference must have pointer type");
825 return 0;
826 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000827
Chris Lattnerdf986172009-01-02 07:01:27 +0000828 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000829
Chris Lattnerdf986172009-01-02 07:01:27 +0000830 // If this is a forward reference for the value, see if we already created a
831 // forward ref record.
832 if (Val == 0) {
833 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
834 I = ForwardRefValIDs.find(ID);
835 if (I != ForwardRefValIDs.end())
836 Val = I->second.first;
837 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000838
Chris Lattnerdf986172009-01-02 07:01:27 +0000839 // If we have the value in the symbol table or fwd-ref table, return it.
840 if (Val) {
841 if (Val->getType() == Ty) return Val;
842 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
843 Val->getType()->getDescription() + "'");
844 return 0;
845 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000846
Chris Lattnerdf986172009-01-02 07:01:27 +0000847 // Otherwise, create a new forward reference for this value and remember it.
848 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000849 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
850 // Function types can return opaque but functions can't.
851 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000852 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000853 return 0;
854 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000855 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000856 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000857 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
858 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000859 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000860
Chris Lattnerdf986172009-01-02 07:01:27 +0000861 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
862 return FwdVal;
863}
864
865
866//===----------------------------------------------------------------------===//
867// Helper Routines.
868//===----------------------------------------------------------------------===//
869
870/// ParseToken - If the current token has the specified kind, eat it and return
871/// success. Otherwise, emit the specified error and return failure.
872bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
873 if (Lex.getKind() != T)
874 return TokError(ErrMsg);
875 Lex.Lex();
876 return false;
877}
878
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000879/// ParseStringConstant
880/// ::= StringConstant
881bool LLParser::ParseStringConstant(std::string &Result) {
882 if (Lex.getKind() != lltok::StringConstant)
883 return TokError("expected string constant");
884 Result = Lex.getStrVal();
885 Lex.Lex();
886 return false;
887}
888
889/// ParseUInt32
890/// ::= uint32
891bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000892 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
893 return TokError("expected integer");
894 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
895 if (Val64 != unsigned(Val64))
896 return TokError("expected 32-bit integer (too large)");
897 Val = Val64;
898 Lex.Lex();
899 return false;
900}
901
902
903/// ParseOptionalAddrSpace
904/// := /*empty*/
905/// := 'addrspace' '(' uint32 ')'
906bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
907 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000908 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000909 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000911 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000912 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000913}
Chris Lattnerdf986172009-01-02 07:01:27 +0000914
915/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
916/// indicates what kind of attribute list this is: 0: function arg, 1: result,
917/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000918/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000919bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
920 Attrs = Attribute::None;
921 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000922
Chris Lattnerdf986172009-01-02 07:01:27 +0000923 while (1) {
924 switch (Lex.getKind()) {
925 case lltok::kw_sext:
926 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000927 // Treat these as signext/zeroext if they occur in the argument list after
928 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
929 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
930 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000931 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000932 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 if (Lex.getKind() == lltok::kw_sext)
934 Attrs |= Attribute::SExt;
935 else
936 Attrs |= Attribute::ZExt;
937 break;
938 }
939 // FALL THROUGH.
940 default: // End of attributes.
941 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
942 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000943
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000944 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000945 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000946
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000948 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
949 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
950 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
951 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
952 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
953 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
954 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
955 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000956
Devang Patel578efa92009-06-05 21:57:13 +0000957 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
958 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
959 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
960 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
961 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000962 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000963 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
964 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
965 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
966 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
967 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
968 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000969 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000970
Chris Lattnerdf986172009-01-02 07:01:27 +0000971 case lltok::kw_align: {
972 unsigned Alignment;
973 if (ParseOptionalAlignment(Alignment))
974 return true;
975 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
976 continue;
977 }
978 }
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'
Chris Lattnerdf986172009-01-02 07:01:27 +0000987/// ::= 'internal'
988/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000989/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000990/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000991/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000992/// ::= 'appending'
993/// ::= 'dllexport'
994/// ::= 'common'
995/// ::= 'dllimport'
996/// ::= 'extern_weak'
997/// ::= 'external'
998bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
999 HasLinkage = false;
1000 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001001 default: Res=GlobalValue::ExternalLinkage; return false;
1002 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1003 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1004 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1005 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1006 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1007 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1008 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001009 case lltok::kw_available_externally:
1010 Res = GlobalValue::AvailableExternallyLinkage;
1011 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001012 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1013 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1014 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1015 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1016 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1017 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001018 }
1019 Lex.Lex();
1020 HasLinkage = true;
1021 return false;
1022}
1023
1024/// ParseOptionalVisibility
1025/// ::= /*empty*/
1026/// ::= 'default'
1027/// ::= 'hidden'
1028/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001029///
Chris Lattnerdf986172009-01-02 07:01:27 +00001030bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1031 switch (Lex.getKind()) {
1032 default: Res = GlobalValue::DefaultVisibility; return false;
1033 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1034 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1035 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1036 }
1037 Lex.Lex();
1038 return false;
1039}
1040
1041/// ParseOptionalCallingConv
1042/// ::= /*empty*/
1043/// ::= 'ccc'
1044/// ::= 'fastcc'
1045/// ::= 'coldcc'
1046/// ::= 'x86_stdcallcc'
1047/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001048/// ::= 'arm_apcscc'
1049/// ::= 'arm_aapcscc'
1050/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001051/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001052///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001053bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001054 switch (Lex.getKind()) {
1055 default: CC = CallingConv::C; return false;
1056 case lltok::kw_ccc: CC = CallingConv::C; break;
1057 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1058 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1059 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1060 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001061 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1062 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1063 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001064 case lltok::kw_cc: {
1065 unsigned ArbitraryCC;
1066 Lex.Lex();
1067 if (ParseUInt32(ArbitraryCC)) {
1068 return true;
1069 } else
1070 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1071 return false;
1072 }
1073 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001074 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001075
Chris Lattnerdf986172009-01-02 07:01:27 +00001076 Lex.Lex();
1077 return false;
1078}
1079
Devang Patel0475c912009-09-29 00:01:14 +00001080/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001081/// ::= /* empty */
Devang Patel0475c912009-09-29 00:01:14 +00001082/// ::= !dbg !42
1083bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001084 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001085 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001086
Chris Lattner52e20312009-10-19 05:31:10 +00001087 std::string Name = Lex.getStrVal();
1088 Lex.Lex();
1089
Devang Patelf633a062009-09-17 23:04:48 +00001090 if (Lex.getKind() != lltok::Metadata)
1091 return TokError("Expected '!' here");
1092 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001093
Devang Patelf633a062009-09-17 23:04:48 +00001094 MetadataBase *Node;
1095 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001096
Devang Patele30e6782009-09-28 21:41:20 +00001097 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patel0475c912009-09-29 00:01:14 +00001098 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1099 if (!MDK)
Devang Pateld9723e92009-10-20 22:50:27 +00001100 MDK = TheMetadata.registerMDKind(Name.c_str());
Devang Patel0475c912009-09-29 00:01:14 +00001101 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001102
Devang Patelf633a062009-09-17 23:04:48 +00001103 return false;
1104}
1105
Chris Lattnerdf986172009-01-02 07:01:27 +00001106/// ParseOptionalAlignment
1107/// ::= /* empty */
1108/// ::= 'align' 4
1109bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1110 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001111 if (!EatIfPresent(lltok::kw_align))
1112 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001113 LocTy AlignLoc = Lex.getLoc();
1114 if (ParseUInt32(Alignment)) return true;
1115 if (!isPowerOf2_32(Alignment))
1116 return Error(AlignLoc, "alignment is not a power of two");
1117 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001118}
1119
Devang Patelf633a062009-09-17 23:04:48 +00001120/// ParseOptionalInfo
1121/// ::= OptionalInfo (',' OptionalInfo)+
1122bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1123
1124 // FIXME: Handle customized metadata info attached with an instruction.
1125 do {
Devang Patel0475c912009-09-29 00:01:14 +00001126 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1127 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001128 } else if (Lex.getKind() == lltok::kw_align) {
1129 if (ParseOptionalAlignment(Alignment)) return true;
1130 } else
1131 return true;
1132 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001133
Devang Patelf633a062009-09-17 23:04:48 +00001134 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001135}
1136
Devang Patelf633a062009-09-17 23:04:48 +00001137
Chris Lattnerdf986172009-01-02 07:01:27 +00001138/// ParseIndexList
1139/// ::= (',' uint32)+
1140bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1141 if (Lex.getKind() != lltok::comma)
1142 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001143
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001144 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001145 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001146 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001147 Indices.push_back(Idx);
1148 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001149
Chris Lattnerdf986172009-01-02 07:01:27 +00001150 return false;
1151}
1152
1153//===----------------------------------------------------------------------===//
1154// Type Parsing.
1155//===----------------------------------------------------------------------===//
1156
1157/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001158bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1159 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001160 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001161
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 // Verify no unresolved uprefs.
1163 if (!UpRefs.empty())
1164 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001165
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001166 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001167 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001168
Chris Lattnerdf986172009-01-02 07:01:27 +00001169 return false;
1170}
1171
1172/// HandleUpRefs - Every time we finish a new layer of types, this function is
1173/// called. It loops through the UpRefs vector, which is a list of the
1174/// currently active types. For each type, if the up-reference is contained in
1175/// the newly completed type, we decrement the level count. When the level
1176/// count reaches zero, the up-referenced type is the type that is passed in:
1177/// thus we can complete the cycle.
1178///
1179PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1180 // If Ty isn't abstract, or if there are no up-references in it, then there is
1181 // nothing to resolve here.
1182 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001183
Chris Lattnerdf986172009-01-02 07:01:27 +00001184 PATypeHolder Ty(ty);
1185#if 0
1186 errs() << "Type '" << Ty->getDescription()
1187 << "' newly formed. Resolving upreferences.\n"
1188 << UpRefs.size() << " upreferences active!\n";
1189#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001190
Chris Lattnerdf986172009-01-02 07:01:27 +00001191 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1192 // to zero), we resolve them all together before we resolve them to Ty. At
1193 // the end of the loop, if there is anything to resolve to Ty, it will be in
1194 // this variable.
1195 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001196
Chris Lattnerdf986172009-01-02 07:01:27 +00001197 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1198 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1199 bool ContainsType =
1200 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1201 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202
Chris Lattnerdf986172009-01-02 07:01:27 +00001203#if 0
1204 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1205 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1206 << (ContainsType ? "true" : "false")
1207 << " level=" << UpRefs[i].NestingLevel << "\n";
1208#endif
1209 if (!ContainsType)
1210 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001211
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 // Decrement level of upreference
1213 unsigned Level = --UpRefs[i].NestingLevel;
1214 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001215
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1217 if (Level != 0)
1218 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001219
Chris Lattnerdf986172009-01-02 07:01:27 +00001220#if 0
1221 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1222#endif
1223 if (!TypeToResolve)
1224 TypeToResolve = UpRefs[i].UpRefTy;
1225 else
1226 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1227 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1228 --i; // Do not skip the next element.
1229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001230
Chris Lattnerdf986172009-01-02 07:01:27 +00001231 if (TypeToResolve)
1232 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001233
Chris Lattnerdf986172009-01-02 07:01:27 +00001234 return Ty;
1235}
1236
1237
1238/// ParseTypeRec - The recursive function used to process the internal
1239/// implementation details of types.
1240bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1241 switch (Lex.getKind()) {
1242 default:
1243 return TokError("expected type");
1244 case lltok::Type:
1245 // TypeRec ::= 'float' | 'void' (etc)
1246 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001247 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 break;
1249 case lltok::kw_opaque:
1250 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001251 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001252 Lex.Lex();
1253 break;
1254 case lltok::lbrace:
1255 // TypeRec ::= '{' ... '}'
1256 if (ParseStructType(Result, false))
1257 return true;
1258 break;
1259 case lltok::lsquare:
1260 // TypeRec ::= '[' ... ']'
1261 Lex.Lex(); // eat the lsquare.
1262 if (ParseArrayVectorType(Result, false))
1263 return true;
1264 break;
1265 case lltok::less: // Either vector or packed struct.
1266 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001267 Lex.Lex();
1268 if (Lex.getKind() == lltok::lbrace) {
1269 if (ParseStructType(Result, true) ||
1270 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 } else if (ParseArrayVectorType(Result, true))
1273 return true;
1274 break;
1275 case lltok::LocalVar:
1276 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1277 // TypeRec ::= %foo
1278 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1279 Result = T;
1280 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001281 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001282 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1283 std::make_pair(Result,
1284 Lex.getLoc())));
1285 M->addTypeName(Lex.getStrVal(), Result.get());
1286 }
1287 Lex.Lex();
1288 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 case lltok::LocalVarID:
1291 // TypeRec ::= %4
1292 if (Lex.getUIntVal() < NumberedTypes.size())
1293 Result = NumberedTypes[Lex.getUIntVal()];
1294 else {
1295 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1296 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1297 if (I != ForwardRefTypeIDs.end())
1298 Result = I->second.first;
1299 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001300 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1302 std::make_pair(Result,
1303 Lex.getLoc())));
1304 }
1305 }
1306 Lex.Lex();
1307 break;
1308 case lltok::backslash: {
1309 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001311 unsigned Val;
1312 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001313 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1315 Result = OT;
1316 break;
1317 }
1318 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001319
1320 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 while (1) {
1322 switch (Lex.getKind()) {
1323 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001324 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001325
1326 // TypeRec ::= TypeRec '*'
1327 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001328 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001330 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001331 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001332 if (!PointerType::isValidElementType(Result.get()))
1333 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001334 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001335 Lex.Lex();
1336 break;
1337
1338 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1339 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001340 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001341 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001342 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001343 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001344 if (!PointerType::isValidElementType(Result.get()))
1345 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 unsigned AddrSpace;
1347 if (ParseOptionalAddrSpace(AddrSpace) ||
1348 ParseToken(lltok::star, "expected '*' in address space"))
1349 return true;
1350
Owen Andersondebcb012009-07-29 22:17:13 +00001351 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 break;
1353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001354
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1356 case lltok::lparen:
1357 if (ParseFunctionType(Result))
1358 return true;
1359 break;
1360 }
1361 }
1362}
1363
1364/// ParseParameterList
1365/// ::= '(' ')'
1366/// ::= '(' Arg (',' Arg)* ')'
1367/// Arg
1368/// ::= Type OptionalAttributes Value OptionalAttributes
1369bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1370 PerFunctionState &PFS) {
1371 if (ParseToken(lltok::lparen, "expected '(' in call"))
1372 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001373
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 while (Lex.getKind() != lltok::rparen) {
1375 // If this isn't the first argument, we need a comma.
1376 if (!ArgList.empty() &&
1377 ParseToken(lltok::comma, "expected ',' in argument list"))
1378 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001379
Chris Lattnerdf986172009-01-02 07:01:27 +00001380 // Parse the argument.
1381 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001382 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001383 unsigned ArgAttrs1, ArgAttrs2;
1384 Value *V;
1385 if (ParseType(ArgTy, ArgLoc) ||
1386 ParseOptionalAttrs(ArgAttrs1, 0) ||
1387 ParseValue(ArgTy, V, PFS) ||
1388 // FIXME: Should not allow attributes after the argument, remove this in
1389 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001390 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001391 return true;
1392 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1393 }
1394
1395 Lex.Lex(); // Lex the ')'.
1396 return false;
1397}
1398
1399
1400
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001401/// ParseArgumentList - Parse the argument list for a function type or function
1402/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001403/// ::= '(' ArgTypeListI ')'
1404/// ArgTypeListI
1405/// ::= /*empty*/
1406/// ::= '...'
1407/// ::= ArgTypeList ',' '...'
1408/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001409///
Chris Lattnerdf986172009-01-02 07:01:27 +00001410bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001411 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001412 isVarArg = false;
1413 assert(Lex.getKind() == lltok::lparen);
1414 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001415
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 if (Lex.getKind() == lltok::rparen) {
1417 // empty
1418 } else if (Lex.getKind() == lltok::dotdotdot) {
1419 isVarArg = true;
1420 Lex.Lex();
1421 } else {
1422 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001423 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001426
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001427 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1428 // types (such as a function returning a pointer to itself). If parsing a
1429 // function prototype, we require fully resolved types.
1430 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001431 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001432
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001433 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001434 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001435
Chris Lattnerdf986172009-01-02 07:01:27 +00001436 if (Lex.getKind() == lltok::LocalVar ||
1437 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1438 Name = Lex.getStrVal();
1439 Lex.Lex();
1440 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001441
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001442 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001443 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001444
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001447 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001449 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001450 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001451 break;
1452 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001453
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 // Otherwise must be an argument type.
1455 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001456 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001457 ParseOptionalAttrs(Attrs, 0)) return true;
1458
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001459 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001460 return Error(TypeLoc, "argument can not have void type");
1461
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 if (Lex.getKind() == lltok::LocalVar ||
1463 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1464 Name = Lex.getStrVal();
1465 Lex.Lex();
1466 } else {
1467 Name = "";
1468 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001469
1470 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1471 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001472
Chris Lattnerdf986172009-01-02 07:01:27 +00001473 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1474 }
1475 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001477 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001478}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Chris Lattnerdf986172009-01-02 07:01:27 +00001480/// ParseFunctionType
1481/// ::= Type ArgumentList OptionalAttrs
1482bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1483 assert(Lex.getKind() == lltok::lparen);
1484
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001485 if (!FunctionType::isValidReturnType(Result))
1486 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattnerdf986172009-01-02 07:01:27 +00001488 std::vector<ArgInfo> ArgList;
1489 bool isVarArg;
1490 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001491 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 // FIXME: Allow, but ignore attributes on function types!
1493 // FIXME: Remove in LLVM 3.0
1494 ParseOptionalAttrs(Attrs, 2))
1495 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001496
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 // Reject names on the arguments lists.
1498 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1499 if (!ArgList[i].Name.empty())
1500 return Error(ArgList[i].Loc, "argument name invalid in function type");
1501 if (!ArgList[i].Attrs != 0) {
1502 // Allow but ignore attributes on function types; this permits
1503 // auto-upgrade.
1504 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1505 }
1506 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001507
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 std::vector<const Type*> ArgListTy;
1509 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1510 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001511
Owen Andersondebcb012009-07-29 22:17:13 +00001512 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001513 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001514 return false;
1515}
1516
1517/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1518/// TypeRec
1519/// ::= '{' '}'
1520/// ::= '{' TypeRec (',' TypeRec)* '}'
1521/// ::= '<' '{' '}' '>'
1522/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1523bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1524 assert(Lex.getKind() == lltok::lbrace);
1525 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001527 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001528 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001529 return false;
1530 }
1531
1532 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001533 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001534 if (ParseTypeRec(Result)) return true;
1535 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001537 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001538 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001539 if (!StructType::isValidElementType(Result))
1540 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001542 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001543 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001546 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001547 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001548 if (!StructType::isValidElementType(Result))
1549 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Chris Lattnerdf986172009-01-02 07:01:27 +00001551 ParamsList.push_back(Result);
1552 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001553
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001554 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1555 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001556
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 std::vector<const Type*> ParamsListTy;
1558 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1559 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001560 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 return false;
1562}
1563
1564/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1565/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001566/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001567/// ::= '[' APSINTVAL 'x' Types ']'
1568/// ::= '<' APSINTVAL 'x' Types '>'
1569bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1570 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1571 Lex.getAPSIntVal().getBitWidth() > 64)
1572 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001573
Chris Lattnerdf986172009-01-02 07:01:27 +00001574 LocTy SizeLoc = Lex.getLoc();
1575 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001576 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001577
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001578 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1579 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001580
1581 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001582 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001583 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001584
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001585 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001586 return Error(TypeLoc, "array and vector element type cannot be void");
1587
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001588 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1589 "expected end of sequential type"))
1590 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001591
Chris Lattnerdf986172009-01-02 07:01:27 +00001592 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001593 if (Size == 0)
1594 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 if ((unsigned)Size != Size)
1596 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001597 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001599 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001600 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001601 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001602 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001603 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001604 }
1605 return false;
1606}
1607
1608//===----------------------------------------------------------------------===//
1609// Function Semantic Analysis.
1610//===----------------------------------------------------------------------===//
1611
Chris Lattner09d9ef42009-10-28 03:39:23 +00001612LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1613 int functionNumber)
1614 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001615
1616 // Insert unnamed arguments into the NumberedVals list.
1617 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1618 AI != E; ++AI)
1619 if (!AI->hasName())
1620 NumberedVals.push_back(AI);
1621}
1622
1623LLParser::PerFunctionState::~PerFunctionState() {
1624 // If there were any forward referenced non-basicblock values, delete them.
1625 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1626 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1627 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001628 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001629 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001630 delete I->second.first;
1631 I->second.first = 0;
1632 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattnerdf986172009-01-02 07:01:27 +00001634 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1635 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1636 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001637 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001638 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001639 delete I->second.first;
1640 I->second.first = 0;
1641 }
1642}
1643
Chris Lattner09d9ef42009-10-28 03:39:23 +00001644bool LLParser::PerFunctionState::FinishFunction() {
1645 // Check to see if someone took the address of labels in this block.
1646 if (!P.ForwardRefBlockAddresses.empty()) {
1647 ValID FunctionID;
1648 if (!F.getName().empty()) {
1649 FunctionID.Kind = ValID::t_GlobalName;
1650 FunctionID.StrVal = F.getName();
1651 } else {
1652 FunctionID.Kind = ValID::t_GlobalID;
1653 FunctionID.UIntVal = FunctionNumber;
1654 }
1655
1656 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1657 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1658 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1659 // Resolve all these references.
1660 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1661 return true;
1662
1663 P.ForwardRefBlockAddresses.erase(FRBAI);
1664 }
1665 }
1666
Chris Lattnerdf986172009-01-02 07:01:27 +00001667 if (!ForwardRefVals.empty())
1668 return P.Error(ForwardRefVals.begin()->second.second,
1669 "use of undefined value '%" + ForwardRefVals.begin()->first +
1670 "'");
1671 if (!ForwardRefValIDs.empty())
1672 return P.Error(ForwardRefValIDs.begin()->second.second,
1673 "use of undefined value '%" +
1674 utostr(ForwardRefValIDs.begin()->first) + "'");
1675 return false;
1676}
1677
1678
1679/// GetVal - Get a value with the specified name or ID, creating a
1680/// forward reference record if needed. This can return null if the value
1681/// exists but does not have the right type.
1682Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1683 const Type *Ty, LocTy Loc) {
1684 // Look this name up in the normal function symbol table.
1685 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001686
Chris Lattnerdf986172009-01-02 07:01:27 +00001687 // If this is a forward reference for the value, see if we already created a
1688 // forward ref record.
1689 if (Val == 0) {
1690 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1691 I = ForwardRefVals.find(Name);
1692 if (I != ForwardRefVals.end())
1693 Val = I->second.first;
1694 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001695
Chris Lattnerdf986172009-01-02 07:01:27 +00001696 // If we have the value in the symbol table or fwd-ref table, return it.
1697 if (Val) {
1698 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001699 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001700 P.Error(Loc, "'%" + Name + "' is not a basic block");
1701 else
1702 P.Error(Loc, "'%" + Name + "' defined with type '" +
1703 Val->getType()->getDescription() + "'");
1704 return 0;
1705 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001706
Chris Lattnerdf986172009-01-02 07:01:27 +00001707 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001708 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1709 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 P.Error(Loc, "invalid use of a non-first-class type");
1711 return 0;
1712 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001713
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 // Otherwise, create a new forward reference for this value and remember it.
1715 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001716 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001717 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 else
1719 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1722 return FwdVal;
1723}
1724
1725Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1726 LocTy Loc) {
1727 // Look this name up in the normal function symbol table.
1728 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001729
Chris Lattnerdf986172009-01-02 07:01:27 +00001730 // If this is a forward reference for the value, see if we already created a
1731 // forward ref record.
1732 if (Val == 0) {
1733 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1734 I = ForwardRefValIDs.find(ID);
1735 if (I != ForwardRefValIDs.end())
1736 Val = I->second.first;
1737 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001738
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 // If we have the value in the symbol table or fwd-ref table, return it.
1740 if (Val) {
1741 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001742 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1744 else
1745 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1746 Val->getType()->getDescription() + "'");
1747 return 0;
1748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001749
Owen Anderson1d0be152009-08-13 21:58:54 +00001750 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1751 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 P.Error(Loc, "invalid use of a non-first-class type");
1753 return 0;
1754 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001755
Chris Lattnerdf986172009-01-02 07:01:27 +00001756 // Otherwise, create a new forward reference for this value and remember it.
1757 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001758 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001759 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001760 else
1761 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattnerdf986172009-01-02 07:01:27 +00001763 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1764 return FwdVal;
1765}
1766
1767/// SetInstName - After an instruction is parsed and inserted into its
1768/// basic block, this installs its name.
1769bool LLParser::PerFunctionState::SetInstName(int NameID,
1770 const std::string &NameStr,
1771 LocTy NameLoc, Instruction *Inst) {
1772 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001773 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 if (NameID != -1 || !NameStr.empty())
1775 return P.Error(NameLoc, "instructions returning void cannot have a name");
1776 return false;
1777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001778
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 // If this was a numbered instruction, verify that the instruction is the
1780 // expected value and resolve any forward references.
1781 if (NameStr.empty()) {
1782 // If neither a name nor an ID was specified, just use the next ID.
1783 if (NameID == -1)
1784 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001785
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 if (unsigned(NameID) != NumberedVals.size())
1787 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1788 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001789
Chris Lattnerdf986172009-01-02 07:01:27 +00001790 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1791 ForwardRefValIDs.find(NameID);
1792 if (FI != ForwardRefValIDs.end()) {
1793 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001794 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001795 FI->second.first->getType()->getDescription() + "'");
1796 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001797 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 ForwardRefValIDs.erase(FI);
1799 }
1800
1801 NumberedVals.push_back(Inst);
1802 return false;
1803 }
1804
1805 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1806 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1807 FI = ForwardRefVals.find(NameStr);
1808 if (FI != ForwardRefVals.end()) {
1809 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001810 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 FI->second.first->getType()->getDescription() + "'");
1812 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001813 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001814 ForwardRefVals.erase(FI);
1815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001816
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 // Set the name on the instruction.
1818 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001819
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 NameStr + "'");
1823 return false;
1824}
1825
1826/// GetBB - Get a basic block with the specified name or ID, creating a
1827/// forward reference record if needed.
1828BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1829 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001830 return cast_or_null<BasicBlock>(GetVal(Name,
1831 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001832}
1833
1834BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001835 return cast_or_null<BasicBlock>(GetVal(ID,
1836 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001837}
1838
1839/// DefineBB - Define the specified basic block, which is either named or
1840/// unnamed. If there is an error, this returns null otherwise it returns
1841/// the block being defined.
1842BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1843 LocTy Loc) {
1844 BasicBlock *BB;
1845 if (Name.empty())
1846 BB = GetBB(NumberedVals.size(), Loc);
1847 else
1848 BB = GetBB(Name, Loc);
1849 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 // Move the block to the end of the function. Forward ref'd blocks are
1852 // inserted wherever they happen to be referenced.
1853 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001854
Chris Lattnerdf986172009-01-02 07:01:27 +00001855 // Remove the block from forward ref sets.
1856 if (Name.empty()) {
1857 ForwardRefValIDs.erase(NumberedVals.size());
1858 NumberedVals.push_back(BB);
1859 } else {
1860 // BB forward references are already in the function symbol table.
1861 ForwardRefVals.erase(Name);
1862 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 return BB;
1865}
1866
1867//===----------------------------------------------------------------------===//
1868// Constants.
1869//===----------------------------------------------------------------------===//
1870
1871/// ParseValID - Parse an abstract value that doesn't necessarily have a
1872/// type implied. For example, if we parse "4" we don't know what integer type
1873/// it has. The value will later be combined with its type and checked for
1874/// sanity.
1875bool LLParser::ParseValID(ValID &ID) {
1876 ID.Loc = Lex.getLoc();
1877 switch (Lex.getKind()) {
1878 default: return TokError("expected value token");
1879 case lltok::GlobalID: // @42
1880 ID.UIntVal = Lex.getUIntVal();
1881 ID.Kind = ValID::t_GlobalID;
1882 break;
1883 case lltok::GlobalVar: // @foo
1884 ID.StrVal = Lex.getStrVal();
1885 ID.Kind = ValID::t_GlobalName;
1886 break;
1887 case lltok::LocalVarID: // %42
1888 ID.UIntVal = Lex.getUIntVal();
1889 ID.Kind = ValID::t_LocalID;
1890 break;
1891 case lltok::LocalVar: // %foo
1892 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1893 ID.StrVal = Lex.getStrVal();
1894 ID.Kind = ValID::t_LocalName;
1895 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001896 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001897 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001898 Lex.Lex();
1899 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001900 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001901 if (ParseMDNodeVector(Elts) ||
1902 ParseToken(lltok::rbrace, "expected end of metadata node"))
1903 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001904
Owen Anderson647e3012009-07-31 21:35:40 +00001905 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001906 return false;
1907 }
1908
Devang Patel923078c2009-07-01 19:21:12 +00001909 // Standalone metadata reference
1910 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001911 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001912 return false;
Devang Patel256be962009-07-20 19:00:08 +00001913
Nick Lewycky21cc4462009-04-04 07:22:01 +00001914 // MDString:
1915 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001916 if (ParseMDString(ID.MetadataVal)) return true;
1917 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001918 return false;
1919 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001920 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 ID.Kind = ValID::t_APSInt;
1923 break;
1924 case lltok::APFloat:
1925 ID.APFloatVal = Lex.getAPFloatVal();
1926 ID.Kind = ValID::t_APFloat;
1927 break;
1928 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001929 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001930 ID.Kind = ValID::t_Constant;
1931 break;
1932 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001933 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001934 ID.Kind = ValID::t_Constant;
1935 break;
1936 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1937 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1938 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 case lltok::lbrace: {
1941 // ValID ::= '{' ConstVector '}'
1942 Lex.Lex();
1943 SmallVector<Constant*, 16> Elts;
1944 if (ParseGlobalValueVector(Elts) ||
1945 ParseToken(lltok::rbrace, "expected end of struct constant"))
1946 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001948 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1949 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001950 ID.Kind = ValID::t_Constant;
1951 return false;
1952 }
1953 case lltok::less: {
1954 // ValID ::= '<' ConstVector '>' --> Vector.
1955 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1956 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001957 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 SmallVector<Constant*, 16> Elts;
1960 LocTy FirstEltLoc = Lex.getLoc();
1961 if (ParseGlobalValueVector(Elts) ||
1962 (isPackedStruct &&
1963 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1964 ParseToken(lltok::greater, "expected end of constant"))
1965 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001966
Chris Lattnerdf986172009-01-02 07:01:27 +00001967 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001968 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001969 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001970 ID.Kind = ValID::t_Constant;
1971 return false;
1972 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001973
Chris Lattnerdf986172009-01-02 07:01:27 +00001974 if (Elts.empty())
1975 return Error(ID.Loc, "constant vector must not be empty");
1976
1977 if (!Elts[0]->getType()->isInteger() &&
1978 !Elts[0]->getType()->isFloatingPoint())
1979 return Error(FirstEltLoc,
1980 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001981
Chris Lattnerdf986172009-01-02 07:01:27 +00001982 // Verify that all the vector elements have the same type.
1983 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1984 if (Elts[i]->getType() != Elts[0]->getType())
1985 return Error(FirstEltLoc,
1986 "vector element #" + utostr(i) +
1987 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988
Owen Andersonaf7ec972009-07-28 21:19:26 +00001989 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001990 ID.Kind = ValID::t_Constant;
1991 return false;
1992 }
1993 case lltok::lsquare: { // Array Constant
1994 Lex.Lex();
1995 SmallVector<Constant*, 16> Elts;
1996 LocTy FirstEltLoc = Lex.getLoc();
1997 if (ParseGlobalValueVector(Elts) ||
1998 ParseToken(lltok::rsquare, "expected end of array constant"))
1999 return true;
2000
2001 // Handle empty element.
2002 if (Elts.empty()) {
2003 // Use undef instead of an array because it's inconvenient to determine
2004 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002005 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002006 return false;
2007 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002012
Owen Andersondebcb012009-07-29 22:17:13 +00002013 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002014
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002016 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 if (Elts[i]->getType() != Elts[0]->getType())
2018 return Error(FirstEltLoc,
2019 "array element #" + utostr(i) +
2020 " is not of type '" +Elts[0]->getType()->getDescription());
2021 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Owen Anderson1fd70962009-07-28 18:32:17 +00002023 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002024 ID.Kind = ValID::t_Constant;
2025 return false;
2026 }
2027 case lltok::kw_c: // c "foo"
2028 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002029 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002030 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2031 ID.Kind = ValID::t_Constant;
2032 return false;
2033
2034 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002035 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2036 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002037 Lex.Lex();
2038 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002039 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002040 ParseStringConstant(ID.StrVal) ||
2041 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002042 ParseToken(lltok::StringConstant, "expected constraint string"))
2043 return true;
2044 ID.StrVal2 = Lex.getStrVal();
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002045 ID.UIntVal = HasSideEffect | ((unsigned)AlignStack<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002046 ID.Kind = ValID::t_InlineAsm;
2047 return false;
2048 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002049
Chris Lattner09d9ef42009-10-28 03:39:23 +00002050 case lltok::kw_blockaddress: {
2051 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2052 Lex.Lex();
2053
2054 ValID Fn, Label;
2055 LocTy FnLoc, LabelLoc;
2056
2057 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2058 ParseValID(Fn) ||
2059 ParseToken(lltok::comma, "expected comma in block address expression")||
2060 ParseValID(Label) ||
2061 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2062 return true;
Chris Lattner7d83ebc2009-10-31 20:08:37 +00002063
Chris Lattner09d9ef42009-10-28 03:39:23 +00002064 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2065 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattner7d83ebc2009-10-31 20:08:37 +00002066 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName &&
2067 Label.Kind != ValID::t_Null)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002068 return Error(Label.Loc, "expected basic block name in blockaddress");
2069
2070 // Make a global variable as a placeholder for this reference.
2071 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2072 false, GlobalValue::InternalLinkage,
2073 0, "");
2074 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2075 ID.ConstantVal = FwdRef;
2076 ID.Kind = ValID::t_Constant;
2077 return false;
2078 }
2079
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 case lltok::kw_trunc:
2081 case lltok::kw_zext:
2082 case lltok::kw_sext:
2083 case lltok::kw_fptrunc:
2084 case lltok::kw_fpext:
2085 case lltok::kw_bitcast:
2086 case lltok::kw_uitofp:
2087 case lltok::kw_sitofp:
2088 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002091 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002093 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 Constant *SrcVal;
2095 Lex.Lex();
2096 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2097 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002098 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 ParseType(DestTy) ||
2100 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2101 return true;
2102 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2103 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2104 SrcVal->getType()->getDescription() + "' to '" +
2105 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002106 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002107 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 ID.Kind = ValID::t_Constant;
2109 return false;
2110 }
2111 case lltok::kw_extractvalue: {
2112 Lex.Lex();
2113 Constant *Val;
2114 SmallVector<unsigned, 4> Indices;
2115 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2116 ParseGlobalTypeAndValue(Val) ||
2117 ParseIndexList(Indices) ||
2118 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2119 return true;
2120 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2121 return Error(ID.Loc, "extractvalue operand must be array or struct");
2122 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2123 Indices.end()))
2124 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002125 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002126 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002127 ID.Kind = ValID::t_Constant;
2128 return false;
2129 }
2130 case lltok::kw_insertvalue: {
2131 Lex.Lex();
2132 Constant *Val0, *Val1;
2133 SmallVector<unsigned, 4> Indices;
2134 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2135 ParseGlobalTypeAndValue(Val0) ||
2136 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2137 ParseGlobalTypeAndValue(Val1) ||
2138 ParseIndexList(Indices) ||
2139 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2140 return true;
2141 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2142 return Error(ID.Loc, "extractvalue operand must be array or struct");
2143 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2144 Indices.end()))
2145 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002146 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002147 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002148 ID.Kind = ValID::t_Constant;
2149 return false;
2150 }
2151 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002152 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 unsigned PredVal, Opc = Lex.getUIntVal();
2154 Constant *Val0, *Val1;
2155 Lex.Lex();
2156 if (ParseCmpPredicate(PredVal, Opc) ||
2157 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2158 ParseGlobalTypeAndValue(Val0) ||
2159 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2160 ParseGlobalTypeAndValue(Val1) ||
2161 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2162 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 if (Val0->getType() != Val1->getType())
2165 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002166
Chris Lattnerdf986172009-01-02 07:01:27 +00002167 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002168
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 if (Opc == Instruction::FCmp) {
2170 if (!Val0->getType()->isFPOrFPVector())
2171 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002172 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002173 } else {
2174 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 if (!Val0->getType()->isIntOrIntVector() &&
2176 !isa<PointerType>(Val0->getType()))
2177 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002178 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 }
2180 ID.Kind = ValID::t_Constant;
2181 return false;
2182 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002183
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 // Binary Operators.
2185 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002186 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002187 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002188 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002189 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002190 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002191 case lltok::kw_udiv:
2192 case lltok::kw_sdiv:
2193 case lltok::kw_fdiv:
2194 case lltok::kw_urem:
2195 case lltok::kw_srem:
2196 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002197 bool NUW = false;
2198 bool NSW = false;
2199 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002200 unsigned Opc = Lex.getUIntVal();
2201 Constant *Val0, *Val1;
2202 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002203 LocTy ModifierLoc = Lex.getLoc();
2204 if (Opc == Instruction::Add ||
2205 Opc == Instruction::Sub ||
2206 Opc == Instruction::Mul) {
2207 if (EatIfPresent(lltok::kw_nuw))
2208 NUW = true;
2209 if (EatIfPresent(lltok::kw_nsw)) {
2210 NSW = true;
2211 if (EatIfPresent(lltok::kw_nuw))
2212 NUW = true;
2213 }
2214 } else if (Opc == Instruction::SDiv) {
2215 if (EatIfPresent(lltok::kw_exact))
2216 Exact = true;
2217 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2219 ParseGlobalTypeAndValue(Val0) ||
2220 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2221 ParseGlobalTypeAndValue(Val1) ||
2222 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2223 return true;
2224 if (Val0->getType() != Val1->getType())
2225 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002226 if (!Val0->getType()->isIntOrIntVector()) {
2227 if (NUW)
2228 return Error(ModifierLoc, "nuw only applies to integer operations");
2229 if (NSW)
2230 return Error(ModifierLoc, "nsw only applies to integer operations");
2231 }
2232 // API compatibility: Accept either integer or floating-point types with
2233 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 if (!Val0->getType()->isIntOrIntVector() &&
2235 !Val0->getType()->isFPOrFPVector())
2236 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002237 unsigned Flags = 0;
2238 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2239 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2240 if (Exact) Flags |= SDivOperator::IsExact;
2241 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002242 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002243 ID.Kind = ValID::t_Constant;
2244 return false;
2245 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002246
Chris Lattnerdf986172009-01-02 07:01:27 +00002247 // Logical Operations
2248 case lltok::kw_shl:
2249 case lltok::kw_lshr:
2250 case lltok::kw_ashr:
2251 case lltok::kw_and:
2252 case lltok::kw_or:
2253 case lltok::kw_xor: {
2254 unsigned Opc = Lex.getUIntVal();
2255 Constant *Val0, *Val1;
2256 Lex.Lex();
2257 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2258 ParseGlobalTypeAndValue(Val0) ||
2259 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2260 ParseGlobalTypeAndValue(Val1) ||
2261 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2262 return true;
2263 if (Val0->getType() != Val1->getType())
2264 return Error(ID.Loc, "operands of constexpr must have same type");
2265 if (!Val0->getType()->isIntOrIntVector())
2266 return Error(ID.Loc,
2267 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002268 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002269 ID.Kind = ValID::t_Constant;
2270 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271 }
2272
Chris Lattnerdf986172009-01-02 07:01:27 +00002273 case lltok::kw_getelementptr:
2274 case lltok::kw_shufflevector:
2275 case lltok::kw_insertelement:
2276 case lltok::kw_extractelement:
2277 case lltok::kw_select: {
2278 unsigned Opc = Lex.getUIntVal();
2279 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002280 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002281 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002282 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002283 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2285 ParseGlobalValueVector(Elts) ||
2286 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2287 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002288
Chris Lattnerdf986172009-01-02 07:01:27 +00002289 if (Opc == Instruction::GetElementPtr) {
2290 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2291 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002292
Chris Lattnerdf986172009-01-02 07:01:27 +00002293 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002294 (Value**)(Elts.data() + 1),
2295 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002297 ID.ConstantVal = InBounds ?
2298 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2299 Elts.data() + 1,
2300 Elts.size() - 1) :
2301 ConstantExpr::getGetElementPtr(Elts[0],
2302 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002303 } else if (Opc == Instruction::Select) {
2304 if (Elts.size() != 3)
2305 return Error(ID.Loc, "expected three operands to select");
2306 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2307 Elts[2]))
2308 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002309 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 } else if (Opc == Instruction::ShuffleVector) {
2311 if (Elts.size() != 3)
2312 return Error(ID.Loc, "expected three operands to shufflevector");
2313 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2314 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002315 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002316 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002317 } else if (Opc == Instruction::ExtractElement) {
2318 if (Elts.size() != 2)
2319 return Error(ID.Loc, "expected two operands to extractelement");
2320 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2321 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002322 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 } else {
2324 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2325 if (Elts.size() != 3)
2326 return Error(ID.Loc, "expected three operands to insertelement");
2327 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2328 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002329 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002330 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002331 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002332
Chris Lattnerdf986172009-01-02 07:01:27 +00002333 ID.Kind = ValID::t_Constant;
2334 return false;
2335 }
2336 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002337
Chris Lattnerdf986172009-01-02 07:01:27 +00002338 Lex.Lex();
2339 return false;
2340}
2341
2342/// ParseGlobalValue - Parse a global value with the specified type.
2343bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2344 V = 0;
2345 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002346 return ParseValID(ID) ||
2347 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002348}
2349
2350/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2351/// constant.
2352bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2353 Constant *&V) {
2354 if (isa<FunctionType>(Ty))
2355 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002356
Chris Lattnerdf986172009-01-02 07:01:27 +00002357 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002358 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002359 case ValID::t_Metadata:
2360 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002361 case ValID::t_LocalID:
2362 case ValID::t_LocalName:
2363 return Error(ID.Loc, "invalid use of function-local name");
2364 case ValID::t_InlineAsm:
2365 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2366 case ValID::t_GlobalName:
2367 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2368 return V == 0;
2369 case ValID::t_GlobalID:
2370 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2371 return V == 0;
2372 case ValID::t_APSInt:
2373 if (!isa<IntegerType>(Ty))
2374 return Error(ID.Loc, "integer constant must have integer type");
2375 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002376 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002377 return false;
2378 case ValID::t_APFloat:
2379 if (!Ty->isFloatingPoint() ||
2380 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2381 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002382
Chris Lattnerdf986172009-01-02 07:01:27 +00002383 // The lexer has no type info, so builds all float and double FP constants
2384 // as double. Fix this here. Long double does not need this.
2385 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002386 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 bool Ignored;
2388 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2389 &Ignored);
2390 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002391 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002392
Chris Lattner959873d2009-01-05 18:24:23 +00002393 if (V->getType() != Ty)
2394 return Error(ID.Loc, "floating point constant does not have type '" +
2395 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002396
Chris Lattnerdf986172009-01-02 07:01:27 +00002397 return false;
2398 case ValID::t_Null:
2399 if (!isa<PointerType>(Ty))
2400 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002401 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 return false;
2403 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002404 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002405 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002406 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002407 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002408 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002410 case ValID::t_EmptyArray:
2411 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2412 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002413 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002414 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002416 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002417 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002419 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002420 return false;
2421 case ValID::t_Constant:
2422 if (ID.ConstantVal->getType() != Ty)
2423 return Error(ID.Loc, "constant expression type mismatch");
2424 V = ID.ConstantVal;
2425 return false;
2426 }
2427}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002428
Chris Lattnerdf986172009-01-02 07:01:27 +00002429bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002430 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002431 return ParseType(Type) ||
2432 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002433}
Chris Lattnerdf986172009-01-02 07:01:27 +00002434
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002435/// ParseGlobalValueVector
2436/// ::= /*empty*/
2437/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002438bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2439 // Empty list.
2440 if (Lex.getKind() == lltok::rbrace ||
2441 Lex.getKind() == lltok::rsquare ||
2442 Lex.getKind() == lltok::greater ||
2443 Lex.getKind() == lltok::rparen)
2444 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 Constant *C;
2447 if (ParseGlobalTypeAndValue(C)) return true;
2448 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002450 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 if (ParseGlobalTypeAndValue(C)) return true;
2452 Elts.push_back(C);
2453 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002454
Chris Lattnerdf986172009-01-02 07:01:27 +00002455 return false;
2456}
2457
2458
2459//===----------------------------------------------------------------------===//
2460// Function Parsing.
2461//===----------------------------------------------------------------------===//
2462
2463bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2464 PerFunctionState &PFS) {
2465 if (ID.Kind == ValID::t_LocalID)
2466 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2467 else if (ID.Kind == ValID::t_LocalName)
2468 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002469 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002470 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2471 const FunctionType *FTy =
2472 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2473 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2474 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002475 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002476 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002477 } else if (ID.Kind == ValID::t_Metadata) {
2478 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002479 } else {
2480 Constant *C;
2481 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2482 V = C;
2483 return false;
2484 }
2485
2486 return V == 0;
2487}
2488
2489bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2490 V = 0;
2491 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002492 return ParseValID(ID) ||
2493 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002494}
2495
2496bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002497 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002498 return ParseType(T) ||
2499 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002500}
2501
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002502bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2503 PerFunctionState &PFS) {
2504 Value *V;
2505 Loc = Lex.getLoc();
2506 if (ParseTypeAndValue(V, PFS)) return true;
2507 if (!isa<BasicBlock>(V))
2508 return Error(Loc, "expected a basic block");
2509 BB = cast<BasicBlock>(V);
2510 return false;
2511}
2512
2513
Chris Lattnerdf986172009-01-02 07:01:27 +00002514/// FunctionHeader
2515/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2516/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2517/// OptionalAlign OptGC
2518bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2519 // Parse the linkage.
2520 LocTy LinkageLoc = Lex.getLoc();
2521 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002522
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002523 unsigned Visibility, RetAttrs;
2524 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002525 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002526 LocTy RetTypeLoc = Lex.getLoc();
2527 if (ParseOptionalLinkage(Linkage) ||
2528 ParseOptionalVisibility(Visibility) ||
2529 ParseOptionalCallingConv(CC) ||
2530 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002531 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 return true;
2533
2534 // Verify that the linkage is ok.
2535 switch ((GlobalValue::LinkageTypes)Linkage) {
2536 case GlobalValue::ExternalLinkage:
2537 break; // always ok.
2538 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002539 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002540 if (isDefine)
2541 return Error(LinkageLoc, "invalid linkage for function definition");
2542 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002543 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002544 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002546 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002547 case GlobalValue::LinkOnceAnyLinkage:
2548 case GlobalValue::LinkOnceODRLinkage:
2549 case GlobalValue::WeakAnyLinkage:
2550 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002551 case GlobalValue::DLLExportLinkage:
2552 if (!isDefine)
2553 return Error(LinkageLoc, "invalid linkage for function declaration");
2554 break;
2555 case GlobalValue::AppendingLinkage:
2556 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002557 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002558 return Error(LinkageLoc, "invalid function linkage type");
2559 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002560
Chris Lattner99bb3152009-01-05 08:00:30 +00002561 if (!FunctionType::isValidReturnType(RetType) ||
2562 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002563 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002564
Chris Lattnerdf986172009-01-02 07:01:27 +00002565 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002566
2567 std::string FunctionName;
2568 if (Lex.getKind() == lltok::GlobalVar) {
2569 FunctionName = Lex.getStrVal();
2570 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2571 unsigned NameID = Lex.getUIntVal();
2572
2573 if (NameID != NumberedVals.size())
2574 return TokError("function expected to be numbered '%" +
2575 utostr(NumberedVals.size()) + "'");
2576 } else {
2577 return TokError("expected function name");
2578 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002579
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002580 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002581
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002582 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002584
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 std::vector<ArgInfo> ArgList;
2586 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002589 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002590 std::string GC;
2591
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002592 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002593 ParseOptionalAttrs(FuncAttrs, 2) ||
2594 (EatIfPresent(lltok::kw_section) &&
2595 ParseStringConstant(Section)) ||
2596 ParseOptionalAlignment(Alignment) ||
2597 (EatIfPresent(lltok::kw_gc) &&
2598 ParseStringConstant(GC)))
2599 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002600
2601 // If the alignment was parsed as an attribute, move to the alignment field.
2602 if (FuncAttrs & Attribute::Alignment) {
2603 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2604 FuncAttrs &= ~Attribute::Alignment;
2605 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002606
Chris Lattnerdf986172009-01-02 07:01:27 +00002607 // Okay, if we got here, the function is syntactically valid. Convert types
2608 // and do semantic checks.
2609 std::vector<const Type*> ParamTypeList;
2610 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002611 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 // attributes.
2613 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2614 if (FuncAttrs & ObsoleteFuncAttrs) {
2615 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2616 FuncAttrs &= ~ObsoleteFuncAttrs;
2617 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002618
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 if (RetAttrs != Attribute::None)
2620 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002621
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2623 ParamTypeList.push_back(ArgList[i].Type);
2624 if (ArgList[i].Attrs != Attribute::None)
2625 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2626 }
2627
2628 if (FuncAttrs != Attribute::None)
2629 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2630
2631 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattnera9a9e072009-03-09 04:49:14 +00002633 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002634 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002635 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2636
Owen Andersonfba933c2009-07-01 23:57:11 +00002637 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002638 FunctionType::get(RetType, ParamTypeList, isVarArg);
2639 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002640
2641 Fn = 0;
2642 if (!FunctionName.empty()) {
2643 // If this was a definition of a forward reference, remove the definition
2644 // from the forward reference table and fill in the forward ref.
2645 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2646 ForwardRefVals.find(FunctionName);
2647 if (FRVI != ForwardRefVals.end()) {
2648 Fn = M->getFunction(FunctionName);
2649 ForwardRefVals.erase(FRVI);
2650 } else if ((Fn = M->getFunction(FunctionName))) {
2651 // If this function already exists in the symbol table, then it is
2652 // multiply defined. We accept a few cases for old backwards compat.
2653 // FIXME: Remove this stuff for LLVM 3.0.
2654 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2655 (!Fn->isDeclaration() && isDefine)) {
2656 // If the redefinition has different type or different attributes,
2657 // reject it. If both have bodies, reject it.
2658 return Error(NameLoc, "invalid redefinition of function '" +
2659 FunctionName + "'");
2660 } else if (Fn->isDeclaration()) {
2661 // Make sure to strip off any argument names so we can't get conflicts.
2662 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2663 AI != AE; ++AI)
2664 AI->setName("");
2665 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002666 } else if (M->getNamedValue(FunctionName)) {
2667 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002668 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002669
Dan Gohman41905542009-08-29 23:37:49 +00002670 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002671 // If this is a definition of a forward referenced function, make sure the
2672 // types agree.
2673 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2674 = ForwardRefValIDs.find(NumberedVals.size());
2675 if (I != ForwardRefValIDs.end()) {
2676 Fn = cast<Function>(I->second.first);
2677 if (Fn->getType() != PFT)
2678 return Error(NameLoc, "type of definition and forward reference of '@" +
2679 utostr(NumberedVals.size()) +"' disagree");
2680 ForwardRefValIDs.erase(I);
2681 }
2682 }
2683
2684 if (Fn == 0)
2685 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2686 else // Move the forward-reference to the correct spot in the module.
2687 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2688
2689 if (FunctionName.empty())
2690 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002691
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2693 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2694 Fn->setCallingConv(CC);
2695 Fn->setAttributes(PAL);
2696 Fn->setAlignment(Alignment);
2697 Fn->setSection(Section);
2698 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002699
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 // Add all of the arguments we parsed to the function.
2701 Function::arg_iterator ArgIt = Fn->arg_begin();
2702 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2703 // If the argument has a name, insert it into the argument symbol table.
2704 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002705
Chris Lattnerdf986172009-01-02 07:01:27 +00002706 // Set the name, if it conflicted, it will be auto-renamed.
2707 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002708
Chris Lattnerdf986172009-01-02 07:01:27 +00002709 if (ArgIt->getNameStr() != ArgList[i].Name)
2710 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2711 ArgList[i].Name + "'");
2712 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002713
Chris Lattnerdf986172009-01-02 07:01:27 +00002714 return false;
2715}
2716
2717
2718/// ParseFunctionBody
2719/// ::= '{' BasicBlock+ '}'
2720/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2721///
2722bool LLParser::ParseFunctionBody(Function &Fn) {
2723 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2724 return TokError("expected '{' in function body");
2725 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002726
Chris Lattner09d9ef42009-10-28 03:39:23 +00002727 int FunctionNumber = -1;
2728 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2729
2730 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002731
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2733 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002734
Chris Lattnerdf986172009-01-02 07:01:27 +00002735 // Eat the }.
2736 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002737
Chris Lattnerdf986172009-01-02 07:01:27 +00002738 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002739 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002740}
2741
2742/// ParseBasicBlock
2743/// ::= LabelStr? Instruction*
2744bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2745 // If this basic block starts out with a name, remember it.
2746 std::string Name;
2747 LocTy NameLoc = Lex.getLoc();
2748 if (Lex.getKind() == lltok::LabelStr) {
2749 Name = Lex.getStrVal();
2750 Lex.Lex();
2751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002752
Chris Lattnerdf986172009-01-02 07:01:27 +00002753 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2754 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002755
Chris Lattnerdf986172009-01-02 07:01:27 +00002756 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002757
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 // Parse the instructions in this block until we get a terminator.
2759 Instruction *Inst;
2760 do {
2761 // This instruction may have three possibilities for a name: a) none
2762 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2763 LocTy NameLoc = Lex.getLoc();
2764 int NameID = -1;
2765 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 if (Lex.getKind() == lltok::LocalVarID) {
2768 NameID = Lex.getUIntVal();
2769 Lex.Lex();
2770 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2771 return true;
2772 } else if (Lex.getKind() == lltok::LocalVar ||
2773 // FIXME: REMOVE IN LLVM 3.0
2774 Lex.getKind() == lltok::StringConstant) {
2775 NameStr = Lex.getStrVal();
2776 Lex.Lex();
2777 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2778 return true;
2779 }
Devang Patelf633a062009-09-17 23:04:48 +00002780
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002782 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002783 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002784
2785 // Set metadata attached with this instruction.
Devang Patele30e6782009-09-28 21:41:20 +00002786 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +00002787 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Devang Patel58a230a2009-09-29 20:30:57 +00002789 TheMetadata.addMD(MDI->first, MDI->second, Inst);
Devang Patelf633a062009-09-17 23:04:48 +00002790 MDsOnInst.clear();
2791
Chris Lattnerdf986172009-01-02 07:01:27 +00002792 BB->getInstList().push_back(Inst);
2793
2794 // Set the name on the instruction.
2795 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2796 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 return false;
2799}
2800
2801//===----------------------------------------------------------------------===//
2802// Instruction Parsing.
2803//===----------------------------------------------------------------------===//
2804
2805/// ParseInstruction - Parse one of the many different instructions.
2806///
2807bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2808 PerFunctionState &PFS) {
2809 lltok::Kind Token = Lex.getKind();
2810 if (Token == lltok::Eof)
2811 return TokError("found end of file when expecting more instructions");
2812 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002813 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002814 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 switch (Token) {
2817 default: return Error(Loc, "expected instruction opcode");
2818 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002819 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2820 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2822 case lltok::kw_br: return ParseBr(Inst, PFS);
2823 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002824 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002825 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2826 // Binary Operators.
2827 case lltok::kw_add:
2828 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002829 case lltok::kw_mul: {
2830 bool NUW = false;
2831 bool NSW = false;
2832 LocTy ModifierLoc = Lex.getLoc();
2833 if (EatIfPresent(lltok::kw_nuw))
2834 NUW = true;
2835 if (EatIfPresent(lltok::kw_nsw)) {
2836 NSW = true;
2837 if (EatIfPresent(lltok::kw_nuw))
2838 NUW = true;
2839 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002840 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002841 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2842 if (!Result) {
2843 if (!Inst->getType()->isIntOrIntVector()) {
2844 if (NUW)
2845 return Error(ModifierLoc, "nuw only applies to integer operations");
2846 if (NSW)
2847 return Error(ModifierLoc, "nsw only applies to integer operations");
2848 }
2849 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002850 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002851 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002852 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002853 }
2854 return Result;
2855 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002856 case lltok::kw_fadd:
2857 case lltok::kw_fsub:
2858 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2859
Dan Gohman59858cf2009-07-27 16:11:46 +00002860 case lltok::kw_sdiv: {
2861 bool Exact = false;
2862 if (EatIfPresent(lltok::kw_exact))
2863 Exact = true;
2864 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2865 if (!Result)
2866 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002867 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002868 return Result;
2869 }
2870
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002872 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002873 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002874 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002875 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002876 case lltok::kw_shl:
2877 case lltok::kw_lshr:
2878 case lltok::kw_ashr:
2879 case lltok::kw_and:
2880 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002881 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002883 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002884 // Casts.
2885 case lltok::kw_trunc:
2886 case lltok::kw_zext:
2887 case lltok::kw_sext:
2888 case lltok::kw_fptrunc:
2889 case lltok::kw_fpext:
2890 case lltok::kw_bitcast:
2891 case lltok::kw_uitofp:
2892 case lltok::kw_sitofp:
2893 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002896 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002897 // Other.
2898 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002899 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002900 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2901 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2902 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2903 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2904 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2905 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2906 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002907 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2908 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00002909 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00002910 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2911 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2912 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002913 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002915 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002916 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002917 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002919 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2920 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2921 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2922 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2923 }
2924}
2925
2926/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2927bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002928 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 switch (Lex.getKind()) {
2930 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2931 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2932 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2933 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2934 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2935 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2936 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2937 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2938 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2939 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2940 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2941 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2942 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2943 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2944 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2945 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2946 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2947 }
2948 } else {
2949 switch (Lex.getKind()) {
2950 default: TokError("expected icmp predicate (e.g. 'eq')");
2951 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2952 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2953 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2954 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2955 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2956 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2957 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2958 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2959 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2960 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2961 }
2962 }
2963 Lex.Lex();
2964 return false;
2965}
2966
2967//===----------------------------------------------------------------------===//
2968// Terminator Instructions.
2969//===----------------------------------------------------------------------===//
2970
2971/// ParseRet - Parse a return instruction.
Devang Patel0475c912009-09-29 00:01:14 +00002972/// ::= 'ret' void (',' !dbg, !1)
2973/// ::= 'ret' TypeAndValue (',' !dbg, !1)
2974/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
Devang Patelf633a062009-09-17 23:04:48 +00002975/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002976bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2977 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002978 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002979 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002980
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002981 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002982 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002983 return false;
2984 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002985
Chris Lattnerdf986172009-01-02 07:01:27 +00002986 Value *RV;
2987 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002988
Devang Patelf633a062009-09-17 23:04:48 +00002989 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002990 // Parse optional custom metadata, e.g. !dbg
2991 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2992 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002993 } else {
2994 // The normal case is one return value.
2995 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2996 // of 'ret {i32,i32} {i32 1, i32 2}'
2997 SmallVector<Value*, 8> RVs;
2998 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002999
Devang Patelf633a062009-09-17 23:04:48 +00003000 do {
Devang Patel0475c912009-09-29 00:01:14 +00003001 // If optional custom metadata, e.g. !dbg is seen then this is the
3002 // end of MRV.
3003 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003004 break;
3005 if (ParseTypeAndValue(RV, PFS)) return true;
3006 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003007 } while (EatIfPresent(lltok::comma));
3008
3009 RV = UndefValue::get(PFS.getFunction().getReturnType());
3010 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003011 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3012 BB->getInstList().push_back(I);
3013 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003014 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003015 }
3016 }
Devang Patelf633a062009-09-17 23:04:48 +00003017
Owen Anderson1d0be152009-08-13 21:58:54 +00003018 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00003019 return false;
3020}
3021
3022
3023/// ParseBr
3024/// ::= 'br' TypeAndValue
3025/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3026bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3027 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003028 Value *Op0;
3029 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003031
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3033 Inst = BranchInst::Create(BB);
3034 return false;
3035 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003036
Owen Anderson1d0be152009-08-13 21:58:54 +00003037 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003039
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003041 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003042 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003043 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003044 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003045
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003046 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003047 return false;
3048}
3049
3050/// ParseSwitch
3051/// Instruction
3052/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3053/// JumpTable
3054/// ::= (TypeAndValue ',' TypeAndValue)*
3055bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3056 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003057 Value *Cond;
3058 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003059 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3060 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003061 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3063 return true;
3064
3065 if (!isa<IntegerType>(Cond->getType()))
3066 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003067
Chris Lattnerdf986172009-01-02 07:01:27 +00003068 // Parse the jump table pairs.
3069 SmallPtrSet<Value*, 32> SeenCases;
3070 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3071 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003072 Value *Constant;
3073 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003074
Chris Lattnerdf986172009-01-02 07:01:27 +00003075 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3076 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003077 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003079
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 if (!SeenCases.insert(Constant))
3081 return Error(CondLoc, "duplicate case value in switch");
3082 if (!isa<ConstantInt>(Constant))
3083 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003084
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003085 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003087
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003089
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003090 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3092 SI->addCase(Table[i].first, Table[i].second);
3093 Inst = SI;
3094 return false;
3095}
3096
Chris Lattnerab21db72009-10-28 00:19:10 +00003097/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003098/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003099/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3100bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003101 LocTy AddrLoc;
3102 Value *Address;
3103 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003104 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3105 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003106 return true;
3107
3108 if (!isa<PointerType>(Address->getType()))
Chris Lattnerab21db72009-10-28 00:19:10 +00003109 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003110
3111 // Parse the destination list.
3112 SmallVector<BasicBlock*, 16> DestList;
3113
3114 if (Lex.getKind() != lltok::rsquare) {
3115 BasicBlock *DestBB;
3116 if (ParseTypeAndBasicBlock(DestBB, PFS))
3117 return true;
3118 DestList.push_back(DestBB);
3119
3120 while (EatIfPresent(lltok::comma)) {
3121 if (ParseTypeAndBasicBlock(DestBB, PFS))
3122 return true;
3123 DestList.push_back(DestBB);
3124 }
3125 }
3126
3127 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3128 return true;
3129
Chris Lattnerab21db72009-10-28 00:19:10 +00003130 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003131 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3132 IBI->addDestination(DestList[i]);
3133 Inst = IBI;
3134 return false;
3135}
3136
3137
Chris Lattnerdf986172009-01-02 07:01:27 +00003138/// ParseInvoke
3139/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3140/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3141bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3142 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003143 unsigned RetAttrs, FnAttrs;
3144 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003145 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003146 LocTy RetTypeLoc;
3147 ValID CalleeID;
3148 SmallVector<ParamInfo, 16> ArgList;
3149
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003150 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 if (ParseOptionalCallingConv(CC) ||
3152 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003153 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003154 ParseValID(CalleeID) ||
3155 ParseParameterList(ArgList, PFS) ||
3156 ParseOptionalAttrs(FnAttrs, 2) ||
3157 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003158 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003159 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003160 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003161 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003162
Chris Lattnerdf986172009-01-02 07:01:27 +00003163 // If RetType is a non-function pointer type, then this is the short syntax
3164 // for the call, which means that RetType is just the return type. Infer the
3165 // rest of the function argument types from the arguments that are present.
3166 const PointerType *PFTy = 0;
3167 const FunctionType *Ty = 0;
3168 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3169 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3170 // Pull out the types of all of the arguments...
3171 std::vector<const Type*> ParamTypes;
3172 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3173 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003174
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 if (!FunctionType::isValidReturnType(RetType))
3176 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003177
Owen Andersondebcb012009-07-29 22:17:13 +00003178 Ty = FunctionType::get(RetType, ParamTypes, false);
3179 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003181
Chris Lattnerdf986172009-01-02 07:01:27 +00003182 // Look up the callee.
3183 Value *Callee;
3184 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003185
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3187 // function attributes.
3188 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3189 if (FnAttrs & ObsoleteFuncAttrs) {
3190 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3191 FnAttrs &= ~ObsoleteFuncAttrs;
3192 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003193
Chris Lattnerdf986172009-01-02 07:01:27 +00003194 // Set up the Attributes for the function.
3195 SmallVector<AttributeWithIndex, 8> Attrs;
3196 if (RetAttrs != Attribute::None)
3197 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003198
Chris Lattnerdf986172009-01-02 07:01:27 +00003199 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003200
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 // Loop through FunctionType's arguments and ensure they are specified
3202 // correctly. Also, gather any parameter attributes.
3203 FunctionType::param_iterator I = Ty->param_begin();
3204 FunctionType::param_iterator E = Ty->param_end();
3205 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3206 const Type *ExpectedTy = 0;
3207 if (I != E) {
3208 ExpectedTy = *I++;
3209 } else if (!Ty->isVarArg()) {
3210 return Error(ArgList[i].Loc, "too many arguments specified");
3211 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003212
Chris Lattnerdf986172009-01-02 07:01:27 +00003213 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3214 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3215 ExpectedTy->getDescription() + "'");
3216 Args.push_back(ArgList[i].V);
3217 if (ArgList[i].Attrs != Attribute::None)
3218 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3219 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003220
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 if (I != E)
3222 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003223
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 if (FnAttrs != Attribute::None)
3225 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 // Finish off the Attributes and check them
3228 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003229
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003230 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 Args.begin(), Args.end());
3232 II->setCallingConv(CC);
3233 II->setAttributes(PAL);
3234 Inst = II;
3235 return false;
3236}
3237
3238
3239
3240//===----------------------------------------------------------------------===//
3241// Binary Operators.
3242//===----------------------------------------------------------------------===//
3243
3244/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003245/// ::= ArithmeticOps TypeAndValue ',' Value
3246///
3247/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3248/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003249bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003250 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 LocTy Loc; Value *LHS, *RHS;
3252 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3253 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3254 ParseValue(LHS->getType(), RHS, PFS))
3255 return true;
3256
Chris Lattnere914b592009-01-05 08:24:46 +00003257 bool Valid;
3258 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003259 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003260 case 0: // int or FP.
3261 Valid = LHS->getType()->isIntOrIntVector() ||
3262 LHS->getType()->isFPOrFPVector();
3263 break;
3264 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3265 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3266 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003267
Chris Lattnere914b592009-01-05 08:24:46 +00003268 if (!Valid)
3269 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003270
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3272 return false;
3273}
3274
3275/// ParseLogical
3276/// ::= ArithmeticOps TypeAndValue ',' Value {
3277bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3278 unsigned Opc) {
3279 LocTy Loc; Value *LHS, *RHS;
3280 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3281 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3282 ParseValue(LHS->getType(), RHS, PFS))
3283 return true;
3284
3285 if (!LHS->getType()->isIntOrIntVector())
3286 return Error(Loc,"instruction requires integer or integer vector operands");
3287
3288 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3289 return false;
3290}
3291
3292
3293/// ParseCompare
3294/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3295/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003296bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3297 unsigned Opc) {
3298 // Parse the integer/fp comparison predicate.
3299 LocTy Loc;
3300 unsigned Pred;
3301 Value *LHS, *RHS;
3302 if (ParseCmpPredicate(Pred, Opc) ||
3303 ParseTypeAndValue(LHS, Loc, PFS) ||
3304 ParseToken(lltok::comma, "expected ',' after compare value") ||
3305 ParseValue(LHS->getType(), RHS, PFS))
3306 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003307
Chris Lattnerdf986172009-01-02 07:01:27 +00003308 if (Opc == Instruction::FCmp) {
3309 if (!LHS->getType()->isFPOrFPVector())
3310 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003311 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003312 } else {
3313 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003314 if (!LHS->getType()->isIntOrIntVector() &&
3315 !isa<PointerType>(LHS->getType()))
3316 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003317 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003318 }
3319 return false;
3320}
3321
3322//===----------------------------------------------------------------------===//
3323// Other Instructions.
3324//===----------------------------------------------------------------------===//
3325
3326
3327/// ParseCast
3328/// ::= CastOpc TypeAndValue 'to' Type
3329bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3330 unsigned Opc) {
3331 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003332 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 if (ParseTypeAndValue(Op, Loc, PFS) ||
3334 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3335 ParseType(DestTy))
3336 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003337
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003338 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3339 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003340 return Error(Loc, "invalid cast opcode for cast from '" +
3341 Op->getType()->getDescription() + "' to '" +
3342 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003343 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3345 return false;
3346}
3347
3348/// ParseSelect
3349/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3350bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3351 LocTy Loc;
3352 Value *Op0, *Op1, *Op2;
3353 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3354 ParseToken(lltok::comma, "expected ',' after select condition") ||
3355 ParseTypeAndValue(Op1, PFS) ||
3356 ParseToken(lltok::comma, "expected ',' after select value") ||
3357 ParseTypeAndValue(Op2, PFS))
3358 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3361 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003362
Chris Lattnerdf986172009-01-02 07:01:27 +00003363 Inst = SelectInst::Create(Op0, Op1, Op2);
3364 return false;
3365}
3366
Chris Lattner0088a5c2009-01-05 08:18:44 +00003367/// ParseVA_Arg
3368/// ::= 'va_arg' TypeAndValue ',' Type
3369bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003371 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003372 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 if (ParseTypeAndValue(Op, PFS) ||
3374 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003375 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003377
Chris Lattner0088a5c2009-01-05 08:18:44 +00003378 if (!EltTy->isFirstClassType())
3379 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003380
3381 Inst = new VAArgInst(Op, EltTy);
3382 return false;
3383}
3384
3385/// ParseExtractElement
3386/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3387bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3388 LocTy Loc;
3389 Value *Op0, *Op1;
3390 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3391 ParseToken(lltok::comma, "expected ',' after extract value") ||
3392 ParseTypeAndValue(Op1, PFS))
3393 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3396 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003397
Eric Christophera3500da2009-07-25 02:28:41 +00003398 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003399 return false;
3400}
3401
3402/// ParseInsertElement
3403/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3404bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3405 LocTy Loc;
3406 Value *Op0, *Op1, *Op2;
3407 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3408 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3409 ParseTypeAndValue(Op1, PFS) ||
3410 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3411 ParseTypeAndValue(Op2, PFS))
3412 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003413
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003415 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003416
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3418 return false;
3419}
3420
3421/// ParseShuffleVector
3422/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3423bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3424 LocTy Loc;
3425 Value *Op0, *Op1, *Op2;
3426 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3427 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3428 ParseTypeAndValue(Op1, PFS) ||
3429 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3430 ParseTypeAndValue(Op2, PFS))
3431 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003432
Chris Lattnerdf986172009-01-02 07:01:27 +00003433 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3434 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003435
Chris Lattnerdf986172009-01-02 07:01:27 +00003436 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3437 return false;
3438}
3439
3440/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003441/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003442bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003443 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003444 Value *Op0, *Op1;
3445 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003446
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 if (ParseType(Ty) ||
3448 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3449 ParseValue(Ty, Op0, PFS) ||
3450 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003451 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3453 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003454
Chris Lattnerdf986172009-01-02 07:01:27 +00003455 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3456 while (1) {
3457 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003458
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003459 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003460 break;
3461
Devang Patela43d46f2009-10-16 18:45:49 +00003462 if (Lex.getKind() == lltok::NamedOrCustomMD)
3463 break;
3464
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003465 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003466 ParseValue(Ty, Op0, PFS) ||
3467 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003468 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003469 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3470 return true;
3471 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003472
Devang Patela43d46f2009-10-16 18:45:49 +00003473 if (Lex.getKind() == lltok::NamedOrCustomMD)
3474 if (ParseOptionalCustomMetadata()) return true;
3475
Chris Lattnerdf986172009-01-02 07:01:27 +00003476 if (!Ty->isFirstClassType())
3477 return Error(TypeLoc, "phi node must have first class type");
3478
3479 PHINode *PN = PHINode::Create(Ty);
3480 PN->reserveOperandSpace(PHIVals.size());
3481 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3482 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3483 Inst = PN;
3484 return false;
3485}
3486
3487/// ParseCall
3488/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3489/// ParameterList OptionalAttrs
3490bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3491 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003492 unsigned RetAttrs, FnAttrs;
3493 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003494 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003495 LocTy RetTypeLoc;
3496 ValID CalleeID;
3497 SmallVector<ParamInfo, 16> ArgList;
3498 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003499
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3501 ParseOptionalCallingConv(CC) ||
3502 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003503 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 ParseValID(CalleeID) ||
3505 ParseParameterList(ArgList, PFS) ||
3506 ParseOptionalAttrs(FnAttrs, 2))
3507 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003508
Chris Lattnerdf986172009-01-02 07:01:27 +00003509 // If RetType is a non-function pointer type, then this is the short syntax
3510 // for the call, which means that RetType is just the return type. Infer the
3511 // rest of the function argument types from the arguments that are present.
3512 const PointerType *PFTy = 0;
3513 const FunctionType *Ty = 0;
3514 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3515 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3516 // Pull out the types of all of the arguments...
3517 std::vector<const Type*> ParamTypes;
3518 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3519 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003520
Chris Lattnerdf986172009-01-02 07:01:27 +00003521 if (!FunctionType::isValidReturnType(RetType))
3522 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003523
Owen Andersondebcb012009-07-29 22:17:13 +00003524 Ty = FunctionType::get(RetType, ParamTypes, false);
3525 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 // Look up the callee.
3529 Value *Callee;
3530 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003531
Chris Lattnerdf986172009-01-02 07:01:27 +00003532 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3533 // function attributes.
3534 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3535 if (FnAttrs & ObsoleteFuncAttrs) {
3536 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3537 FnAttrs &= ~ObsoleteFuncAttrs;
3538 }
3539
3540 // Set up the Attributes for the function.
3541 SmallVector<AttributeWithIndex, 8> Attrs;
3542 if (RetAttrs != Attribute::None)
3543 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003544
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003546
Chris Lattnerdf986172009-01-02 07:01:27 +00003547 // Loop through FunctionType's arguments and ensure they are specified
3548 // correctly. Also, gather any parameter attributes.
3549 FunctionType::param_iterator I = Ty->param_begin();
3550 FunctionType::param_iterator E = Ty->param_end();
3551 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3552 const Type *ExpectedTy = 0;
3553 if (I != E) {
3554 ExpectedTy = *I++;
3555 } else if (!Ty->isVarArg()) {
3556 return Error(ArgList[i].Loc, "too many arguments specified");
3557 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003558
Chris Lattnerdf986172009-01-02 07:01:27 +00003559 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3560 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3561 ExpectedTy->getDescription() + "'");
3562 Args.push_back(ArgList[i].V);
3563 if (ArgList[i].Attrs != Attribute::None)
3564 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3565 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003566
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 if (I != E)
3568 return Error(CallLoc, "not enough parameters specified for call");
3569
3570 if (FnAttrs != Attribute::None)
3571 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3572
3573 // Finish off the Attributes and check them
3574 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003575
Chris Lattnerdf986172009-01-02 07:01:27 +00003576 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3577 CI->setTailCall(isTail);
3578 CI->setCallingConv(CC);
3579 CI->setAttributes(PAL);
3580 Inst = CI;
3581 return false;
3582}
3583
3584//===----------------------------------------------------------------------===//
3585// Memory Instructions.
3586//===----------------------------------------------------------------------===//
3587
3588/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003589/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3590/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003591bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003592 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003593 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003594 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003595 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003597 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003598
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003599 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003600 if (Lex.getKind() == lltok::kw_align
3601 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003602 if (ParseOptionalInfo(Alignment)) return true;
3603 } else {
3604 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3605 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003606 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 }
3608 }
3609
Owen Anderson1d0be152009-08-13 21:58:54 +00003610 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003611 return Error(SizeLoc, "element count must be i32");
3612
Victor Hernandez68afa542009-10-21 19:11:40 +00003613 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003614 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez68afa542009-10-21 19:11:40 +00003615 return false;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003616 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003617
3618 // Autoupgrade old malloc instruction to malloc call.
3619 // FIXME: Remove in LLVM 3.0.
3620 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez68afa542009-10-21 19:11:40 +00003621 if (!MallocF)
3622 // Prototype malloc as "void *(int32)".
3623 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003624 MallocF = cast<Function>(
3625 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez68afa542009-10-21 19:11:40 +00003626 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 return false;
3628}
3629
3630/// ParseFree
3631/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003632bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3633 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003634 Value *Val; LocTy Loc;
3635 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3636 if (!isa<PointerType>(Val->getType()))
3637 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003638 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 return false;
3640}
3641
3642/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003643/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003644bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3645 bool isVolatile) {
3646 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003647 unsigned Alignment = 0;
3648 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003649
Devang Patelf633a062009-09-17 23:04:48 +00003650 if (EatIfPresent(lltok::comma))
3651 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003652
3653 if (!isa<PointerType>(Val->getType()) ||
3654 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3655 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003656
Chris Lattnerdf986172009-01-02 07:01:27 +00003657 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3658 return false;
3659}
3660
3661/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003662/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003663bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3664 bool isVolatile) {
3665 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003666 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 if (ParseTypeAndValue(Val, Loc, PFS) ||
3668 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003669 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003670 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003671
3672 if (EatIfPresent(lltok::comma))
3673 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003674
Chris Lattnerdf986172009-01-02 07:01:27 +00003675 if (!isa<PointerType>(Ptr->getType()))
3676 return Error(PtrLoc, "store operand must be a pointer");
3677 if (!Val->getType()->isFirstClassType())
3678 return Error(Loc, "store operand must be a first class value");
3679 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3680 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003681
Chris Lattnerdf986172009-01-02 07:01:27 +00003682 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3683 return false;
3684}
3685
3686/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003687/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003688/// FIXME: Remove support for getresult in LLVM 3.0
3689bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3690 Value *Val; LocTy ValLoc, EltLoc;
3691 unsigned Element;
3692 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3693 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003694 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003696
Chris Lattnerdf986172009-01-02 07:01:27 +00003697 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3698 return Error(ValLoc, "getresult inst requires an aggregate operand");
3699 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3700 return Error(EltLoc, "invalid getresult index for value");
3701 Inst = ExtractValueInst::Create(Val, Element);
3702 return false;
3703}
3704
3705/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003706/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003707bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3708 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003709
Dan Gohmandcb40a32009-07-29 15:58:36 +00003710 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003711
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003712 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003713
Chris Lattnerdf986172009-01-02 07:01:27 +00003714 if (!isa<PointerType>(Ptr->getType()))
3715 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003716
Chris Lattnerdf986172009-01-02 07:01:27 +00003717 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003718 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003719 if (Lex.getKind() == lltok::NamedOrCustomMD)
3720 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003721 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 if (!isa<IntegerType>(Val->getType()))
3723 return Error(EltLoc, "getelementptr index must be an integer");
3724 Indices.push_back(Val);
3725 }
Devang Patel6225d642009-10-13 18:49:55 +00003726 if (Lex.getKind() == lltok::NamedOrCustomMD)
3727 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003728
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3730 Indices.begin(), Indices.end()))
3731 return Error(Loc, "invalid getelementptr indices");
3732 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003733 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003734 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003735 return false;
3736}
3737
3738/// ParseExtractValue
3739/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3740bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3741 Value *Val; LocTy Loc;
3742 SmallVector<unsigned, 4> Indices;
3743 if (ParseTypeAndValue(Val, Loc, PFS) ||
3744 ParseIndexList(Indices))
3745 return true;
3746
3747 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3748 return Error(Loc, "extractvalue operand must be array or struct");
3749
3750 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3751 Indices.end()))
3752 return Error(Loc, "invalid indices for extractvalue");
3753 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3754 return false;
3755}
3756
3757/// ParseInsertValue
3758/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3759bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3760 Value *Val0, *Val1; LocTy Loc0, Loc1;
3761 SmallVector<unsigned, 4> Indices;
3762 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3763 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3764 ParseTypeAndValue(Val1, Loc1, PFS) ||
3765 ParseIndexList(Indices))
3766 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003767
Chris Lattnerdf986172009-01-02 07:01:27 +00003768 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3769 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003770
Chris Lattnerdf986172009-01-02 07:01:27 +00003771 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3772 Indices.end()))
3773 return Error(Loc0, "invalid indices for insertvalue");
3774 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3775 return false;
3776}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003777
3778//===----------------------------------------------------------------------===//
3779// Embedded metadata.
3780//===----------------------------------------------------------------------===//
3781
3782/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003783/// ::= Element (',' Element)*
3784/// Element
3785/// ::= 'null' | TypeAndValue
3786bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003787 assert(Lex.getKind() == lltok::lbrace);
3788 Lex.Lex();
3789 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003790 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003791 if (Lex.getKind() == lltok::kw_null) {
3792 Lex.Lex();
3793 V = 0;
3794 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003795 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003796 if (ParseType(Ty)) return true;
3797 if (Lex.getKind() == lltok::Metadata) {
3798 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003799 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003800 if (!ParseMDNode(Node))
3801 V = Node;
3802 else {
3803 MetadataBase *MDS = 0;
3804 if (ParseMDString(MDS)) return true;
3805 V = MDS;
3806 }
3807 } else {
3808 Constant *C;
3809 if (ParseGlobalValue(Ty, C)) return true;
3810 V = C;
3811 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003812 }
3813 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003814 } while (EatIfPresent(lltok::comma));
3815
3816 return false;
3817}