blob: f21a065473b6297d818eb1a3720f0e6bf31bbd0e [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattnerad7d1e22009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000037}
38
39/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40/// module.
41bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000042 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 I != E; ++I) {
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
49
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
52
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
57 }
58 }
59 ForwardRefInstMetadata.clear();
60 }
61
62
Victor Hernandez68afa542009-10-21 19:11:40 +000063 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000064 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000065 if (MallocF) {
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000071 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000072 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000075 MallocF->eraseFromParent();
76 MallocF = NULL;
77 }
78 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000079
80
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
85 Function *TheFn = 0;
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
91
92 if (TheFn == 0)
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
94
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
98 0))
99 return true;
100
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
102 }
103
104
Chris Lattnerdf986172009-01-02 07:01:27 +0000105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
117 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000123
Devang Patel1c7eea62009-07-08 19:23:54 +0000124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000128
Devang Patel1c7eea62009-07-08 19:23:54 +0000129
Chris Lattnerdf986172009-01-02 07:01:27 +0000130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000133
Devang Patele4b27562009-08-28 23:24:31 +0000134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000136 return false;
137}
138
Chris Lattner09d9ef42009-10-28 03:39:23 +0000139bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
144 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000148 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000152 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000153 } else {
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
156 }
157
Chris Lattnercdfc9402009-11-01 01:27:45 +0000158 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
161
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
166 }
167 return false;
168}
169
170
Chris Lattnerdf986172009-01-02 07:01:27 +0000171//===----------------------------------------------------------------------===//
172// Top-Level Entities
173//===----------------------------------------------------------------------===//
174
175bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000176 while (1) {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000194
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000202 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000203 case lltok::kw_internal: // OptionalLinkage
204 case lltok::kw_weak: // OptionalLinkage
205 case lltok::kw_weak_odr: // OptionalLinkage
206 case lltok::kw_linkonce: // OptionalLinkage
207 case lltok::kw_linkonce_odr: // OptionalLinkage
208 case lltok::kw_appending: // OptionalLinkage
209 case lltok::kw_dllexport: // OptionalLinkage
210 case lltok::kw_common: // OptionalLinkage
211 case lltok::kw_dllimport: // OptionalLinkage
212 case lltok::kw_extern_weak: // OptionalLinkage
213 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 unsigned Linkage, Visibility;
215 if (ParseOptionalLinkage(Linkage) ||
216 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000217 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 return true;
219 break;
220 }
221 case lltok::kw_default: // OptionalVisibility
222 case lltok::kw_hidden: // OptionalVisibility
223 case lltok::kw_protected: { // OptionalVisibility
224 unsigned Visibility;
225 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000226 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000227 return true;
228 break;
229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Chris Lattnerdf986172009-01-02 07:01:27 +0000231 case lltok::kw_thread_local: // OptionalThreadLocal
232 case lltok::kw_addrspace: // OptionalAddrSpace
233 case lltok::kw_constant: // GlobalType
234 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000235 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 break;
237 }
238 }
239}
240
241
242/// toplevelentity
243/// ::= 'module' 'asm' STRINGCONSTANT
244bool LLParser::ParseModuleAsm() {
245 assert(Lex.getKind() == lltok::kw_module);
246 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000247
248 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000249 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
250 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000251
Chris Lattnerdf986172009-01-02 07:01:27 +0000252 const std::string &AsmSoFar = M->getModuleInlineAsm();
253 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000256 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 return false;
258}
259
260/// toplevelentity
261/// ::= 'target' 'triple' '=' STRINGCONSTANT
262/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
263bool LLParser::ParseTargetDefinition() {
264 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000265 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000266 switch (Lex.Lex()) {
267 default: return TokError("unknown target property");
268 case lltok::kw_triple:
269 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000270 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000273 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000274 return false;
275 case lltok::kw_datalayout:
276 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000277 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000280 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 return false;
282 }
283}
284
285/// toplevelentity
286/// ::= 'deplibs' '=' '[' ']'
287/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288bool LLParser::ParseDepLibs() {
289 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000290 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000291 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
292 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
293 return true;
294
295 if (EatIfPresent(lltok::rsquare))
296 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000298 std::string Str;
299 if (ParseStringConstant(Str)) return true;
300 M->addLibrary(Str);
301
302 while (EatIfPresent(lltok::comma)) {
303 if (ParseStringConstant(Str)) return true;
304 M->addLibrary(Str);
305 }
306
307 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000308}
309
Dan Gohman3845e502009-08-12 23:32:33 +0000310/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000311/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000312/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000313bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000314 unsigned TypeID = NumberedTypes.size();
315
316 // Handle the LocalVarID form.
317 if (Lex.getKind() == lltok::LocalVarID) {
318 if (Lex.getUIntVal() != TypeID)
319 return Error(Lex.getLoc(), "type expected to be numbered '%" +
320 utostr(TypeID) + "'");
321 Lex.Lex(); // eat LocalVarID;
322
323 if (ParseToken(lltok::equal, "expected '=' after name"))
324 return true;
325 }
326
Chris Lattnerdf986172009-01-02 07:01:27 +0000327 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000328 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000329
Owen Anderson1d0be152009-08-13 21:58:54 +0000330 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000332
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 // See if this type was previously referenced.
334 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
335 FI = ForwardRefTypeIDs.find(TypeID);
336 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000337 if (FI->second.first.get() == Ty)
338 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
341 Ty = FI->second.first.get();
342 ForwardRefTypeIDs.erase(FI);
343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344
Chris Lattnerdf986172009-01-02 07:01:27 +0000345 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000346
Chris Lattnerdf986172009-01-02 07:01:27 +0000347 return false;
348}
349
350/// toplevelentity
351/// ::= LocalVar '=' 'type' type
352bool LLParser::ParseNamedType() {
353 std::string Name = Lex.getStrVal();
354 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000355 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000356
Owen Anderson1d0be152009-08-13 21:58:54 +0000357 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000358
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000359 if (ParseToken(lltok::equal, "expected '=' after name") ||
360 ParseToken(lltok::kw_type, "expected 'type' after name") ||
361 ParseType(Ty))
362 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000363
Chris Lattnerdf986172009-01-02 07:01:27 +0000364 // Set the type name, checking for conflicts as we do so.
365 bool AlreadyExists = M->addTypeName(Name, Ty);
366 if (!AlreadyExists) return false;
367
368 // See if this type is a forward reference. We need to eagerly resolve
369 // types to allow recursive type redefinitions below.
370 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
371 FI = ForwardRefTypes.find(Name);
372 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000373 if (FI->second.first.get() == Ty)
374 return Error(NameLoc, "self referential type is invalid");
375
Chris Lattnerdf986172009-01-02 07:01:27 +0000376 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
377 Ty = FI->second.first.get();
378 ForwardRefTypes.erase(FI);
379 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000380
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 // Inserting a name that is already defined, get the existing name.
382 const Type *Existing = M->getTypeByName(Name);
383 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Chris Lattnerdf986172009-01-02 07:01:27 +0000385 // Otherwise, this is an attempt to redefine a type. That's okay if
386 // the redefinition is identical to the original.
387 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
388 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 // Any other kind of (non-equivalent) redefinition is an error.
391 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
392 Ty->getDescription() + "'");
393}
394
395
396/// toplevelentity
397/// ::= 'declare' FunctionHeader
398bool LLParser::ParseDeclare() {
399 assert(Lex.getKind() == lltok::kw_declare);
400 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Chris Lattnerdf986172009-01-02 07:01:27 +0000402 Function *F;
403 return ParseFunctionHeader(F, false);
404}
405
406/// toplevelentity
407/// ::= 'define' FunctionHeader '{' ...
408bool LLParser::ParseDefine() {
409 assert(Lex.getKind() == lltok::kw_define);
410 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Chris Lattnerdf986172009-01-02 07:01:27 +0000412 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000413 return ParseFunctionHeader(F, true) ||
414 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000415}
416
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000417/// ParseGlobalType
418/// ::= 'constant'
419/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000420bool LLParser::ParseGlobalType(bool &IsConstant) {
421 if (Lex.getKind() == lltok::kw_constant)
422 IsConstant = true;
423 else if (Lex.getKind() == lltok::kw_global)
424 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000425 else {
426 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000427 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000428 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000429 Lex.Lex();
430 return false;
431}
432
Dan Gohman3845e502009-08-12 23:32:33 +0000433/// ParseUnnamedGlobal:
434/// OptionalVisibility ALIAS ...
435/// OptionalLinkage OptionalVisibility ... -> global variable
436/// GlobalID '=' OptionalVisibility ALIAS ...
437/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
438bool LLParser::ParseUnnamedGlobal() {
439 unsigned VarID = NumberedVals.size();
440 std::string Name;
441 LocTy NameLoc = Lex.getLoc();
442
443 // Handle the GlobalID form.
444 if (Lex.getKind() == lltok::GlobalID) {
445 if (Lex.getUIntVal() != VarID)
446 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
447 utostr(VarID) + "'");
448 Lex.Lex(); // eat GlobalID;
449
450 if (ParseToken(lltok::equal, "expected '=' after name"))
451 return true;
452 }
453
454 bool HasLinkage;
455 unsigned Linkage, Visibility;
456 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
457 ParseOptionalVisibility(Visibility))
458 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Dan Gohman3845e502009-08-12 23:32:33 +0000460 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
461 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
462 return ParseAlias(Name, NameLoc, Visibility);
463}
464
Chris Lattnerdf986172009-01-02 07:01:27 +0000465/// ParseNamedGlobal:
466/// GlobalVar '=' OptionalVisibility ALIAS ...
467/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
468bool LLParser::ParseNamedGlobal() {
469 assert(Lex.getKind() == lltok::GlobalVar);
470 LocTy NameLoc = Lex.getLoc();
471 std::string Name = Lex.getStrVal();
472 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000473
Chris Lattnerdf986172009-01-02 07:01:27 +0000474 bool HasLinkage;
475 unsigned Linkage, Visibility;
476 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
477 ParseOptionalLinkage(Linkage, HasLinkage) ||
478 ParseOptionalVisibility(Visibility))
479 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000480
Chris Lattnerdf986172009-01-02 07:01:27 +0000481 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
482 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
483 return ParseAlias(Name, NameLoc, Visibility);
484}
485
Devang Patel256be962009-07-20 19:00:08 +0000486// MDString:
487// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000488bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000489 std::string Str;
490 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000491 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000492 return false;
493}
494
495// MDNode:
496// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000497//
498/// This version of ParseMDNodeID returns the slot number and null in the case
499/// of a forward reference.
500bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
501 // !{ ..., !42, ... }
502 if (ParseUInt32(SlotNo)) return true;
503
504 // Check existing MDNode.
505 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
506 Result = NumberedMetadata[SlotNo];
507 else
508 Result = 0;
509 return false;
510}
511
Chris Lattner4a72efc2009-12-30 04:15:23 +0000512bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000513 // !{ ..., !42, ... }
514 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000515 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000516
Chris Lattner449c3102010-04-01 05:14:45 +0000517 // If not a forward reference, just return it now.
518 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000519
Chris Lattner449c3102010-04-01 05:14:45 +0000520 // Otherwise, create MDNode forward reference.
Dan Gohman489b29b2010-08-20 22:02:26 +0000521 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
Devang Patel256be962009-07-20 19:00:08 +0000522 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000523
524 if (NumberedMetadata.size() <= MID)
525 NumberedMetadata.resize(MID+1);
526 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000527 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000528 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529}
Devang Patel256be962009-07-20 19:00:08 +0000530
Chris Lattner84d03b12009-12-29 22:35:39 +0000531/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000532/// !foo = !{ !1, !2 }
533bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000534 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000535 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000536 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000537
Chris Lattner84d03b12009-12-29 22:35:39 +0000538 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000539 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000540 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000541 return true;
542
Dan Gohman17aa92c2010-07-21 23:38:33 +0000543 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000544 if (Lex.getKind() != lltok::rbrace)
545 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000546 if (ParseToken(lltok::exclaim, "Expected '!' here"))
547 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000548
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000549 MDNode *N = 0;
550 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000551 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000552 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000553
554 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
555 return true;
556
Devang Pateleff2ab62009-07-29 00:34:02 +0000557 return false;
558}
559
Devang Patel923078c2009-07-01 19:21:12 +0000560/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000561/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000562bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000563 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000564 Lex.Lex();
565 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000566
567 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000569 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000570 if (ParseUInt32(MetadataID) ||
571 ParseToken(lltok::equal, "expected '=' here") ||
572 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000573 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000574 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000575 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000576 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000577 return true;
578
Owen Anderson647e3012009-07-31 21:35:40 +0000579 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000580
581 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000582 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000583 FI = ForwardRefMDNodes.find(MetadataID);
584 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000585 MDNode *Temp = FI->second.first;
586 Temp->replaceAllUsesWith(Init);
587 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000588 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000589
590 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
591 } else {
592 if (MetadataID >= NumberedMetadata.size())
593 NumberedMetadata.resize(MetadataID+1);
594
595 if (NumberedMetadata[MetadataID] != 0)
596 return TokError("Metadata id is already used");
597 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000598 }
599
Devang Patel923078c2009-07-01 19:21:12 +0000600 return false;
601}
602
Chris Lattnerdf986172009-01-02 07:01:27 +0000603/// ParseAlias:
604/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
605/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000606/// ::= TypeAndValue
607/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000608/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000609///
610/// Everything through visibility has already been parsed.
611///
612bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
613 unsigned Visibility) {
614 assert(Lex.getKind() == lltok::kw_alias);
615 Lex.Lex();
616 unsigned Linkage;
617 LocTy LinkageLoc = Lex.getLoc();
618 if (ParseOptionalLinkage(Linkage))
619 return true;
620
621 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000622 Linkage != GlobalValue::WeakAnyLinkage &&
623 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000624 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000625 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000626 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000627 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
628 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 Constant *Aliasee;
632 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000633 if (Lex.getKind() != lltok::kw_bitcast &&
634 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 if (ParseGlobalTypeAndValue(Aliasee)) return true;
636 } else {
637 // The bitcast dest type is not present, it is implied by the dest type.
638 ValID ID;
639 if (ParseValID(ID)) return true;
640 if (ID.Kind != ValID::t_Constant)
641 return Error(AliaseeLoc, "invalid aliasee");
642 Aliasee = ID.ConstantVal;
643 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644
Duncan Sands1df98592010-02-16 11:11:14 +0000645 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000646 return Error(AliaseeLoc, "alias must have pointer type");
647
648 // Okay, create the alias but do not insert it into the module yet.
649 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650 (GlobalValue::LinkageTypes)Linkage, Name,
651 Aliasee);
652 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 // See if this value already exists in the symbol table. If so, it is either
655 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000656 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 // See if this was a redefinition. If so, there is no entry in
658 // ForwardRefVals.
659 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefVals.find(Name);
661 if (I == ForwardRefVals.end())
662 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
663
664 // Otherwise, this was a definition of forward ref. Verify that types
665 // agree.
666 if (Val->getType() != GA->getType())
667 return Error(NameLoc,
668 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 // If they agree, just RAUW the old value with the alias and remove the
671 // forward ref info.
672 Val->replaceAllUsesWith(GA);
673 Val->eraseFromParent();
674 ForwardRefVals.erase(I);
675 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 // Insert into the module, we know its name won't collide now.
678 M->getAliasList().push_back(GA);
679 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000680
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 return false;
682}
683
684/// ParseGlobal
685/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
686/// OptionalAddrSpace GlobalType Type Const
687/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
688/// OptionalAddrSpace GlobalType Type Const
689///
690/// Everything through visibility has been parsed already.
691///
692bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693 unsigned Linkage, bool HasLinkage,
694 unsigned Visibility) {
695 unsigned AddrSpace;
696 bool ThreadLocal, IsConstant;
697 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000698
Owen Anderson1d0be152009-08-13 21:58:54 +0000699 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
701 ParseOptionalAddrSpace(AddrSpace) ||
702 ParseGlobalType(IsConstant) ||
703 ParseType(Ty, TyLoc))
704 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000705
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 // If the linkage is specified and is external, then no initializer is
707 // present.
708 Constant *Init = 0;
709 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000710 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 Linkage != GlobalValue::ExternalLinkage)) {
712 if (ParseGlobalValue(Ty, Init))
713 return true;
714 }
715
Duncan Sands1df98592010-02-16 11:11:14 +0000716 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000717 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 GlobalVariable *GV = 0;
720
721 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000722 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000723 if (GlobalValue *GVal = M->getNamedValue(Name)) {
724 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
725 return Error(NameLoc, "redefinition of global '@" + Name + "'");
726 GV = cast<GlobalVariable>(GVal);
727 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000728 } else {
729 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
730 I = ForwardRefValIDs.find(NumberedVals.size());
731 if (I != ForwardRefValIDs.end()) {
732 GV = cast<GlobalVariable>(I->second.first);
733 ForwardRefValIDs.erase(I);
734 }
735 }
736
737 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000738 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000739 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 } else {
741 if (GV->getType()->getElementType() != Ty)
742 return Error(TyLoc,
743 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 // Move the forward-reference to the correct spot in the module.
746 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
747 }
748
749 if (Name.empty())
750 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751
Chris Lattnerdf986172009-01-02 07:01:27 +0000752 // Set the parsed properties on the global.
753 if (Init)
754 GV->setInitializer(Init);
755 GV->setConstant(IsConstant);
756 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
757 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
758 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerdf986172009-01-02 07:01:27 +0000760 // Parse attributes on the global.
761 while (Lex.getKind() == lltok::comma) {
762 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 if (Lex.getKind() == lltok::kw_section) {
765 Lex.Lex();
766 GV->setSection(Lex.getStrVal());
767 if (ParseToken(lltok::StringConstant, "expected global section string"))
768 return true;
769 } else if (Lex.getKind() == lltok::kw_align) {
770 unsigned Alignment;
771 if (ParseOptionalAlignment(Alignment)) return true;
772 GV->setAlignment(Alignment);
773 } else {
774 TokError("unknown global variable property!");
775 }
776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Chris Lattnerdf986172009-01-02 07:01:27 +0000778 return false;
779}
780
781
782//===----------------------------------------------------------------------===//
783// GlobalValue Reference/Resolution Routines.
784//===----------------------------------------------------------------------===//
785
786/// GetGlobalVal - Get a value with the specified name or ID, creating a
787/// forward reference record if needed. This can return null if the value
788/// exists but does not have the right type.
789GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
790 LocTy Loc) {
791 const PointerType *PTy = dyn_cast<PointerType>(Ty);
792 if (PTy == 0) {
793 Error(Loc, "global variable reference must have pointer type");
794 return 0;
795 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 // Look this name up in the normal function symbol table.
798 GlobalValue *Val =
799 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000800
Chris Lattnerdf986172009-01-02 07:01:27 +0000801 // If this is a forward reference for the value, see if we already created a
802 // forward ref record.
803 if (Val == 0) {
804 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
805 I = ForwardRefVals.find(Name);
806 if (I != ForwardRefVals.end())
807 Val = I->second.first;
808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000809
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 // If we have the value in the symbol table or fwd-ref table, return it.
811 if (Val) {
812 if (Val->getType() == Ty) return Val;
813 Error(Loc, "'@" + Name + "' defined with type '" +
814 Val->getType()->getDescription() + "'");
815 return 0;
816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000817
Chris Lattnerdf986172009-01-02 07:01:27 +0000818 // Otherwise, create a new forward reference for this value and remember it.
819 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000820 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
821 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000822 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000823 Error(Loc, "function may not return opaque type");
824 return 0;
825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000827 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000828 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000829 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
830 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000831 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000832
Chris Lattnerdf986172009-01-02 07:01:27 +0000833 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
834 return FwdVal;
835}
836
837GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
838 const PointerType *PTy = dyn_cast<PointerType>(Ty);
839 if (PTy == 0) {
840 Error(Loc, "global variable reference must have pointer type");
841 return 0;
842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Chris Lattnerdf986172009-01-02 07:01:27 +0000844 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000845
Chris Lattnerdf986172009-01-02 07:01:27 +0000846 // If this is a forward reference for the value, see if we already created a
847 // forward ref record.
848 if (Val == 0) {
849 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
850 I = ForwardRefValIDs.find(ID);
851 if (I != ForwardRefValIDs.end())
852 Val = I->second.first;
853 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000854
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 // If we have the value in the symbol table or fwd-ref table, return it.
856 if (Val) {
857 if (Val->getType() == Ty) return Val;
858 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
859 Val->getType()->getDescription() + "'");
860 return 0;
861 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000862
Chris Lattnerdf986172009-01-02 07:01:27 +0000863 // Otherwise, create a new forward reference for this value and remember it.
864 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000865 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
866 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000867 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000868 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000869 return 0;
870 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000871 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000872 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000873 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
874 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000875 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000876
Chris Lattnerdf986172009-01-02 07:01:27 +0000877 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
878 return FwdVal;
879}
880
881
882//===----------------------------------------------------------------------===//
883// Helper Routines.
884//===----------------------------------------------------------------------===//
885
886/// ParseToken - If the current token has the specified kind, eat it and return
887/// success. Otherwise, emit the specified error and return failure.
888bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
889 if (Lex.getKind() != T)
890 return TokError(ErrMsg);
891 Lex.Lex();
892 return false;
893}
894
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000895/// ParseStringConstant
896/// ::= StringConstant
897bool LLParser::ParseStringConstant(std::string &Result) {
898 if (Lex.getKind() != lltok::StringConstant)
899 return TokError("expected string constant");
900 Result = Lex.getStrVal();
901 Lex.Lex();
902 return false;
903}
904
905/// ParseUInt32
906/// ::= uint32
907bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000908 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
909 return TokError("expected integer");
910 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
911 if (Val64 != unsigned(Val64))
912 return TokError("expected 32-bit integer (too large)");
913 Val = Val64;
914 Lex.Lex();
915 return false;
916}
917
918
919/// ParseOptionalAddrSpace
920/// := /*empty*/
921/// := 'addrspace' '(' uint32 ')'
922bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
923 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000924 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000925 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000926 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000927 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000929}
Chris Lattnerdf986172009-01-02 07:01:27 +0000930
931/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
932/// indicates what kind of attribute list this is: 0: function arg, 1: result,
933/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000934/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000935bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
936 Attrs = Attribute::None;
937 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000938
Chris Lattnerdf986172009-01-02 07:01:27 +0000939 while (1) {
940 switch (Lex.getKind()) {
941 case lltok::kw_sext:
942 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000943 // Treat these as signext/zeroext if they occur in the argument list after
944 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
945 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
946 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000948 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000949 if (Lex.getKind() == lltok::kw_sext)
950 Attrs |= Attribute::SExt;
951 else
952 Attrs |= Attribute::ZExt;
953 break;
954 }
955 // FALL THROUGH.
956 default: // End of attributes.
957 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
958 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000960 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000961 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962
Chris Lattnerdf986172009-01-02 07:01:27 +0000963 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000964 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
965 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
966 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
967 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
968 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
969 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
970 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
971 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000972
Devang Patel578efa92009-06-05 21:57:13 +0000973 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
974 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
975 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
976 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
977 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000978 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000979 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
980 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
981 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
982 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
983 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
984 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000985 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000986
Charles Davis1e063d12010-02-12 00:31:15 +0000987 case lltok::kw_alignstack: {
988 unsigned Alignment;
989 if (ParseOptionalStackAlignment(Alignment))
990 return true;
991 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
992 continue;
993 }
994
Chris Lattnerdf986172009-01-02 07:01:27 +0000995 case lltok::kw_align: {
996 unsigned Alignment;
997 if (ParseOptionalAlignment(Alignment))
998 return true;
999 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1000 continue;
1001 }
Charles Davis1e063d12010-02-12 00:31:15 +00001002
Chris Lattnerdf986172009-01-02 07:01:27 +00001003 }
1004 Lex.Lex();
1005 }
1006}
1007
1008/// ParseOptionalLinkage
1009/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001010/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001011/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001012/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +00001013/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +00001014/// ::= 'internal'
1015/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001016/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001017/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001018/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001019/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001020/// ::= 'appending'
1021/// ::= 'dllexport'
1022/// ::= 'common'
1023/// ::= 'dllimport'
1024/// ::= 'extern_weak'
1025/// ::= 'external'
1026bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1027 HasLinkage = false;
1028 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001029 default: Res=GlobalValue::ExternalLinkage; return false;
1030 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1031 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001032 case lltok::kw_linker_private_weak:
1033 Res = GlobalValue::LinkerPrivateWeakLinkage;
1034 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001035 case lltok::kw_linker_private_weak_def_auto:
1036 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1037 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001038 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1039 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1040 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1041 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1042 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001043 case lltok::kw_available_externally:
1044 Res = GlobalValue::AvailableExternallyLinkage;
1045 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001046 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1047 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1048 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1049 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1050 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1051 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001052 }
1053 Lex.Lex();
1054 HasLinkage = true;
1055 return false;
1056}
1057
1058/// ParseOptionalVisibility
1059/// ::= /*empty*/
1060/// ::= 'default'
1061/// ::= 'hidden'
1062/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001063///
Chris Lattnerdf986172009-01-02 07:01:27 +00001064bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1065 switch (Lex.getKind()) {
1066 default: Res = GlobalValue::DefaultVisibility; return false;
1067 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1068 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1069 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1070 }
1071 Lex.Lex();
1072 return false;
1073}
1074
1075/// ParseOptionalCallingConv
1076/// ::= /*empty*/
1077/// ::= 'ccc'
1078/// ::= 'fastcc'
1079/// ::= 'coldcc'
1080/// ::= 'x86_stdcallcc'
1081/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001082/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001083/// ::= 'arm_apcscc'
1084/// ::= 'arm_aapcscc'
1085/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001086/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001087/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001088///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001089bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001090 switch (Lex.getKind()) {
1091 default: CC = CallingConv::C; return false;
1092 case lltok::kw_ccc: CC = CallingConv::C; break;
1093 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1094 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1095 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1096 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001097 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001098 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1099 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1100 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001101 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001102 case lltok::kw_cc: {
1103 unsigned ArbitraryCC;
1104 Lex.Lex();
1105 if (ParseUInt32(ArbitraryCC)) {
1106 return true;
1107 } else
1108 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1109 return false;
1110 }
1111 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001112 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 Lex.Lex();
1115 return false;
1116}
1117
Chris Lattnerb8c46862009-12-30 05:31:19 +00001118/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001119/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001120bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1121 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001122 do {
1123 if (Lex.getKind() != lltok::MetadataVar)
1124 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001125
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001126 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001127 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001128 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001129
Chris Lattner442ffa12009-12-29 21:53:55 +00001130 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001131 unsigned NodeID;
1132 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001133
1134 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001135 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136
Dan Gohman68261142010-08-24 14:35:45 +00001137 // This code is similar to that of ParseMetadataValue, however it needs to
1138 // have special-case code for a forward reference; see the comments on
1139 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1140 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001141 if (Lex.getKind() == lltok::lbrace) {
1142 ValID ID;
1143 if (ParseMetadataListValue(ID, PFS))
1144 return true;
1145 assert(ID.Kind == ValID::t_MDNode);
1146 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001147 } else {
Dan Gohman309b3af2010-08-24 02:24:03 +00001148 if (ParseMDNodeID(Node, NodeID))
1149 return true;
1150 if (Node) {
1151 // If we got the node, add it to the instruction.
1152 Inst->setMetadata(MDK, Node);
1153 } else {
1154 MDRef R = { Loc, MDK, NodeID };
1155 // Otherwise, remember that this should be resolved later.
1156 ForwardRefInstMetadata[Inst].push_back(R);
1157 }
Chris Lattner449c3102010-04-01 05:14:45 +00001158 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001159
1160 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001161 } while (EatIfPresent(lltok::comma));
1162 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001163}
1164
Chris Lattnerdf986172009-01-02 07:01:27 +00001165/// ParseOptionalAlignment
1166/// ::= /* empty */
1167/// ::= 'align' 4
1168bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1169 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001170 if (!EatIfPresent(lltok::kw_align))
1171 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001172 LocTy AlignLoc = Lex.getLoc();
1173 if (ParseUInt32(Alignment)) return true;
1174 if (!isPowerOf2_32(Alignment))
1175 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001176 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001177 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001178 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001179}
1180
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001181/// ParseOptionalCommaAlign
1182/// ::=
1183/// ::= ',' align 4
1184///
1185/// This returns with AteExtraComma set to true if it ate an excess comma at the
1186/// end.
1187bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1188 bool &AteExtraComma) {
1189 AteExtraComma = false;
1190 while (EatIfPresent(lltok::comma)) {
1191 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001192 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001193 AteExtraComma = true;
1194 return false;
1195 }
1196
Chris Lattner093eed12010-04-23 00:50:50 +00001197 if (Lex.getKind() != lltok::kw_align)
1198 return Error(Lex.getLoc(), "expected metadata or 'align'");
1199
Dan Gohman138aa2a2010-07-28 20:12:04 +00001200 LocTy AlignLoc = Lex.getLoc();
Chris Lattner093eed12010-04-23 00:50:50 +00001201 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001202 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001203
Devang Patelf633a062009-09-17 23:04:48 +00001204 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001205}
1206
Charles Davis1e063d12010-02-12 00:31:15 +00001207/// ParseOptionalStackAlignment
1208/// ::= /* empty */
1209/// ::= 'alignstack' '(' 4 ')'
1210bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1211 Alignment = 0;
1212 if (!EatIfPresent(lltok::kw_alignstack))
1213 return false;
1214 LocTy ParenLoc = Lex.getLoc();
1215 if (!EatIfPresent(lltok::lparen))
1216 return Error(ParenLoc, "expected '('");
1217 LocTy AlignLoc = Lex.getLoc();
1218 if (ParseUInt32(Alignment)) return true;
1219 ParenLoc = Lex.getLoc();
1220 if (!EatIfPresent(lltok::rparen))
1221 return Error(ParenLoc, "expected ')'");
1222 if (!isPowerOf2_32(Alignment))
1223 return Error(AlignLoc, "stack alignment is not a power of two");
1224 return false;
1225}
Devang Patelf633a062009-09-17 23:04:48 +00001226
Chris Lattner628c13a2009-12-30 05:14:00 +00001227/// ParseIndexList - This parses the index list for an insert/extractvalue
1228/// instruction. This sets AteExtraComma in the case where we eat an extra
1229/// comma at the end of the line and find that it is followed by metadata.
1230/// Clients that don't allow metadata can call the version of this function that
1231/// only takes one argument.
1232///
Chris Lattnerdf986172009-01-02 07:01:27 +00001233/// ParseIndexList
1234/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001235///
1236bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1237 bool &AteExtraComma) {
1238 AteExtraComma = false;
1239
Chris Lattnerdf986172009-01-02 07:01:27 +00001240 if (Lex.getKind() != lltok::comma)
1241 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001242
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001243 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001244 if (Lex.getKind() == lltok::MetadataVar) {
1245 AteExtraComma = true;
1246 return false;
1247 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001249 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 Indices.push_back(Idx);
1251 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001252
Chris Lattnerdf986172009-01-02 07:01:27 +00001253 return false;
1254}
1255
1256//===----------------------------------------------------------------------===//
1257// Type Parsing.
1258//===----------------------------------------------------------------------===//
1259
1260/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001261bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1262 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001263 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001264
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 // Verify no unresolved uprefs.
1266 if (!UpRefs.empty())
1267 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001268
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001269 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001270 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 return false;
1273}
1274
1275/// HandleUpRefs - Every time we finish a new layer of types, this function is
1276/// called. It loops through the UpRefs vector, which is a list of the
1277/// currently active types. For each type, if the up-reference is contained in
1278/// the newly completed type, we decrement the level count. When the level
1279/// count reaches zero, the up-referenced type is the type that is passed in:
1280/// thus we can complete the cycle.
1281///
1282PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1283 // If Ty isn't abstract, or if there are no up-references in it, then there is
1284 // nothing to resolve here.
1285 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001286
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 PATypeHolder Ty(ty);
1288#if 0
David Greene0e28d762009-12-23 23:38:28 +00001289 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 << "' newly formed. Resolving upreferences.\n"
1291 << UpRefs.size() << " upreferences active!\n";
1292#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1295 // to zero), we resolve them all together before we resolve them to Ty. At
1296 // the end of the loop, if there is anything to resolve to Ty, it will be in
1297 // this variable.
1298 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001299
Chris Lattnerdf986172009-01-02 07:01:27 +00001300 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1301 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1302 bool ContainsType =
1303 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1304 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001305
Chris Lattnerdf986172009-01-02 07:01:27 +00001306#if 0
David Greene0e28d762009-12-23 23:38:28 +00001307 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001308 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1309 << (ContainsType ? "true" : "false")
1310 << " level=" << UpRefs[i].NestingLevel << "\n";
1311#endif
1312 if (!ContainsType)
1313 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001314
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 // Decrement level of upreference
1316 unsigned Level = --UpRefs[i].NestingLevel;
1317 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001318
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1320 if (Level != 0)
1321 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001322
Chris Lattnerdf986172009-01-02 07:01:27 +00001323#if 0
David Greene0e28d762009-12-23 23:38:28 +00001324 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001325#endif
1326 if (!TypeToResolve)
1327 TypeToResolve = UpRefs[i].UpRefTy;
1328 else
1329 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1330 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1331 --i; // Do not skip the next element.
1332 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001333
Chris Lattnerdf986172009-01-02 07:01:27 +00001334 if (TypeToResolve)
1335 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001336
Chris Lattnerdf986172009-01-02 07:01:27 +00001337 return Ty;
1338}
1339
1340
1341/// ParseTypeRec - The recursive function used to process the internal
1342/// implementation details of types.
1343bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1344 switch (Lex.getKind()) {
1345 default:
1346 return TokError("expected type");
1347 case lltok::Type:
1348 // TypeRec ::= 'float' | 'void' (etc)
1349 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001350 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 break;
1352 case lltok::kw_opaque:
1353 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001354 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 Lex.Lex();
1356 break;
1357 case lltok::lbrace:
1358 // TypeRec ::= '{' ... '}'
1359 if (ParseStructType(Result, false))
1360 return true;
1361 break;
1362 case lltok::lsquare:
1363 // TypeRec ::= '[' ... ']'
1364 Lex.Lex(); // eat the lsquare.
1365 if (ParseArrayVectorType(Result, false))
1366 return true;
1367 break;
1368 case lltok::less: // Either vector or packed struct.
1369 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001370 Lex.Lex();
1371 if (Lex.getKind() == lltok::lbrace) {
1372 if (ParseStructType(Result, true) ||
1373 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001375 } else if (ParseArrayVectorType(Result, true))
1376 return true;
1377 break;
1378 case lltok::LocalVar:
1379 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1380 // TypeRec ::= %foo
1381 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1382 Result = T;
1383 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001384 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001385 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1386 std::make_pair(Result,
1387 Lex.getLoc())));
1388 M->addTypeName(Lex.getStrVal(), Result.get());
1389 }
1390 Lex.Lex();
1391 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001392
Chris Lattnerdf986172009-01-02 07:01:27 +00001393 case lltok::LocalVarID:
1394 // TypeRec ::= %4
1395 if (Lex.getUIntVal() < NumberedTypes.size())
1396 Result = NumberedTypes[Lex.getUIntVal()];
1397 else {
1398 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1399 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1400 if (I != ForwardRefTypeIDs.end())
1401 Result = I->second.first;
1402 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001403 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001404 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1405 std::make_pair(Result,
1406 Lex.getLoc())));
1407 }
1408 }
1409 Lex.Lex();
1410 break;
1411 case lltok::backslash: {
1412 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001414 unsigned Val;
1415 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001416 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001417 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1418 Result = OT;
1419 break;
1420 }
1421 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001422
1423 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 while (1) {
1425 switch (Lex.getKind()) {
1426 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001427 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001428
1429 // TypeRec ::= TypeRec '*'
1430 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001431 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001433 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001434 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001435 if (!PointerType::isValidElementType(Result.get()))
1436 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001437 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 Lex.Lex();
1439 break;
1440
1441 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1442 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001443 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001444 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001445 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001446 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001447 if (!PointerType::isValidElementType(Result.get()))
1448 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001449 unsigned AddrSpace;
1450 if (ParseOptionalAddrSpace(AddrSpace) ||
1451 ParseToken(lltok::star, "expected '*' in address space"))
1452 return true;
1453
Owen Andersondebcb012009-07-29 22:17:13 +00001454 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001455 break;
1456 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001457
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1459 case lltok::lparen:
1460 if (ParseFunctionType(Result))
1461 return true;
1462 break;
1463 }
1464 }
1465}
1466
1467/// ParseParameterList
1468/// ::= '(' ')'
1469/// ::= '(' Arg (',' Arg)* ')'
1470/// Arg
1471/// ::= Type OptionalAttributes Value OptionalAttributes
1472bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1473 PerFunctionState &PFS) {
1474 if (ParseToken(lltok::lparen, "expected '(' in call"))
1475 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattnerdf986172009-01-02 07:01:27 +00001477 while (Lex.getKind() != lltok::rparen) {
1478 // If this isn't the first argument, we need a comma.
1479 if (!ArgList.empty() &&
1480 ParseToken(lltok::comma, "expected ',' in argument list"))
1481 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001482
Chris Lattnerdf986172009-01-02 07:01:27 +00001483 // Parse the argument.
1484 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001485 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001486 unsigned ArgAttrs1 = Attribute::None;
1487 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001488 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001489 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001490 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001491
Chris Lattner287881d2009-12-30 02:11:14 +00001492 // Otherwise, handle normal operands.
1493 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1494 ParseValue(ArgTy, V, PFS) ||
1495 // FIXME: Should not allow attributes after the argument, remove this
1496 // in LLVM 3.0.
1497 ParseOptionalAttrs(ArgAttrs2, 3))
1498 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1500 }
1501
1502 Lex.Lex(); // Lex the ')'.
1503 return false;
1504}
1505
1506
1507
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001508/// ParseArgumentList - Parse the argument list for a function type or function
1509/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001510/// ::= '(' ArgTypeListI ')'
1511/// ArgTypeListI
1512/// ::= /*empty*/
1513/// ::= '...'
1514/// ::= ArgTypeList ',' '...'
1515/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001516///
Chris Lattnerdf986172009-01-02 07:01:27 +00001517bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001518 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001519 isVarArg = false;
1520 assert(Lex.getKind() == lltok::lparen);
1521 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 if (Lex.getKind() == lltok::rparen) {
1524 // empty
1525 } else if (Lex.getKind() == lltok::dotdotdot) {
1526 isVarArg = true;
1527 Lex.Lex();
1528 } else {
1529 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001530 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001532 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001534 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1535 // types (such as a function returning a pointer to itself). If parsing a
1536 // function prototype, we require fully resolved types.
1537 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001538 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001539
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001540 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001541 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001542
Chris Lattnerdf986172009-01-02 07:01:27 +00001543 if (Lex.getKind() == lltok::LocalVar ||
1544 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1545 Name = Lex.getStrVal();
1546 Lex.Lex();
1547 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001548
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001549 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001550 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001551
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001553
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001554 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001555 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001556 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001558 break;
1559 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001560
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 // Otherwise must be an argument type.
1562 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001563 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001564 ParseOptionalAttrs(Attrs, 0)) return true;
1565
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001566 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001567 return Error(TypeLoc, "argument can not have void type");
1568
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 if (Lex.getKind() == lltok::LocalVar ||
1570 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1571 Name = Lex.getStrVal();
1572 Lex.Lex();
1573 } else {
1574 Name = "";
1575 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001576
Duncan Sands47c51882010-02-16 14:50:09 +00001577 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001578 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1581 }
1582 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001584 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001585}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattnerdf986172009-01-02 07:01:27 +00001587/// ParseFunctionType
1588/// ::= Type ArgumentList OptionalAttrs
1589bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1590 assert(Lex.getKind() == lltok::lparen);
1591
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001592 if (!FunctionType::isValidReturnType(Result))
1593 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 std::vector<ArgInfo> ArgList;
1596 bool isVarArg;
1597 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001598 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 // FIXME: Allow, but ignore attributes on function types!
1600 // FIXME: Remove in LLVM 3.0
1601 ParseOptionalAttrs(Attrs, 2))
1602 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001603
Chris Lattnerdf986172009-01-02 07:01:27 +00001604 // Reject names on the arguments lists.
1605 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1606 if (!ArgList[i].Name.empty())
1607 return Error(ArgList[i].Loc, "argument name invalid in function type");
1608 if (!ArgList[i].Attrs != 0) {
1609 // Allow but ignore attributes on function types; this permits
1610 // auto-upgrade.
1611 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1612 }
1613 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001614
Chris Lattnerdf986172009-01-02 07:01:27 +00001615 std::vector<const Type*> ArgListTy;
1616 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1617 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001618
Owen Andersondebcb012009-07-29 22:17:13 +00001619 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001620 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001621 return false;
1622}
1623
1624/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1625/// TypeRec
1626/// ::= '{' '}'
1627/// ::= '{' TypeRec (',' TypeRec)* '}'
1628/// ::= '<' '{' '}' '>'
1629/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1630bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1631 assert(Lex.getKind() == lltok::lbrace);
1632 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001634 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001635 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001636 return false;
1637 }
1638
1639 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001640 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 if (ParseTypeRec(Result)) return true;
1642 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001643
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001644 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001645 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001646 if (!StructType::isValidElementType(Result))
1647 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001648
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001649 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001650 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001651 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001652
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001653 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001654 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001655 if (!StructType::isValidElementType(Result))
1656 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattnerdf986172009-01-02 07:01:27 +00001658 ParamsList.push_back(Result);
1659 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001660
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001661 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1662 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 std::vector<const Type*> ParamsListTy;
1665 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1666 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001667 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001668 return false;
1669}
1670
1671/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1672/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001673/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001674/// ::= '[' APSINTVAL 'x' Types ']'
1675/// ::= '<' APSINTVAL 'x' Types '>'
1676bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1677 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1678 Lex.getAPSIntVal().getBitWidth() > 64)
1679 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001680
Chris Lattnerdf986172009-01-02 07:01:27 +00001681 LocTy SizeLoc = Lex.getLoc();
1682 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001683 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001685 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1686 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001687
1688 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001689 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001691
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001692 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001693 return Error(TypeLoc, "array and vector element type cannot be void");
1694
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001695 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1696 "expected end of sequential type"))
1697 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001700 if (Size == 0)
1701 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 if ((unsigned)Size != Size)
1703 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001704 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001706 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001707 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001708 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001710 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 }
1712 return false;
1713}
1714
1715//===----------------------------------------------------------------------===//
1716// Function Semantic Analysis.
1717//===----------------------------------------------------------------------===//
1718
Chris Lattner09d9ef42009-10-28 03:39:23 +00001719LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1720 int functionNumber)
1721 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001722
1723 // Insert unnamed arguments into the NumberedVals list.
1724 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1725 AI != E; ++AI)
1726 if (!AI->hasName())
1727 NumberedVals.push_back(AI);
1728}
1729
1730LLParser::PerFunctionState::~PerFunctionState() {
1731 // If there were any forward referenced non-basicblock values, delete them.
1732 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1733 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1734 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001735 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001736 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001737 delete I->second.first;
1738 I->second.first = 0;
1739 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001740
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1742 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1743 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001744 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001745 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 delete I->second.first;
1747 I->second.first = 0;
1748 }
1749}
1750
Chris Lattner09d9ef42009-10-28 03:39:23 +00001751bool LLParser::PerFunctionState::FinishFunction() {
1752 // Check to see if someone took the address of labels in this block.
1753 if (!P.ForwardRefBlockAddresses.empty()) {
1754 ValID FunctionID;
1755 if (!F.getName().empty()) {
1756 FunctionID.Kind = ValID::t_GlobalName;
1757 FunctionID.StrVal = F.getName();
1758 } else {
1759 FunctionID.Kind = ValID::t_GlobalID;
1760 FunctionID.UIntVal = FunctionNumber;
1761 }
1762
1763 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1764 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1765 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1766 // Resolve all these references.
1767 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1768 return true;
1769
1770 P.ForwardRefBlockAddresses.erase(FRBAI);
1771 }
1772 }
1773
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 if (!ForwardRefVals.empty())
1775 return P.Error(ForwardRefVals.begin()->second.second,
1776 "use of undefined value '%" + ForwardRefVals.begin()->first +
1777 "'");
1778 if (!ForwardRefValIDs.empty())
1779 return P.Error(ForwardRefValIDs.begin()->second.second,
1780 "use of undefined value '%" +
1781 utostr(ForwardRefValIDs.begin()->first) + "'");
1782 return false;
1783}
1784
1785
1786/// GetVal - Get a value with the specified name or ID, creating a
1787/// forward reference record if needed. This can return null if the value
1788/// exists but does not have the right type.
1789Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1790 const Type *Ty, LocTy Loc) {
1791 // Look this name up in the normal function symbol table.
1792 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001793
Chris Lattnerdf986172009-01-02 07:01:27 +00001794 // If this is a forward reference for the value, see if we already created a
1795 // forward ref record.
1796 if (Val == 0) {
1797 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1798 I = ForwardRefVals.find(Name);
1799 if (I != ForwardRefVals.end())
1800 Val = I->second.first;
1801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001802
Chris Lattnerdf986172009-01-02 07:01:27 +00001803 // If we have the value in the symbol table or fwd-ref table, return it.
1804 if (Val) {
1805 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001806 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 P.Error(Loc, "'%" + Name + "' is not a basic block");
1808 else
1809 P.Error(Loc, "'%" + Name + "' defined with type '" +
1810 Val->getType()->getDescription() + "'");
1811 return 0;
1812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001813
Chris Lattnerdf986172009-01-02 07:01:27 +00001814 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001815 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001816 P.Error(Loc, "invalid use of a non-first-class type");
1817 return 0;
1818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001819
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 // Otherwise, create a new forward reference for this value and remember it.
1821 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001822 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001823 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 else
1825 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001826
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1828 return FwdVal;
1829}
1830
1831Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1832 LocTy Loc) {
1833 // Look this name up in the normal function symbol table.
1834 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001835
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 // If this is a forward reference for the value, see if we already created a
1837 // forward ref record.
1838 if (Val == 0) {
1839 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1840 I = ForwardRefValIDs.find(ID);
1841 if (I != ForwardRefValIDs.end())
1842 Val = I->second.first;
1843 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001844
Chris Lattnerdf986172009-01-02 07:01:27 +00001845 // If we have the value in the symbol table or fwd-ref table, return it.
1846 if (Val) {
1847 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001848 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1850 else
1851 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1852 Val->getType()->getDescription() + "'");
1853 return 0;
1854 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001855
Duncan Sands47c51882010-02-16 14:50:09 +00001856 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 P.Error(Loc, "invalid use of a non-first-class type");
1858 return 0;
1859 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001860
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 // Otherwise, create a new forward reference for this value and remember it.
1862 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001863 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001864 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001865 else
1866 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001867
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1869 return FwdVal;
1870}
1871
1872/// SetInstName - After an instruction is parsed and inserted into its
1873/// basic block, this installs its name.
1874bool LLParser::PerFunctionState::SetInstName(int NameID,
1875 const std::string &NameStr,
1876 LocTy NameLoc, Instruction *Inst) {
1877 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001878 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001879 if (NameID != -1 || !NameStr.empty())
1880 return P.Error(NameLoc, "instructions returning void cannot have a name");
1881 return false;
1882 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001883
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 // If this was a numbered instruction, verify that the instruction is the
1885 // expected value and resolve any forward references.
1886 if (NameStr.empty()) {
1887 // If neither a name nor an ID was specified, just use the next ID.
1888 if (NameID == -1)
1889 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001890
Chris Lattnerdf986172009-01-02 07:01:27 +00001891 if (unsigned(NameID) != NumberedVals.size())
1892 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1893 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Chris Lattnerdf986172009-01-02 07:01:27 +00001895 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1896 ForwardRefValIDs.find(NameID);
1897 if (FI != ForwardRefValIDs.end()) {
1898 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001899 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 FI->second.first->getType()->getDescription() + "'");
1901 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001902 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 ForwardRefValIDs.erase(FI);
1904 }
1905
1906 NumberedVals.push_back(Inst);
1907 return false;
1908 }
1909
1910 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1911 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1912 FI = ForwardRefVals.find(NameStr);
1913 if (FI != ForwardRefVals.end()) {
1914 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 FI->second.first->getType()->getDescription() + "'");
1917 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001918 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 ForwardRefVals.erase(FI);
1920 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 // Set the name on the instruction.
1923 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001927 NameStr + "'");
1928 return false;
1929}
1930
1931/// GetBB - Get a basic block with the specified name or ID, creating a
1932/// forward reference record if needed.
1933BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1934 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001935 return cast_or_null<BasicBlock>(GetVal(Name,
1936 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001937}
1938
1939BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001940 return cast_or_null<BasicBlock>(GetVal(ID,
1941 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001942}
1943
1944/// DefineBB - Define the specified basic block, which is either named or
1945/// unnamed. If there is an error, this returns null otherwise it returns
1946/// the block being defined.
1947BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1948 LocTy Loc) {
1949 BasicBlock *BB;
1950 if (Name.empty())
1951 BB = GetBB(NumberedVals.size(), Loc);
1952 else
1953 BB = GetBB(Name, Loc);
1954 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Chris Lattnerdf986172009-01-02 07:01:27 +00001956 // Move the block to the end of the function. Forward ref'd blocks are
1957 // inserted wherever they happen to be referenced.
1958 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 // Remove the block from forward ref sets.
1961 if (Name.empty()) {
1962 ForwardRefValIDs.erase(NumberedVals.size());
1963 NumberedVals.push_back(BB);
1964 } else {
1965 // BB forward references are already in the function symbol table.
1966 ForwardRefVals.erase(Name);
1967 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001968
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 return BB;
1970}
1971
1972//===----------------------------------------------------------------------===//
1973// Constants.
1974//===----------------------------------------------------------------------===//
1975
1976/// ParseValID - Parse an abstract value that doesn't necessarily have a
1977/// type implied. For example, if we parse "4" we don't know what integer type
1978/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001979/// sanity. PFS is used to convert function-local operands of metadata (since
1980/// metadata operands are not just parsed here but also converted to values).
1981/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001982bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 ID.Loc = Lex.getLoc();
1984 switch (Lex.getKind()) {
1985 default: return TokError("expected value token");
1986 case lltok::GlobalID: // @42
1987 ID.UIntVal = Lex.getUIntVal();
1988 ID.Kind = ValID::t_GlobalID;
1989 break;
1990 case lltok::GlobalVar: // @foo
1991 ID.StrVal = Lex.getStrVal();
1992 ID.Kind = ValID::t_GlobalName;
1993 break;
1994 case lltok::LocalVarID: // %42
1995 ID.UIntVal = Lex.getUIntVal();
1996 ID.Kind = ValID::t_LocalID;
1997 break;
1998 case lltok::LocalVar: // %foo
1999 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2000 ID.StrVal = Lex.getStrVal();
2001 ID.Kind = ValID::t_LocalName;
2002 break;
Dan Gohman83448032010-07-14 18:26:50 +00002003 case lltok::exclaim: // !42, !{...}, or !"foo"
2004 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002005 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002006 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 ID.Kind = ValID::t_APSInt;
2008 break;
2009 case lltok::APFloat:
2010 ID.APFloatVal = Lex.getAPFloatVal();
2011 ID.Kind = ValID::t_APFloat;
2012 break;
2013 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002014 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 ID.Kind = ValID::t_Constant;
2016 break;
2017 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002018 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 ID.Kind = ValID::t_Constant;
2020 break;
2021 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2022 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2023 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Chris Lattnerdf986172009-01-02 07:01:27 +00002025 case lltok::lbrace: {
2026 // ValID ::= '{' ConstVector '}'
2027 Lex.Lex();
2028 SmallVector<Constant*, 16> Elts;
2029 if (ParseGlobalValueVector(Elts) ||
2030 ParseToken(lltok::rbrace, "expected end of struct constant"))
2031 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002032
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002033 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2034 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 ID.Kind = ValID::t_Constant;
2036 return false;
2037 }
2038 case lltok::less: {
2039 // ValID ::= '<' ConstVector '>' --> Vector.
2040 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2041 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002042 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 SmallVector<Constant*, 16> Elts;
2045 LocTy FirstEltLoc = Lex.getLoc();
2046 if (ParseGlobalValueVector(Elts) ||
2047 (isPackedStruct &&
2048 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2049 ParseToken(lltok::greater, "expected end of constant"))
2050 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002053 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002054 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 ID.Kind = ValID::t_Constant;
2056 return false;
2057 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002058
Chris Lattnerdf986172009-01-02 07:01:27 +00002059 if (Elts.empty())
2060 return Error(ID.Loc, "constant vector must not be empty");
2061
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002062 if (!Elts[0]->getType()->isIntegerTy() &&
2063 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 return Error(FirstEltLoc,
2065 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002066
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 // Verify that all the vector elements have the same type.
2068 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2069 if (Elts[i]->getType() != Elts[0]->getType())
2070 return Error(FirstEltLoc,
2071 "vector element #" + utostr(i) +
2072 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002073
Owen Andersonaf7ec972009-07-28 21:19:26 +00002074 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 ID.Kind = ValID::t_Constant;
2076 return false;
2077 }
2078 case lltok::lsquare: { // Array Constant
2079 Lex.Lex();
2080 SmallVector<Constant*, 16> Elts;
2081 LocTy FirstEltLoc = Lex.getLoc();
2082 if (ParseGlobalValueVector(Elts) ||
2083 ParseToken(lltok::rsquare, "expected end of array constant"))
2084 return true;
2085
2086 // Handle empty element.
2087 if (Elts.empty()) {
2088 // Use undef instead of an array because it's inconvenient to determine
2089 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002090 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 return false;
2092 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002093
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002096 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002097
Owen Andersondebcb012009-07-29 22:17:13 +00002098 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002101 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 if (Elts[i]->getType() != Elts[0]->getType())
2103 return Error(FirstEltLoc,
2104 "array element #" + utostr(i) +
2105 " is not of type '" +Elts[0]->getType()->getDescription());
2106 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107
Owen Anderson1fd70962009-07-28 18:32:17 +00002108 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002109 ID.Kind = ValID::t_Constant;
2110 return false;
2111 }
2112 case lltok::kw_c: // c "foo"
2113 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002114 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002115 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2116 ID.Kind = ValID::t_Constant;
2117 return false;
2118
2119 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002120 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2121 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002122 Lex.Lex();
2123 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002124 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002125 ParseStringConstant(ID.StrVal) ||
2126 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002127 ParseToken(lltok::StringConstant, "expected constraint string"))
2128 return true;
2129 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002130 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 ID.Kind = ValID::t_InlineAsm;
2132 return false;
2133 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002134
Chris Lattner09d9ef42009-10-28 03:39:23 +00002135 case lltok::kw_blockaddress: {
2136 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2137 Lex.Lex();
2138
2139 ValID Fn, Label;
2140 LocTy FnLoc, LabelLoc;
2141
2142 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2143 ParseValID(Fn) ||
2144 ParseToken(lltok::comma, "expected comma in block address expression")||
2145 ParseValID(Label) ||
2146 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2147 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002148
Chris Lattner09d9ef42009-10-28 03:39:23 +00002149 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2150 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002151 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002152 return Error(Label.Loc, "expected basic block name in blockaddress");
2153
2154 // Make a global variable as a placeholder for this reference.
2155 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2156 false, GlobalValue::InternalLinkage,
2157 0, "");
2158 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2159 ID.ConstantVal = FwdRef;
2160 ID.Kind = ValID::t_Constant;
2161 return false;
2162 }
2163
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 case lltok::kw_trunc:
2165 case lltok::kw_zext:
2166 case lltok::kw_sext:
2167 case lltok::kw_fptrunc:
2168 case lltok::kw_fpext:
2169 case lltok::kw_bitcast:
2170 case lltok::kw_uitofp:
2171 case lltok::kw_sitofp:
2172 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002173 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002175 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002177 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 Constant *SrcVal;
2179 Lex.Lex();
2180 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2181 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002182 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002183 ParseType(DestTy) ||
2184 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2185 return true;
2186 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2187 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2188 SrcVal->getType()->getDescription() + "' to '" +
2189 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002190 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002191 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 ID.Kind = ValID::t_Constant;
2193 return false;
2194 }
2195 case lltok::kw_extractvalue: {
2196 Lex.Lex();
2197 Constant *Val;
2198 SmallVector<unsigned, 4> Indices;
2199 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2200 ParseGlobalTypeAndValue(Val) ||
2201 ParseIndexList(Indices) ||
2202 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2203 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002204
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002205 if (!Val->getType()->isAggregateType())
2206 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2208 Indices.end()))
2209 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002210 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002211 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002212 ID.Kind = ValID::t_Constant;
2213 return false;
2214 }
2215 case lltok::kw_insertvalue: {
2216 Lex.Lex();
2217 Constant *Val0, *Val1;
2218 SmallVector<unsigned, 4> Indices;
2219 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2220 ParseGlobalTypeAndValue(Val0) ||
2221 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2222 ParseGlobalTypeAndValue(Val1) ||
2223 ParseIndexList(Indices) ||
2224 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2225 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002226 if (!Val0->getType()->isAggregateType())
2227 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2229 Indices.end()))
2230 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002231 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002232 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 ID.Kind = ValID::t_Constant;
2234 return false;
2235 }
2236 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002237 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002238 unsigned PredVal, Opc = Lex.getUIntVal();
2239 Constant *Val0, *Val1;
2240 Lex.Lex();
2241 if (ParseCmpPredicate(PredVal, Opc) ||
2242 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2243 ParseGlobalTypeAndValue(Val0) ||
2244 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2245 ParseGlobalTypeAndValue(Val1) ||
2246 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2247 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002248
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 if (Val0->getType() != Val1->getType())
2250 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002253
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002255 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002257 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002258 } else {
2259 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002260 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002261 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002262 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002263 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 }
2265 ID.Kind = ValID::t_Constant;
2266 return false;
2267 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002268
Chris Lattnerdf986172009-01-02 07:01:27 +00002269 // Binary Operators.
2270 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002271 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002273 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002275 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 case lltok::kw_udiv:
2277 case lltok::kw_sdiv:
2278 case lltok::kw_fdiv:
2279 case lltok::kw_urem:
2280 case lltok::kw_srem:
2281 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002282 bool NUW = false;
2283 bool NSW = false;
2284 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002285 unsigned Opc = Lex.getUIntVal();
2286 Constant *Val0, *Val1;
2287 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002288 LocTy ModifierLoc = Lex.getLoc();
2289 if (Opc == Instruction::Add ||
2290 Opc == Instruction::Sub ||
2291 Opc == Instruction::Mul) {
2292 if (EatIfPresent(lltok::kw_nuw))
2293 NUW = true;
2294 if (EatIfPresent(lltok::kw_nsw)) {
2295 NSW = true;
2296 if (EatIfPresent(lltok::kw_nuw))
2297 NUW = true;
2298 }
2299 } else if (Opc == Instruction::SDiv) {
2300 if (EatIfPresent(lltok::kw_exact))
2301 Exact = true;
2302 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002303 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2304 ParseGlobalTypeAndValue(Val0) ||
2305 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2306 ParseGlobalTypeAndValue(Val1) ||
2307 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2308 return true;
2309 if (Val0->getType() != Val1->getType())
2310 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002311 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002312 if (NUW)
2313 return Error(ModifierLoc, "nuw only applies to integer operations");
2314 if (NSW)
2315 return Error(ModifierLoc, "nsw only applies to integer operations");
2316 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002317 // Check that the type is valid for the operator.
2318 switch (Opc) {
2319 case Instruction::Add:
2320 case Instruction::Sub:
2321 case Instruction::Mul:
2322 case Instruction::UDiv:
2323 case Instruction::SDiv:
2324 case Instruction::URem:
2325 case Instruction::SRem:
2326 if (!Val0->getType()->isIntOrIntVectorTy())
2327 return Error(ID.Loc, "constexpr requires integer operands");
2328 break;
2329 case Instruction::FAdd:
2330 case Instruction::FSub:
2331 case Instruction::FMul:
2332 case Instruction::FDiv:
2333 case Instruction::FRem:
2334 if (!Val0->getType()->isFPOrFPVectorTy())
2335 return Error(ID.Loc, "constexpr requires fp operands");
2336 break;
2337 default: llvm_unreachable("Unknown binary operator!");
2338 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002339 unsigned Flags = 0;
2340 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2341 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2342 if (Exact) Flags |= SDivOperator::IsExact;
2343 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002344 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002345 ID.Kind = ValID::t_Constant;
2346 return false;
2347 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002348
Chris Lattnerdf986172009-01-02 07:01:27 +00002349 // Logical Operations
2350 case lltok::kw_shl:
2351 case lltok::kw_lshr:
2352 case lltok::kw_ashr:
2353 case lltok::kw_and:
2354 case lltok::kw_or:
2355 case lltok::kw_xor: {
2356 unsigned Opc = Lex.getUIntVal();
2357 Constant *Val0, *Val1;
2358 Lex.Lex();
2359 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2360 ParseGlobalTypeAndValue(Val0) ||
2361 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2362 ParseGlobalTypeAndValue(Val1) ||
2363 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2364 return true;
2365 if (Val0->getType() != Val1->getType())
2366 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002367 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002368 return Error(ID.Loc,
2369 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002370 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002371 ID.Kind = ValID::t_Constant;
2372 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002373 }
2374
Chris Lattnerdf986172009-01-02 07:01:27 +00002375 case lltok::kw_getelementptr:
2376 case lltok::kw_shufflevector:
2377 case lltok::kw_insertelement:
2378 case lltok::kw_extractelement:
2379 case lltok::kw_select: {
2380 unsigned Opc = Lex.getUIntVal();
2381 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002382 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002383 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002384 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002385 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2387 ParseGlobalValueVector(Elts) ||
2388 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2389 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002390
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002392 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002396 (Value**)(Elts.data() + 1),
2397 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002399 ID.ConstantVal = InBounds ?
2400 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2401 Elts.data() + 1,
2402 Elts.size() - 1) :
2403 ConstantExpr::getGetElementPtr(Elts[0],
2404 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002405 } else if (Opc == Instruction::Select) {
2406 if (Elts.size() != 3)
2407 return Error(ID.Loc, "expected three operands to select");
2408 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2409 Elts[2]))
2410 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002411 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002412 } else if (Opc == Instruction::ShuffleVector) {
2413 if (Elts.size() != 3)
2414 return Error(ID.Loc, "expected three operands to shufflevector");
2415 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2416 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002417 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002418 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002419 } else if (Opc == Instruction::ExtractElement) {
2420 if (Elts.size() != 2)
2421 return Error(ID.Loc, "expected two operands to extractelement");
2422 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2423 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002424 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002425 } else {
2426 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2427 if (Elts.size() != 3)
2428 return Error(ID.Loc, "expected three operands to insertelement");
2429 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2430 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002431 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002432 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002433 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002434
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 ID.Kind = ValID::t_Constant;
2436 return false;
2437 }
2438 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002439
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 Lex.Lex();
2441 return false;
2442}
2443
2444/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002445bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2446 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002447 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002448 Value *V = NULL;
2449 bool Parsed = ParseValID(ID) ||
2450 ConvertValIDToValue(Ty, ID, V, NULL);
2451 if (V && !(C = dyn_cast<Constant>(V)))
2452 return Error(ID.Loc, "global values must be constants");
2453 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002454}
2455
Victor Hernandez92f238d2010-01-11 22:31:58 +00002456bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2457 PATypeHolder Type(Type::getVoidTy(Context));
2458 return ParseType(Type) ||
2459 ParseGlobalValue(Type, V);
2460}
2461
2462/// ParseGlobalValueVector
2463/// ::= /*empty*/
2464/// ::= TypeAndValue (',' TypeAndValue)*
2465bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2466 // Empty list.
2467 if (Lex.getKind() == lltok::rbrace ||
2468 Lex.getKind() == lltok::rsquare ||
2469 Lex.getKind() == lltok::greater ||
2470 Lex.getKind() == lltok::rparen)
2471 return false;
2472
2473 Constant *C;
2474 if (ParseGlobalTypeAndValue(C)) return true;
2475 Elts.push_back(C);
2476
2477 while (EatIfPresent(lltok::comma)) {
2478 if (ParseGlobalTypeAndValue(C)) return true;
2479 Elts.push_back(C);
2480 }
2481
2482 return false;
2483}
2484
Dan Gohman309b3af2010-08-24 02:24:03 +00002485bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2486 assert(Lex.getKind() == lltok::lbrace);
2487 Lex.Lex();
2488
2489 SmallVector<Value*, 16> Elts;
2490 if (ParseMDNodeVector(Elts, PFS) ||
2491 ParseToken(lltok::rbrace, "expected end of metadata node"))
2492 return true;
2493
2494 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2495 ID.Kind = ValID::t_MDNode;
2496 return false;
2497}
2498
Dan Gohman83448032010-07-14 18:26:50 +00002499/// ParseMetadataValue
2500/// ::= !42
2501/// ::= !{...}
2502/// ::= !"string"
2503bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2504 assert(Lex.getKind() == lltok::exclaim);
2505 Lex.Lex();
2506
2507 // MDNode:
2508 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002509 if (Lex.getKind() == lltok::lbrace)
2510 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002511
2512 // Standalone metadata reference
2513 // !42
2514 if (Lex.getKind() == lltok::APSInt) {
2515 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2516 ID.Kind = ValID::t_MDNode;
2517 return false;
2518 }
2519
2520 // MDString:
2521 // ::= '!' STRINGCONSTANT
2522 if (ParseMDString(ID.MDStringVal)) return true;
2523 ID.Kind = ValID::t_MDString;
2524 return false;
2525}
2526
Victor Hernandez92f238d2010-01-11 22:31:58 +00002527
2528//===----------------------------------------------------------------------===//
2529// Function Parsing.
2530//===----------------------------------------------------------------------===//
2531
2532bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2533 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002534 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002536
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002538 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002540 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2541 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2542 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002543 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002544 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2545 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2546 return (V == 0);
2547 case ValID::t_InlineAsm: {
2548 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2549 const FunctionType *FTy =
2550 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2551 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2552 return Error(ID.Loc, "invalid type for inline asm constraint string");
2553 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2554 return false;
2555 }
2556 case ValID::t_MDNode:
2557 if (!Ty->isMetadataTy())
2558 return Error(ID.Loc, "metadata value must have metadata type");
2559 V = ID.MDNodeVal;
2560 return false;
2561 case ValID::t_MDString:
2562 if (!Ty->isMetadataTy())
2563 return Error(ID.Loc, "metadata value must have metadata type");
2564 V = ID.MDStringVal;
2565 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002566 case ValID::t_GlobalName:
2567 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2568 return V == 0;
2569 case ValID::t_GlobalID:
2570 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2571 return V == 0;
2572 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002573 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 return Error(ID.Loc, "integer constant must have integer type");
2575 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002576 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002577 return false;
2578 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002579 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002580 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2581 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 // The lexer has no type info, so builds all float and double FP constants
2584 // as double. Fix this here. Long double does not need this.
2585 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002586 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 bool Ignored;
2588 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2589 &Ignored);
2590 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002591 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002592
Chris Lattner959873d2009-01-05 18:24:23 +00002593 if (V->getType() != Ty)
2594 return Error(ID.Loc, "floating point constant does not have type '" +
2595 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 return false;
2598 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002599 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002601 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 return false;
2603 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002604 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002605 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002606 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002607 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002608 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002609 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002610 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002611 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002612 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002613 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002614 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002616 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002617 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002619 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 return false;
2621 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002622 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002623 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002624
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 V = ID.ConstantVal;
2626 return false;
2627 }
2628}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattnerdf986172009-01-02 07:01:27 +00002630bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2631 V = 0;
2632 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002633 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002634 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002635}
2636
2637bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002638 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002639 return ParseType(T) ||
2640 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002641}
2642
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002643bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2644 PerFunctionState &PFS) {
2645 Value *V;
2646 Loc = Lex.getLoc();
2647 if (ParseTypeAndValue(V, PFS)) return true;
2648 if (!isa<BasicBlock>(V))
2649 return Error(Loc, "expected a basic block");
2650 BB = cast<BasicBlock>(V);
2651 return false;
2652}
2653
2654
Chris Lattnerdf986172009-01-02 07:01:27 +00002655/// FunctionHeader
2656/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2657/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2658/// OptionalAlign OptGC
2659bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2660 // Parse the linkage.
2661 LocTy LinkageLoc = Lex.getLoc();
2662 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002663
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002664 unsigned Visibility, RetAttrs;
2665 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002666 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002667 LocTy RetTypeLoc = Lex.getLoc();
2668 if (ParseOptionalLinkage(Linkage) ||
2669 ParseOptionalVisibility(Visibility) ||
2670 ParseOptionalCallingConv(CC) ||
2671 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002672 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002673 return true;
2674
2675 // Verify that the linkage is ok.
2676 switch ((GlobalValue::LinkageTypes)Linkage) {
2677 case GlobalValue::ExternalLinkage:
2678 break; // always ok.
2679 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002680 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002681 if (isDefine)
2682 return Error(LinkageLoc, "invalid linkage for function definition");
2683 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002684 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002685 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002686 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002687 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002688 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002689 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002690 case GlobalValue::LinkOnceAnyLinkage:
2691 case GlobalValue::LinkOnceODRLinkage:
2692 case GlobalValue::WeakAnyLinkage:
2693 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 case GlobalValue::DLLExportLinkage:
2695 if (!isDefine)
2696 return Error(LinkageLoc, "invalid linkage for function declaration");
2697 break;
2698 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002699 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 return Error(LinkageLoc, "invalid function linkage type");
2701 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002702
Chris Lattner99bb3152009-01-05 08:00:30 +00002703 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002704 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002705 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002706
Chris Lattnerdf986172009-01-02 07:01:27 +00002707 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002708
2709 std::string FunctionName;
2710 if (Lex.getKind() == lltok::GlobalVar) {
2711 FunctionName = Lex.getStrVal();
2712 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2713 unsigned NameID = Lex.getUIntVal();
2714
2715 if (NameID != NumberedVals.size())
2716 return TokError("function expected to be numbered '%" +
2717 utostr(NumberedVals.size()) + "'");
2718 } else {
2719 return TokError("expected function name");
2720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002721
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002722 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002724 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002726
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 std::vector<ArgInfo> ArgList;
2728 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002729 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002732 std::string GC;
2733
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002734 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002735 ParseOptionalAttrs(FuncAttrs, 2) ||
2736 (EatIfPresent(lltok::kw_section) &&
2737 ParseStringConstant(Section)) ||
2738 ParseOptionalAlignment(Alignment) ||
2739 (EatIfPresent(lltok::kw_gc) &&
2740 ParseStringConstant(GC)))
2741 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002742
2743 // If the alignment was parsed as an attribute, move to the alignment field.
2744 if (FuncAttrs & Attribute::Alignment) {
2745 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2746 FuncAttrs &= ~Attribute::Alignment;
2747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002748
Chris Lattnerdf986172009-01-02 07:01:27 +00002749 // Okay, if we got here, the function is syntactically valid. Convert types
2750 // and do semantic checks.
2751 std::vector<const Type*> ParamTypeList;
2752 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002753 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002754 // attributes.
2755 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2756 if (FuncAttrs & ObsoleteFuncAttrs) {
2757 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2758 FuncAttrs &= ~ObsoleteFuncAttrs;
2759 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002760
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 if (RetAttrs != Attribute::None)
2762 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002763
Chris Lattnerdf986172009-01-02 07:01:27 +00002764 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2765 ParamTypeList.push_back(ArgList[i].Type);
2766 if (ArgList[i].Attrs != Attribute::None)
2767 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2768 }
2769
2770 if (FuncAttrs != Attribute::None)
2771 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2772
2773 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002774
Benjamin Kramerf0127052010-01-05 13:12:22 +00002775 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2777
Owen Andersonfba933c2009-07-01 23:57:11 +00002778 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002779 FunctionType::get(RetType, ParamTypeList, isVarArg);
2780 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002781
2782 Fn = 0;
2783 if (!FunctionName.empty()) {
2784 // If this was a definition of a forward reference, remove the definition
2785 // from the forward reference table and fill in the forward ref.
2786 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2787 ForwardRefVals.find(FunctionName);
2788 if (FRVI != ForwardRefVals.end()) {
2789 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002790 if (Fn->getType() != PFT)
2791 return Error(FRVI->second.second, "invalid forward reference to "
2792 "function '" + FunctionName + "' with wrong type!");
2793
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 ForwardRefVals.erase(FRVI);
2795 } else if ((Fn = M->getFunction(FunctionName))) {
2796 // If this function already exists in the symbol table, then it is
2797 // multiply defined. We accept a few cases for old backwards compat.
2798 // FIXME: Remove this stuff for LLVM 3.0.
2799 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2800 (!Fn->isDeclaration() && isDefine)) {
2801 // If the redefinition has different type or different attributes,
2802 // reject it. If both have bodies, reject it.
2803 return Error(NameLoc, "invalid redefinition of function '" +
2804 FunctionName + "'");
2805 } else if (Fn->isDeclaration()) {
2806 // Make sure to strip off any argument names so we can't get conflicts.
2807 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2808 AI != AE; ++AI)
2809 AI->setName("");
2810 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002811 } else if (M->getNamedValue(FunctionName)) {
2812 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002814
Dan Gohman41905542009-08-29 23:37:49 +00002815 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 // If this is a definition of a forward referenced function, make sure the
2817 // types agree.
2818 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2819 = ForwardRefValIDs.find(NumberedVals.size());
2820 if (I != ForwardRefValIDs.end()) {
2821 Fn = cast<Function>(I->second.first);
2822 if (Fn->getType() != PFT)
2823 return Error(NameLoc, "type of definition and forward reference of '@" +
2824 utostr(NumberedVals.size()) +"' disagree");
2825 ForwardRefValIDs.erase(I);
2826 }
2827 }
2828
2829 if (Fn == 0)
2830 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2831 else // Move the forward-reference to the correct spot in the module.
2832 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2833
2834 if (FunctionName.empty())
2835 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002836
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2838 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2839 Fn->setCallingConv(CC);
2840 Fn->setAttributes(PAL);
2841 Fn->setAlignment(Alignment);
2842 Fn->setSection(Section);
2843 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002844
Chris Lattnerdf986172009-01-02 07:01:27 +00002845 // Add all of the arguments we parsed to the function.
2846 Function::arg_iterator ArgIt = Fn->arg_begin();
2847 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002848 // If we run out of arguments in the Function prototype, exit early.
2849 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2850 if (ArgIt == Fn->arg_end()) break;
2851
Chris Lattnerdf986172009-01-02 07:01:27 +00002852 // If the argument has a name, insert it into the argument symbol table.
2853 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002854
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 // Set the name, if it conflicted, it will be auto-renamed.
2856 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002857
Chris Lattnerdf986172009-01-02 07:01:27 +00002858 if (ArgIt->getNameStr() != ArgList[i].Name)
2859 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2860 ArgList[i].Name + "'");
2861 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002862
Chris Lattnerdf986172009-01-02 07:01:27 +00002863 return false;
2864}
2865
2866
2867/// ParseFunctionBody
2868/// ::= '{' BasicBlock+ '}'
2869/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2870///
2871bool LLParser::ParseFunctionBody(Function &Fn) {
2872 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2873 return TokError("expected '{' in function body");
2874 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002875
Chris Lattner09d9ef42009-10-28 03:39:23 +00002876 int FunctionNumber = -1;
2877 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2878
2879 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002880
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002881 // We need at least one basic block.
2882 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2883 return TokError("function body requires at least one basic block");
2884
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2886 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002887
Chris Lattnerdf986172009-01-02 07:01:27 +00002888 // Eat the }.
2889 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnerdf986172009-01-02 07:01:27 +00002891 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002892 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002893}
2894
2895/// ParseBasicBlock
2896/// ::= LabelStr? Instruction*
2897bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2898 // If this basic block starts out with a name, remember it.
2899 std::string Name;
2900 LocTy NameLoc = Lex.getLoc();
2901 if (Lex.getKind() == lltok::LabelStr) {
2902 Name = Lex.getStrVal();
2903 Lex.Lex();
2904 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905
Chris Lattnerdf986172009-01-02 07:01:27 +00002906 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2907 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002908
Chris Lattnerdf986172009-01-02 07:01:27 +00002909 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002910
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 // Parse the instructions in this block until we get a terminator.
2912 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002913 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 do {
2915 // This instruction may have three possibilities for a name: a) none
2916 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2917 LocTy NameLoc = Lex.getLoc();
2918 int NameID = -1;
2919 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002920
Chris Lattnerdf986172009-01-02 07:01:27 +00002921 if (Lex.getKind() == lltok::LocalVarID) {
2922 NameID = Lex.getUIntVal();
2923 Lex.Lex();
2924 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2925 return true;
2926 } else if (Lex.getKind() == lltok::LocalVar ||
2927 // FIXME: REMOVE IN LLVM 3.0
2928 Lex.getKind() == lltok::StringConstant) {
2929 NameStr = Lex.getStrVal();
2930 Lex.Lex();
2931 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2932 return true;
2933 }
Devang Patelf633a062009-09-17 23:04:48 +00002934
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002935 switch (ParseInstruction(Inst, BB, PFS)) {
2936 default: assert(0 && "Unknown ParseInstruction result!");
2937 case InstError: return true;
2938 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002939 BB->getInstList().push_back(Inst);
2940
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002941 // With a normal result, we check to see if the instruction is followed by
2942 // a comma and metadata.
2943 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002944 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002945 return true;
2946 break;
2947 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002948 BB->getInstList().push_back(Inst);
2949
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002950 // If the instruction parser ate an extra comma at the end of it, it
2951 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002952 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002953 return true;
2954 break;
2955 }
Devang Patelf633a062009-09-17 23:04:48 +00002956
Chris Lattnerdf986172009-01-02 07:01:27 +00002957 // Set the name on the instruction.
2958 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2959 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002960
Chris Lattnerdf986172009-01-02 07:01:27 +00002961 return false;
2962}
2963
2964//===----------------------------------------------------------------------===//
2965// Instruction Parsing.
2966//===----------------------------------------------------------------------===//
2967
2968/// ParseInstruction - Parse one of the many different instructions.
2969///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002970int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2971 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 lltok::Kind Token = Lex.getKind();
2973 if (Token == lltok::Eof)
2974 return TokError("found end of file when expecting more instructions");
2975 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002976 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002977 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002978
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 switch (Token) {
2980 default: return Error(Loc, "expected instruction opcode");
2981 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002982 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2983 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002984 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2985 case lltok::kw_br: return ParseBr(Inst, PFS);
2986 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002987 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2989 // Binary Operators.
2990 case lltok::kw_add:
2991 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002992 case lltok::kw_mul: {
2993 bool NUW = false;
2994 bool NSW = false;
2995 LocTy ModifierLoc = Lex.getLoc();
2996 if (EatIfPresent(lltok::kw_nuw))
2997 NUW = true;
2998 if (EatIfPresent(lltok::kw_nsw)) {
2999 NSW = true;
3000 if (EatIfPresent(lltok::kw_nuw))
3001 NUW = true;
3002 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003003 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003004 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003005 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003006 if (NUW)
3007 return Error(ModifierLoc, "nuw only applies to integer operations");
3008 if (NSW)
3009 return Error(ModifierLoc, "nsw only applies to integer operations");
3010 }
3011 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003012 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003013 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003014 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003015 }
3016 return Result;
3017 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003018 case lltok::kw_fadd:
3019 case lltok::kw_fsub:
3020 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3021
Dan Gohman59858cf2009-07-27 16:11:46 +00003022 case lltok::kw_sdiv: {
3023 bool Exact = false;
3024 if (EatIfPresent(lltok::kw_exact))
3025 Exact = true;
3026 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3027 if (!Result)
3028 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003029 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003030 return Result;
3031 }
3032
Chris Lattnerdf986172009-01-02 07:01:27 +00003033 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003035 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003036 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003037 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 case lltok::kw_shl:
3039 case lltok::kw_lshr:
3040 case lltok::kw_ashr:
3041 case lltok::kw_and:
3042 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003043 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003044 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003045 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 // Casts.
3047 case lltok::kw_trunc:
3048 case lltok::kw_zext:
3049 case lltok::kw_sext:
3050 case lltok::kw_fptrunc:
3051 case lltok::kw_fpext:
3052 case lltok::kw_bitcast:
3053 case lltok::kw_uitofp:
3054 case lltok::kw_sitofp:
3055 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003056 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003057 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003058 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003059 // Other.
3060 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003061 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3063 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3064 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3065 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3066 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3067 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3068 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003069 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3070 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003071 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3073 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3074 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003075 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003077 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003079 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003081 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3082 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3083 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3084 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3085 }
3086}
3087
3088/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3089bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003090 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 switch (Lex.getKind()) {
3092 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3093 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3094 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3095 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3096 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3097 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3098 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3099 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3100 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3101 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3102 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3103 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3104 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3105 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3106 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3107 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3108 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3109 }
3110 } else {
3111 switch (Lex.getKind()) {
3112 default: TokError("expected icmp predicate (e.g. 'eq')");
3113 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3114 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3115 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3116 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3117 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3118 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3119 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3120 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3121 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3122 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3123 }
3124 }
3125 Lex.Lex();
3126 return false;
3127}
3128
3129//===----------------------------------------------------------------------===//
3130// Terminator Instructions.
3131//===----------------------------------------------------------------------===//
3132
3133/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003134/// ::= 'ret' void (',' !dbg, !1)*
3135/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3136/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003137/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003138int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3139 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003140 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003141 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003142
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003143 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003144 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003145 return false;
3146 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003147
Chris Lattnerdf986172009-01-02 07:01:27 +00003148 Value *RV;
3149 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003150
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003151 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003152 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003153 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003154 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003155 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003156 } else {
3157 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003158 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3159 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003160 SmallVector<Value*, 8> RVs;
3161 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003162
Devang Patelf633a062009-09-17 23:04:48 +00003163 do {
Devang Patel0475c912009-09-29 00:01:14 +00003164 // If optional custom metadata, e.g. !dbg is seen then this is the
3165 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003166 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003167 break;
3168 if (ParseTypeAndValue(RV, PFS)) return true;
3169 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003170 } while (EatIfPresent(lltok::comma));
3171
3172 RV = UndefValue::get(PFS.getFunction().getReturnType());
3173 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003174 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3175 BB->getInstList().push_back(I);
3176 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003177 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 }
3179 }
Devang Patelf633a062009-09-17 23:04:48 +00003180
Owen Anderson1d0be152009-08-13 21:58:54 +00003181 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003182 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003183}
3184
3185
3186/// ParseBr
3187/// ::= 'br' TypeAndValue
3188/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3189bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3190 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003191 Value *Op0;
3192 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003193 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003194
Chris Lattnerdf986172009-01-02 07:01:27 +00003195 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3196 Inst = BranchInst::Create(BB);
3197 return false;
3198 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003199
Owen Anderson1d0be152009-08-13 21:58:54 +00003200 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003202
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003204 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003206 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003208
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003209 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 return false;
3211}
3212
3213/// ParseSwitch
3214/// Instruction
3215/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3216/// JumpTable
3217/// ::= (TypeAndValue ',' TypeAndValue)*
3218bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3219 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003220 Value *Cond;
3221 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003222 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3223 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003224 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3226 return true;
3227
Duncan Sands1df98592010-02-16 11:11:14 +00003228 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003230
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 // Parse the jump table pairs.
3232 SmallPtrSet<Value*, 32> SeenCases;
3233 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3234 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003235 Value *Constant;
3236 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3239 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003240 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003241 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003242
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 if (!SeenCases.insert(Constant))
3244 return Error(CondLoc, "duplicate case value in switch");
3245 if (!isa<ConstantInt>(Constant))
3246 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003247
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003248 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003249 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003250
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003252
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003253 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3255 SI->addCase(Table[i].first, Table[i].second);
3256 Inst = SI;
3257 return false;
3258}
3259
Chris Lattnerab21db72009-10-28 00:19:10 +00003260/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003261/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003262/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3263bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003264 LocTy AddrLoc;
3265 Value *Address;
3266 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003267 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3268 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003269 return true;
3270
Duncan Sands1df98592010-02-16 11:11:14 +00003271 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003272 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003273
3274 // Parse the destination list.
3275 SmallVector<BasicBlock*, 16> DestList;
3276
3277 if (Lex.getKind() != lltok::rsquare) {
3278 BasicBlock *DestBB;
3279 if (ParseTypeAndBasicBlock(DestBB, PFS))
3280 return true;
3281 DestList.push_back(DestBB);
3282
3283 while (EatIfPresent(lltok::comma)) {
3284 if (ParseTypeAndBasicBlock(DestBB, PFS))
3285 return true;
3286 DestList.push_back(DestBB);
3287 }
3288 }
3289
3290 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3291 return true;
3292
Chris Lattnerab21db72009-10-28 00:19:10 +00003293 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003294 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3295 IBI->addDestination(DestList[i]);
3296 Inst = IBI;
3297 return false;
3298}
3299
3300
Chris Lattnerdf986172009-01-02 07:01:27 +00003301/// ParseInvoke
3302/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3303/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3304bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3305 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003306 unsigned RetAttrs, FnAttrs;
3307 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003308 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003309 LocTy RetTypeLoc;
3310 ValID CalleeID;
3311 SmallVector<ParamInfo, 16> ArgList;
3312
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003313 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003314 if (ParseOptionalCallingConv(CC) ||
3315 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003316 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003317 ParseValID(CalleeID) ||
3318 ParseParameterList(ArgList, PFS) ||
3319 ParseOptionalAttrs(FnAttrs, 2) ||
3320 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003321 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003323 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003324 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003325
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 // If RetType is a non-function pointer type, then this is the short syntax
3327 // for the call, which means that RetType is just the return type. Infer the
3328 // rest of the function argument types from the arguments that are present.
3329 const PointerType *PFTy = 0;
3330 const FunctionType *Ty = 0;
3331 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3332 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3333 // Pull out the types of all of the arguments...
3334 std::vector<const Type*> ParamTypes;
3335 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3336 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003337
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 if (!FunctionType::isValidReturnType(RetType))
3339 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003340
Owen Andersondebcb012009-07-29 22:17:13 +00003341 Ty = FunctionType::get(RetType, ParamTypes, false);
3342 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003344
Chris Lattnerdf986172009-01-02 07:01:27 +00003345 // Look up the callee.
3346 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003347 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003348
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3350 // function attributes.
3351 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3352 if (FnAttrs & ObsoleteFuncAttrs) {
3353 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3354 FnAttrs &= ~ObsoleteFuncAttrs;
3355 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003356
Chris Lattnerdf986172009-01-02 07:01:27 +00003357 // Set up the Attributes for the function.
3358 SmallVector<AttributeWithIndex, 8> Attrs;
3359 if (RetAttrs != Attribute::None)
3360 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003361
Chris Lattnerdf986172009-01-02 07:01:27 +00003362 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003363
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 // Loop through FunctionType's arguments and ensure they are specified
3365 // correctly. Also, gather any parameter attributes.
3366 FunctionType::param_iterator I = Ty->param_begin();
3367 FunctionType::param_iterator E = Ty->param_end();
3368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3369 const Type *ExpectedTy = 0;
3370 if (I != E) {
3371 ExpectedTy = *I++;
3372 } else if (!Ty->isVarArg()) {
3373 return Error(ArgList[i].Loc, "too many arguments specified");
3374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003375
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3377 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3378 ExpectedTy->getDescription() + "'");
3379 Args.push_back(ArgList[i].V);
3380 if (ArgList[i].Attrs != Attribute::None)
3381 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3382 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003383
Chris Lattnerdf986172009-01-02 07:01:27 +00003384 if (I != E)
3385 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003386
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 if (FnAttrs != Attribute::None)
3388 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 // Finish off the Attributes and check them
3391 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003392
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003393 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003394 Args.begin(), Args.end());
3395 II->setCallingConv(CC);
3396 II->setAttributes(PAL);
3397 Inst = II;
3398 return false;
3399}
3400
3401
3402
3403//===----------------------------------------------------------------------===//
3404// Binary Operators.
3405//===----------------------------------------------------------------------===//
3406
3407/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003408/// ::= ArithmeticOps TypeAndValue ',' Value
3409///
3410/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3411/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003412bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003413 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 LocTy Loc; Value *LHS, *RHS;
3415 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3416 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3417 ParseValue(LHS->getType(), RHS, PFS))
3418 return true;
3419
Chris Lattnere914b592009-01-05 08:24:46 +00003420 bool Valid;
3421 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003422 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003423 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003424 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3425 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003426 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003427 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3428 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003429 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003430
Chris Lattnere914b592009-01-05 08:24:46 +00003431 if (!Valid)
3432 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003433
Chris Lattnerdf986172009-01-02 07:01:27 +00003434 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3435 return false;
3436}
3437
3438/// ParseLogical
3439/// ::= ArithmeticOps TypeAndValue ',' Value {
3440bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3441 unsigned Opc) {
3442 LocTy Loc; Value *LHS, *RHS;
3443 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3444 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3445 ParseValue(LHS->getType(), RHS, PFS))
3446 return true;
3447
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003448 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003449 return Error(Loc,"instruction requires integer or integer vector operands");
3450
3451 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3452 return false;
3453}
3454
3455
3456/// ParseCompare
3457/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3458/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003459bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3460 unsigned Opc) {
3461 // Parse the integer/fp comparison predicate.
3462 LocTy Loc;
3463 unsigned Pred;
3464 Value *LHS, *RHS;
3465 if (ParseCmpPredicate(Pred, Opc) ||
3466 ParseTypeAndValue(LHS, Loc, PFS) ||
3467 ParseToken(lltok::comma, "expected ',' after compare value") ||
3468 ParseValue(LHS->getType(), RHS, PFS))
3469 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003470
Chris Lattnerdf986172009-01-02 07:01:27 +00003471 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003472 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003475 } else {
3476 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003477 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003478 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003479 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003480 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 }
3482 return false;
3483}
3484
3485//===----------------------------------------------------------------------===//
3486// Other Instructions.
3487//===----------------------------------------------------------------------===//
3488
3489
3490/// ParseCast
3491/// ::= CastOpc TypeAndValue 'to' Type
3492bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3493 unsigned Opc) {
3494 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003495 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003496 if (ParseTypeAndValue(Op, Loc, PFS) ||
3497 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3498 ParseType(DestTy))
3499 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003500
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003501 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3502 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 return Error(Loc, "invalid cast opcode for cast from '" +
3504 Op->getType()->getDescription() + "' to '" +
3505 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003506 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003507 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3508 return false;
3509}
3510
3511/// ParseSelect
3512/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3513bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3514 LocTy Loc;
3515 Value *Op0, *Op1, *Op2;
3516 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3517 ParseToken(lltok::comma, "expected ',' after select condition") ||
3518 ParseTypeAndValue(Op1, PFS) ||
3519 ParseToken(lltok::comma, "expected ',' after select value") ||
3520 ParseTypeAndValue(Op2, PFS))
3521 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003522
Chris Lattnerdf986172009-01-02 07:01:27 +00003523 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3524 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003525
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 Inst = SelectInst::Create(Op0, Op1, Op2);
3527 return false;
3528}
3529
Chris Lattner0088a5c2009-01-05 08:18:44 +00003530/// ParseVA_Arg
3531/// ::= 'va_arg' TypeAndValue ',' Type
3532bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003533 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003534 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003535 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003536 if (ParseTypeAndValue(Op, PFS) ||
3537 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003538 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003539 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003540
Chris Lattner0088a5c2009-01-05 08:18:44 +00003541 if (!EltTy->isFirstClassType())
3542 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003543
3544 Inst = new VAArgInst(Op, EltTy);
3545 return false;
3546}
3547
3548/// ParseExtractElement
3549/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3550bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3551 LocTy Loc;
3552 Value *Op0, *Op1;
3553 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3554 ParseToken(lltok::comma, "expected ',' after extract value") ||
3555 ParseTypeAndValue(Op1, PFS))
3556 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003557
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3559 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003560
Eric Christophera3500da2009-07-25 02:28:41 +00003561 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003562 return false;
3563}
3564
3565/// ParseInsertElement
3566/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3567bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3568 LocTy Loc;
3569 Value *Op0, *Op1, *Op2;
3570 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3571 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3572 ParseTypeAndValue(Op1, PFS) ||
3573 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3574 ParseTypeAndValue(Op2, PFS))
3575 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003576
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003578 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3581 return false;
3582}
3583
3584/// ParseShuffleVector
3585/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3586bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3587 LocTy Loc;
3588 Value *Op0, *Op1, *Op2;
3589 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3590 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3591 ParseTypeAndValue(Op1, PFS) ||
3592 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3593 ParseTypeAndValue(Op2, PFS))
3594 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003595
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3597 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003598
Chris Lattnerdf986172009-01-02 07:01:27 +00003599 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3600 return false;
3601}
3602
3603/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003604/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003605int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003606 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 Value *Op0, *Op1;
3608 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 if (ParseType(Ty) ||
3611 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3612 ParseValue(Ty, Op0, PFS) ||
3613 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003614 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3616 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003617
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003618 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3620 while (1) {
3621 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003622
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003623 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003624 break;
3625
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003626 if (Lex.getKind() == lltok::MetadataVar) {
3627 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003628 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003629 }
Devang Patela43d46f2009-10-16 18:45:49 +00003630
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003631 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003632 ParseValue(Ty, Op0, PFS) ||
3633 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003634 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3636 return true;
3637 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003638
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 if (!Ty->isFirstClassType())
3640 return Error(TypeLoc, "phi node must have first class type");
3641
3642 PHINode *PN = PHINode::Create(Ty);
3643 PN->reserveOperandSpace(PHIVals.size());
3644 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3645 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3646 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003647 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003648}
3649
3650/// ParseCall
3651/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3652/// ParameterList OptionalAttrs
3653bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3654 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003655 unsigned RetAttrs, FnAttrs;
3656 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003657 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003658 LocTy RetTypeLoc;
3659 ValID CalleeID;
3660 SmallVector<ParamInfo, 16> ArgList;
3661 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003662
Chris Lattnerdf986172009-01-02 07:01:27 +00003663 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3664 ParseOptionalCallingConv(CC) ||
3665 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003666 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 ParseValID(CalleeID) ||
3668 ParseParameterList(ArgList, PFS) ||
3669 ParseOptionalAttrs(FnAttrs, 2))
3670 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003671
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 // If RetType is a non-function pointer type, then this is the short syntax
3673 // for the call, which means that RetType is just the return type. Infer the
3674 // rest of the function argument types from the arguments that are present.
3675 const PointerType *PFTy = 0;
3676 const FunctionType *Ty = 0;
3677 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3678 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3679 // Pull out the types of all of the arguments...
3680 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003681 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3682 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003683
Chris Lattnerdf986172009-01-02 07:01:27 +00003684 if (!FunctionType::isValidReturnType(RetType))
3685 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003686
Owen Andersondebcb012009-07-29 22:17:13 +00003687 Ty = FunctionType::get(RetType, ParamTypes, false);
3688 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003689 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003690
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 // Look up the callee.
3692 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003693 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003694
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3696 // function attributes.
3697 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3698 if (FnAttrs & ObsoleteFuncAttrs) {
3699 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3700 FnAttrs &= ~ObsoleteFuncAttrs;
3701 }
3702
3703 // Set up the Attributes for the function.
3704 SmallVector<AttributeWithIndex, 8> Attrs;
3705 if (RetAttrs != Attribute::None)
3706 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003707
Chris Lattnerdf986172009-01-02 07:01:27 +00003708 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003709
Chris Lattnerdf986172009-01-02 07:01:27 +00003710 // Loop through FunctionType's arguments and ensure they are specified
3711 // correctly. Also, gather any parameter attributes.
3712 FunctionType::param_iterator I = Ty->param_begin();
3713 FunctionType::param_iterator E = Ty->param_end();
3714 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3715 const Type *ExpectedTy = 0;
3716 if (I != E) {
3717 ExpectedTy = *I++;
3718 } else if (!Ty->isVarArg()) {
3719 return Error(ArgList[i].Loc, "too many arguments specified");
3720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003721
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3723 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3724 ExpectedTy->getDescription() + "'");
3725 Args.push_back(ArgList[i].V);
3726 if (ArgList[i].Attrs != Attribute::None)
3727 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3728 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003729
Chris Lattnerdf986172009-01-02 07:01:27 +00003730 if (I != E)
3731 return Error(CallLoc, "not enough parameters specified for call");
3732
3733 if (FnAttrs != Attribute::None)
3734 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3735
3736 // Finish off the Attributes and check them
3737 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003738
Chris Lattnerdf986172009-01-02 07:01:27 +00003739 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3740 CI->setTailCall(isTail);
3741 CI->setCallingConv(CC);
3742 CI->setAttributes(PAL);
3743 Inst = CI;
3744 return false;
3745}
3746
3747//===----------------------------------------------------------------------===//
3748// Memory Instructions.
3749//===----------------------------------------------------------------------===//
3750
3751/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003752/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3753/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003754int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3755 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003756 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003757 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003758 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003759 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003760 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003761
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003762 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003763 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003764 if (Lex.getKind() == lltok::kw_align) {
3765 if (ParseOptionalAlignment(Alignment)) return true;
3766 } else if (Lex.getKind() == lltok::MetadataVar) {
3767 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003768 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003769 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3770 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3771 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 }
3773 }
3774
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003775 if (Size && !Size->getType()->isIntegerTy())
3776 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003777
Victor Hernandez68afa542009-10-21 19:11:40 +00003778 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003779 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003780 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003781 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003782
3783 // Autoupgrade old malloc instruction to malloc call.
3784 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003785 if (Size && !Size->getType()->isIntegerTy(32))
3786 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003787 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003788 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3789 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003790 if (!MallocF)
3791 // Prototype malloc as "void *(int32)".
3792 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003793 MallocF = cast<Function>(
3794 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003795 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003796return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003797}
3798
3799/// ParseFree
3800/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003801bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3802 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003803 Value *Val; LocTy Loc;
3804 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003805 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003806 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003807 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003808 return false;
3809}
3810
3811/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003812/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003813int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3814 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003815 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003816 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003817 bool AteExtraComma = false;
3818 if (ParseTypeAndValue(Val, Loc, PFS) ||
3819 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3820 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003821
Duncan Sands1df98592010-02-16 11:11:14 +00003822 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003823 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3824 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003825
Chris Lattnerdf986172009-01-02 07:01:27 +00003826 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003827 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003828}
3829
3830/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003831/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003832int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3833 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003834 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003835 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003836 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003837 if (ParseTypeAndValue(Val, Loc, PFS) ||
3838 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003839 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3840 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003841 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003842
Duncan Sands1df98592010-02-16 11:11:14 +00003843 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003844 return Error(PtrLoc, "store operand must be a pointer");
3845 if (!Val->getType()->isFirstClassType())
3846 return Error(Loc, "store operand must be a first class value");
3847 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3848 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003849
Chris Lattnerdf986172009-01-02 07:01:27 +00003850 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003851 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003852}
3853
3854/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003855/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003856/// FIXME: Remove support for getresult in LLVM 3.0
3857bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3858 Value *Val; LocTy ValLoc, EltLoc;
3859 unsigned Element;
3860 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3861 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003862 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003863 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003864
Duncan Sands1df98592010-02-16 11:11:14 +00003865 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003866 return Error(ValLoc, "getresult inst requires an aggregate operand");
3867 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3868 return Error(EltLoc, "invalid getresult index for value");
3869 Inst = ExtractValueInst::Create(Val, Element);
3870 return false;
3871}
3872
3873/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003874/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003875int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003876 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003877
Dan Gohmandcb40a32009-07-29 15:58:36 +00003878 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003879
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003880 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003881
Duncan Sands1df98592010-02-16 11:11:14 +00003882 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003883 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003884
Chris Lattnerdf986172009-01-02 07:01:27 +00003885 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003886 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003887 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003888 if (Lex.getKind() == lltok::MetadataVar) {
3889 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003890 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003891 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003892 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003893 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003894 return Error(EltLoc, "getelementptr index must be an integer");
3895 Indices.push_back(Val);
3896 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003897
Chris Lattnerdf986172009-01-02 07:01:27 +00003898 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3899 Indices.begin(), Indices.end()))
3900 return Error(Loc, "invalid getelementptr indices");
3901 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003902 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003903 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003904 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003905}
3906
3907/// ParseExtractValue
3908/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003909int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003910 Value *Val; LocTy Loc;
3911 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003912 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003913 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003914 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003915 return true;
3916
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003917 if (!Val->getType()->isAggregateType())
3918 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003919
3920 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3921 Indices.end()))
3922 return Error(Loc, "invalid indices for extractvalue");
3923 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003924 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003925}
3926
3927/// ParseInsertValue
3928/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003929int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003930 Value *Val0, *Val1; LocTy Loc0, Loc1;
3931 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003932 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003933 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3934 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3935 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003936 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003937 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003938
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003939 if (!Val0->getType()->isAggregateType())
3940 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003941
Chris Lattnerdf986172009-01-02 07:01:27 +00003942 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3943 Indices.end()))
3944 return Error(Loc0, "invalid indices for insertvalue");
3945 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003946 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003947}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003948
3949//===----------------------------------------------------------------------===//
3950// Embedded metadata.
3951//===----------------------------------------------------------------------===//
3952
3953/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003954/// ::= Element (',' Element)*
3955/// Element
3956/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003957bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003958 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003959 // Check for an empty list.
3960 if (Lex.getKind() == lltok::rbrace)
3961 return false;
3962
Nick Lewycky21cc4462009-04-04 07:22:01 +00003963 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003964 // Null is a special case since it is typeless.
3965 if (EatIfPresent(lltok::kw_null)) {
3966 Elts.push_back(0);
3967 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003968 }
Chris Lattnera7352392009-12-30 04:42:57 +00003969
3970 Value *V = 0;
3971 PATypeHolder Ty(Type::getVoidTy(Context));
3972 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003973 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003974 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003975 return true;
3976
Nick Lewyckycb337992009-05-10 20:57:05 +00003977 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003978 } while (EatIfPresent(lltok::comma));
3979
3980 return false;
3981}