blob: aa887d21777973b4c9840bb748390c06fa799131 [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 Wendling3d10a5a2009-07-20 01:03:30 +0000199 case lltok::kw_private : // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_internal: // OptionalLinkage
202 case lltok::kw_weak: // OptionalLinkage
203 case lltok::kw_weak_odr: // OptionalLinkage
204 case lltok::kw_linkonce: // OptionalLinkage
205 case lltok::kw_linkonce_odr: // OptionalLinkage
206 case lltok::kw_appending: // OptionalLinkage
207 case lltok::kw_dllexport: // OptionalLinkage
208 case lltok::kw_common: // OptionalLinkage
209 case lltok::kw_dllimport: // OptionalLinkage
210 case lltok::kw_extern_weak: // OptionalLinkage
211 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 unsigned Linkage, Visibility;
213 if (ParseOptionalLinkage(Linkage) ||
214 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000215 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 return true;
217 break;
218 }
219 case lltok::kw_default: // OptionalVisibility
220 case lltok::kw_hidden: // OptionalVisibility
221 case lltok::kw_protected: { // OptionalVisibility
222 unsigned Visibility;
223 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000224 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000225 return true;
226 break;
227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000228
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000233 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000234 break;
235 }
236 }
237}
238
239
240/// toplevelentity
241/// ::= 'module' 'asm' STRINGCONSTANT
242bool LLParser::ParseModuleAsm() {
243 assert(Lex.getKind() == lltok::kw_module);
244 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000245
246 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
248 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000249
Chris Lattnerdf986172009-01-02 07:01:27 +0000250 const std::string &AsmSoFar = M->getModuleInlineAsm();
251 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000252 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000253 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return false;
256}
257
258/// toplevelentity
259/// ::= 'target' 'triple' '=' STRINGCONSTANT
260/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
261bool LLParser::ParseTargetDefinition() {
262 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000263 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000264 switch (Lex.Lex()) {
265 default: return TokError("unknown target property");
266 case lltok::kw_triple:
267 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000268 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
269 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000270 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000271 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 return false;
273 case lltok::kw_datalayout:
274 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000275 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
276 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000277 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000278 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 return false;
280 }
281}
282
283/// toplevelentity
284/// ::= 'deplibs' '=' '[' ']'
285/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
286bool LLParser::ParseDepLibs() {
287 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000288 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000289 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
290 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
291 return true;
292
293 if (EatIfPresent(lltok::rsquare))
294 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000296 std::string Str;
297 if (ParseStringConstant(Str)) return true;
298 M->addLibrary(Str);
299
300 while (EatIfPresent(lltok::comma)) {
301 if (ParseStringConstant(Str)) return true;
302 M->addLibrary(Str);
303 }
304
305 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000306}
307
Dan Gohman3845e502009-08-12 23:32:33 +0000308/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000309/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000310/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000311bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000312 unsigned TypeID = NumberedTypes.size();
313
314 // Handle the LocalVarID form.
315 if (Lex.getKind() == lltok::LocalVarID) {
316 if (Lex.getUIntVal() != TypeID)
317 return Error(Lex.getLoc(), "type expected to be numbered '%" +
318 utostr(TypeID) + "'");
319 Lex.Lex(); // eat LocalVarID;
320
321 if (ParseToken(lltok::equal, "expected '=' after name"))
322 return true;
323 }
324
Chris Lattnerdf986172009-01-02 07:01:27 +0000325 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000326 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000327
Owen Anderson1d0be152009-08-13 21:58:54 +0000328 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000329 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000330
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 // See if this type was previously referenced.
332 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
333 FI = ForwardRefTypeIDs.find(TypeID);
334 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000335 if (FI->second.first.get() == Ty)
336 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000337
Chris Lattnerdf986172009-01-02 07:01:27 +0000338 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
339 Ty = FI->second.first.get();
340 ForwardRefTypeIDs.erase(FI);
341 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342
Chris Lattnerdf986172009-01-02 07:01:27 +0000343 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344
Chris Lattnerdf986172009-01-02 07:01:27 +0000345 return false;
346}
347
348/// toplevelentity
349/// ::= LocalVar '=' 'type' type
350bool LLParser::ParseNamedType() {
351 std::string Name = Lex.getStrVal();
352 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000353 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Owen Anderson1d0be152009-08-13 21:58:54 +0000355 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000356
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000357 if (ParseToken(lltok::equal, "expected '=' after name") ||
358 ParseToken(lltok::kw_type, "expected 'type' after name") ||
359 ParseType(Ty))
360 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000361
Chris Lattnerdf986172009-01-02 07:01:27 +0000362 // Set the type name, checking for conflicts as we do so.
363 bool AlreadyExists = M->addTypeName(Name, Ty);
364 if (!AlreadyExists) return false;
365
366 // See if this type is a forward reference. We need to eagerly resolve
367 // types to allow recursive type redefinitions below.
368 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
369 FI = ForwardRefTypes.find(Name);
370 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000371 if (FI->second.first.get() == Ty)
372 return Error(NameLoc, "self referential type is invalid");
373
Chris Lattnerdf986172009-01-02 07:01:27 +0000374 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
375 Ty = FI->second.first.get();
376 ForwardRefTypes.erase(FI);
377 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000378
Chris Lattnerdf986172009-01-02 07:01:27 +0000379 // Inserting a name that is already defined, get the existing name.
380 const Type *Existing = M->getTypeByName(Name);
381 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Chris Lattnerdf986172009-01-02 07:01:27 +0000383 // Otherwise, this is an attempt to redefine a type. That's okay if
384 // the redefinition is identical to the original.
385 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
386 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000387
Chris Lattnerdf986172009-01-02 07:01:27 +0000388 // Any other kind of (non-equivalent) redefinition is an error.
389 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
390 Ty->getDescription() + "'");
391}
392
393
394/// toplevelentity
395/// ::= 'declare' FunctionHeader
396bool LLParser::ParseDeclare() {
397 assert(Lex.getKind() == lltok::kw_declare);
398 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000399
Chris Lattnerdf986172009-01-02 07:01:27 +0000400 Function *F;
401 return ParseFunctionHeader(F, false);
402}
403
404/// toplevelentity
405/// ::= 'define' FunctionHeader '{' ...
406bool LLParser::ParseDefine() {
407 assert(Lex.getKind() == lltok::kw_define);
408 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000409
Chris Lattnerdf986172009-01-02 07:01:27 +0000410 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000411 return ParseFunctionHeader(F, true) ||
412 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000413}
414
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000415/// ParseGlobalType
416/// ::= 'constant'
417/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000418bool LLParser::ParseGlobalType(bool &IsConstant) {
419 if (Lex.getKind() == lltok::kw_constant)
420 IsConstant = true;
421 else if (Lex.getKind() == lltok::kw_global)
422 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000423 else {
424 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000425 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000426 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000427 Lex.Lex();
428 return false;
429}
430
Dan Gohman3845e502009-08-12 23:32:33 +0000431/// ParseUnnamedGlobal:
432/// OptionalVisibility ALIAS ...
433/// OptionalLinkage OptionalVisibility ... -> global variable
434/// GlobalID '=' OptionalVisibility ALIAS ...
435/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
436bool LLParser::ParseUnnamedGlobal() {
437 unsigned VarID = NumberedVals.size();
438 std::string Name;
439 LocTy NameLoc = Lex.getLoc();
440
441 // Handle the GlobalID form.
442 if (Lex.getKind() == lltok::GlobalID) {
443 if (Lex.getUIntVal() != VarID)
444 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
445 utostr(VarID) + "'");
446 Lex.Lex(); // eat GlobalID;
447
448 if (ParseToken(lltok::equal, "expected '=' after name"))
449 return true;
450 }
451
452 bool HasLinkage;
453 unsigned Linkage, Visibility;
454 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
455 ParseOptionalVisibility(Visibility))
456 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Dan Gohman3845e502009-08-12 23:32:33 +0000458 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
459 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
460 return ParseAlias(Name, NameLoc, Visibility);
461}
462
Chris Lattnerdf986172009-01-02 07:01:27 +0000463/// ParseNamedGlobal:
464/// GlobalVar '=' OptionalVisibility ALIAS ...
465/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
466bool LLParser::ParseNamedGlobal() {
467 assert(Lex.getKind() == lltok::GlobalVar);
468 LocTy NameLoc = Lex.getLoc();
469 std::string Name = Lex.getStrVal();
470 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000471
Chris Lattnerdf986172009-01-02 07:01:27 +0000472 bool HasLinkage;
473 unsigned Linkage, Visibility;
474 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
475 ParseOptionalLinkage(Linkage, HasLinkage) ||
476 ParseOptionalVisibility(Visibility))
477 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000478
Chris Lattnerdf986172009-01-02 07:01:27 +0000479 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
480 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
481 return ParseAlias(Name, NameLoc, Visibility);
482}
483
Devang Patel256be962009-07-20 19:00:08 +0000484// MDString:
485// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000486bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000487 std::string Str;
488 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000489 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000490 return false;
491}
492
493// MDNode:
494// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000495//
496/// This version of ParseMDNodeID returns the slot number and null in the case
497/// of a forward reference.
498bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
499 // !{ ..., !42, ... }
500 if (ParseUInt32(SlotNo)) return true;
501
502 // Check existing MDNode.
503 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
504 Result = NumberedMetadata[SlotNo];
505 else
506 Result = 0;
507 return false;
508}
509
Chris Lattner4a72efc2009-12-30 04:15:23 +0000510bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000511 // !{ ..., !42, ... }
512 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000513 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000514
Chris Lattner449c3102010-04-01 05:14:45 +0000515 // If not a forward reference, just return it now.
516 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000517
Chris Lattner449c3102010-04-01 05:14:45 +0000518 // Otherwise, create MDNode forward reference.
Chris Lattner42991ee2009-12-29 22:01:50 +0000519
520 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000521 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000522 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000523 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000524 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000525
526 if (NumberedMetadata.size() <= MID)
527 NumberedMetadata.resize(MID+1);
528 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000529 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000530 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000531}
Devang Patel256be962009-07-20 19:00:08 +0000532
Chris Lattner84d03b12009-12-29 22:35:39 +0000533/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000534/// !foo = !{ !1, !2 }
535bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000536 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000537 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000538 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000539
Chris Lattner84d03b12009-12-29 22:35:39 +0000540 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000541 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000542 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000543 return true;
544
Devang Patel3e30c2a2010-01-05 20:41:31 +0000545 SmallVector<MDNode *, 8> Elts;
Devang Pateleff2ab62009-07-29 00:34:02 +0000546 do {
Devang Patel69d02e02010-01-05 21:47:32 +0000547 // Null is a special case since it is typeless.
548 if (EatIfPresent(lltok::kw_null)) {
549 Elts.push_back(0);
550 continue;
551 }
552
Chris Lattnere434d272009-12-30 04:56:59 +0000553 if (ParseToken(lltok::exclaim, "Expected '!' here"))
Chris Lattner42991ee2009-12-29 22:01:50 +0000554 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000555
Chris Lattner442ffa12009-12-29 21:53:55 +0000556 MDNode *N = 0;
Chris Lattner4a72efc2009-12-30 04:15:23 +0000557 if (ParseMDNodeID(N)) return true;
Devang Pateleff2ab62009-07-29 00:34:02 +0000558 Elts.push_back(N);
559 } while (EatIfPresent(lltok::comma));
560
561 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
562 return true;
563
Owen Anderson1d0be152009-08-13 21:58:54 +0000564 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000565 return false;
566}
567
Devang Patel923078c2009-07-01 19:21:12 +0000568/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000569/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000570bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000571 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000572 Lex.Lex();
573 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000574
575 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000576 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000577 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000578 if (ParseUInt32(MetadataID) ||
579 ParseToken(lltok::equal, "expected '=' here") ||
580 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000581 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000582 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000583 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000584 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000585 return true;
586
Owen Anderson647e3012009-07-31 21:35:40 +0000587 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000588
589 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000590 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000591 FI = ForwardRefMDNodes.find(MetadataID);
592 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000593 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000594 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000595
596 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
597 } else {
598 if (MetadataID >= NumberedMetadata.size())
599 NumberedMetadata.resize(MetadataID+1);
600
601 if (NumberedMetadata[MetadataID] != 0)
602 return TokError("Metadata id is already used");
603 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000604 }
605
Devang Patel923078c2009-07-01 19:21:12 +0000606 return false;
607}
608
Chris Lattnerdf986172009-01-02 07:01:27 +0000609/// ParseAlias:
610/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
611/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000612/// ::= TypeAndValue
613/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000614/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000615///
616/// Everything through visibility has already been parsed.
617///
618bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
619 unsigned Visibility) {
620 assert(Lex.getKind() == lltok::kw_alias);
621 Lex.Lex();
622 unsigned Linkage;
623 LocTy LinkageLoc = Lex.getLoc();
624 if (ParseOptionalLinkage(Linkage))
625 return true;
626
627 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000628 Linkage != GlobalValue::WeakAnyLinkage &&
629 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000630 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000631 Linkage != GlobalValue::PrivateLinkage &&
632 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000634
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 Constant *Aliasee;
636 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000637 if (Lex.getKind() != lltok::kw_bitcast &&
638 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000639 if (ParseGlobalTypeAndValue(Aliasee)) return true;
640 } else {
641 // The bitcast dest type is not present, it is implied by the dest type.
642 ValID ID;
643 if (ParseValID(ID)) return true;
644 if (ID.Kind != ValID::t_Constant)
645 return Error(AliaseeLoc, "invalid aliasee");
646 Aliasee = ID.ConstantVal;
647 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000648
Duncan Sands1df98592010-02-16 11:11:14 +0000649 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000650 return Error(AliaseeLoc, "alias must have pointer type");
651
652 // Okay, create the alias but do not insert it into the module yet.
653 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
654 (GlobalValue::LinkageTypes)Linkage, Name,
655 Aliasee);
656 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000657
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 // See if this value already exists in the symbol table. If so, it is either
659 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000660 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 // See if this was a redefinition. If so, there is no entry in
662 // ForwardRefVals.
663 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
664 I = ForwardRefVals.find(Name);
665 if (I == ForwardRefVals.end())
666 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
667
668 // Otherwise, this was a definition of forward ref. Verify that types
669 // agree.
670 if (Val->getType() != GA->getType())
671 return Error(NameLoc,
672 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000673
Chris Lattnerdf986172009-01-02 07:01:27 +0000674 // If they agree, just RAUW the old value with the alias and remove the
675 // forward ref info.
676 Val->replaceAllUsesWith(GA);
677 Val->eraseFromParent();
678 ForwardRefVals.erase(I);
679 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000680
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 // Insert into the module, we know its name won't collide now.
682 M->getAliasList().push_back(GA);
683 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 return false;
686}
687
688/// ParseGlobal
689/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
690/// OptionalAddrSpace GlobalType Type Const
691/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
692/// OptionalAddrSpace GlobalType Type Const
693///
694/// Everything through visibility has been parsed already.
695///
696bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
697 unsigned Linkage, bool HasLinkage,
698 unsigned Visibility) {
699 unsigned AddrSpace;
700 bool ThreadLocal, IsConstant;
701 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000702
Owen Anderson1d0be152009-08-13 21:58:54 +0000703 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000704 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
705 ParseOptionalAddrSpace(AddrSpace) ||
706 ParseGlobalType(IsConstant) ||
707 ParseType(Ty, TyLoc))
708 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000709
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 // If the linkage is specified and is external, then no initializer is
711 // present.
712 Constant *Init = 0;
713 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000714 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000715 Linkage != GlobalValue::ExternalLinkage)) {
716 if (ParseGlobalValue(Ty, Init))
717 return true;
718 }
719
Duncan Sands1df98592010-02-16 11:11:14 +0000720 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000721 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000722
Chris Lattnerdf986172009-01-02 07:01:27 +0000723 GlobalVariable *GV = 0;
724
725 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000726 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000727 if (GlobalValue *GVal = M->getNamedValue(Name)) {
728 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
729 return Error(NameLoc, "redefinition of global '@" + Name + "'");
730 GV = cast<GlobalVariable>(GVal);
731 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000732 } else {
733 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
734 I = ForwardRefValIDs.find(NumberedVals.size());
735 if (I != ForwardRefValIDs.end()) {
736 GV = cast<GlobalVariable>(I->second.first);
737 ForwardRefValIDs.erase(I);
738 }
739 }
740
741 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000742 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000743 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000744 } else {
745 if (GV->getType()->getElementType() != Ty)
746 return Error(TyLoc,
747 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000748
Chris Lattnerdf986172009-01-02 07:01:27 +0000749 // Move the forward-reference to the correct spot in the module.
750 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
751 }
752
753 if (Name.empty())
754 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000755
Chris Lattnerdf986172009-01-02 07:01:27 +0000756 // Set the parsed properties on the global.
757 if (Init)
758 GV->setInitializer(Init);
759 GV->setConstant(IsConstant);
760 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
761 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
762 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 // Parse attributes on the global.
765 while (Lex.getKind() == lltok::comma) {
766 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000767
Chris Lattnerdf986172009-01-02 07:01:27 +0000768 if (Lex.getKind() == lltok::kw_section) {
769 Lex.Lex();
770 GV->setSection(Lex.getStrVal());
771 if (ParseToken(lltok::StringConstant, "expected global section string"))
772 return true;
773 } else if (Lex.getKind() == lltok::kw_align) {
774 unsigned Alignment;
775 if (ParseOptionalAlignment(Alignment)) return true;
776 GV->setAlignment(Alignment);
777 } else {
778 TokError("unknown global variable property!");
779 }
780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattnerdf986172009-01-02 07:01:27 +0000782 return false;
783}
784
785
786//===----------------------------------------------------------------------===//
787// GlobalValue Reference/Resolution Routines.
788//===----------------------------------------------------------------------===//
789
790/// GetGlobalVal - Get a value with the specified name or ID, creating a
791/// forward reference record if needed. This can return null if the value
792/// exists but does not have the right type.
793GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
794 LocTy Loc) {
795 const PointerType *PTy = dyn_cast<PointerType>(Ty);
796 if (PTy == 0) {
797 Error(Loc, "global variable reference must have pointer type");
798 return 0;
799 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000800
Chris Lattnerdf986172009-01-02 07:01:27 +0000801 // Look this name up in the normal function symbol table.
802 GlobalValue *Val =
803 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000804
Chris Lattnerdf986172009-01-02 07:01:27 +0000805 // If this is a forward reference for the value, see if we already created a
806 // forward ref record.
807 if (Val == 0) {
808 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
809 I = ForwardRefVals.find(Name);
810 if (I != ForwardRefVals.end())
811 Val = I->second.first;
812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Chris Lattnerdf986172009-01-02 07:01:27 +0000814 // If we have the value in the symbol table or fwd-ref table, return it.
815 if (Val) {
816 if (Val->getType() == Ty) return Val;
817 Error(Loc, "'@" + Name + "' defined with type '" +
818 Val->getType()->getDescription() + "'");
819 return 0;
820 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000821
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 // Otherwise, create a new forward reference for this value and remember it.
823 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000824 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
825 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000826 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000827 Error(Loc, "function may not return opaque type");
828 return 0;
829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000831 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000832 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000833 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
834 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000835 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000836
Chris Lattnerdf986172009-01-02 07:01:27 +0000837 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
838 return FwdVal;
839}
840
841GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
842 const PointerType *PTy = dyn_cast<PointerType>(Ty);
843 if (PTy == 0) {
844 Error(Loc, "global variable reference must have pointer type");
845 return 0;
846 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000847
Chris Lattnerdf986172009-01-02 07:01:27 +0000848 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000849
Chris Lattnerdf986172009-01-02 07:01:27 +0000850 // If this is a forward reference for the value, see if we already created a
851 // forward ref record.
852 if (Val == 0) {
853 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
854 I = ForwardRefValIDs.find(ID);
855 if (I != ForwardRefValIDs.end())
856 Val = I->second.first;
857 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000858
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 // If we have the value in the symbol table or fwd-ref table, return it.
860 if (Val) {
861 if (Val->getType() == Ty) return Val;
862 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
863 Val->getType()->getDescription() + "'");
864 return 0;
865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000866
Chris Lattnerdf986172009-01-02 07:01:27 +0000867 // Otherwise, create a new forward reference for this value and remember it.
868 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000869 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
870 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000871 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000872 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000873 return 0;
874 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000875 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000876 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000877 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
878 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000879 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880
Chris Lattnerdf986172009-01-02 07:01:27 +0000881 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
882 return FwdVal;
883}
884
885
886//===----------------------------------------------------------------------===//
887// Helper Routines.
888//===----------------------------------------------------------------------===//
889
890/// ParseToken - If the current token has the specified kind, eat it and return
891/// success. Otherwise, emit the specified error and return failure.
892bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
893 if (Lex.getKind() != T)
894 return TokError(ErrMsg);
895 Lex.Lex();
896 return false;
897}
898
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000899/// ParseStringConstant
900/// ::= StringConstant
901bool LLParser::ParseStringConstant(std::string &Result) {
902 if (Lex.getKind() != lltok::StringConstant)
903 return TokError("expected string constant");
904 Result = Lex.getStrVal();
905 Lex.Lex();
906 return false;
907}
908
909/// ParseUInt32
910/// ::= uint32
911bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000912 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
913 return TokError("expected integer");
914 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
915 if (Val64 != unsigned(Val64))
916 return TokError("expected 32-bit integer (too large)");
917 Val = Val64;
918 Lex.Lex();
919 return false;
920}
921
922
923/// ParseOptionalAddrSpace
924/// := /*empty*/
925/// := 'addrspace' '(' uint32 ')'
926bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
927 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000928 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000929 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000930 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000931 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000933}
Chris Lattnerdf986172009-01-02 07:01:27 +0000934
935/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
936/// indicates what kind of attribute list this is: 0: function arg, 1: result,
937/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000938/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000939bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
940 Attrs = Attribute::None;
941 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000942
Chris Lattnerdf986172009-01-02 07:01:27 +0000943 while (1) {
944 switch (Lex.getKind()) {
945 case lltok::kw_sext:
946 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000947 // Treat these as signext/zeroext if they occur in the argument list after
948 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
949 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
950 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000951 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000952 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000953 if (Lex.getKind() == lltok::kw_sext)
954 Attrs |= Attribute::SExt;
955 else
956 Attrs |= Attribute::ZExt;
957 break;
958 }
959 // FALL THROUGH.
960 default: // End of attributes.
961 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
962 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000963
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000964 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000965 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000966
Chris Lattnerdf986172009-01-02 07:01:27 +0000967 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000968 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
969 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
970 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
971 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
972 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
973 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
974 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
975 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000976
Devang Patel578efa92009-06-05 21:57:13 +0000977 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
978 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
979 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
980 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
981 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000982 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000983 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
984 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
985 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
986 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
987 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
988 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000989 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000990
Charles Davis1e063d12010-02-12 00:31:15 +0000991 case lltok::kw_alignstack: {
992 unsigned Alignment;
993 if (ParseOptionalStackAlignment(Alignment))
994 return true;
995 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
996 continue;
997 }
998
Chris Lattnerdf986172009-01-02 07:01:27 +0000999 case lltok::kw_align: {
1000 unsigned Alignment;
1001 if (ParseOptionalAlignment(Alignment))
1002 return true;
1003 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1004 continue;
1005 }
Charles Davis1e063d12010-02-12 00:31:15 +00001006
Chris Lattnerdf986172009-01-02 07:01:27 +00001007 }
1008 Lex.Lex();
1009 }
1010}
1011
1012/// ParseOptionalLinkage
1013/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001014/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001015/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +00001016/// ::= 'internal'
1017/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001018/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001019/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001020/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001021/// ::= 'appending'
1022/// ::= 'dllexport'
1023/// ::= 'common'
1024/// ::= 'dllimport'
1025/// ::= 'extern_weak'
1026/// ::= 'external'
1027bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1028 HasLinkage = false;
1029 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001030 default: Res=GlobalValue::ExternalLinkage; return false;
1031 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1032 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1033 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1034 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1035 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1036 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1037 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001038 case lltok::kw_available_externally:
1039 Res = GlobalValue::AvailableExternallyLinkage;
1040 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001041 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1042 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1043 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1044 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1045 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1046 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001047 }
1048 Lex.Lex();
1049 HasLinkage = true;
1050 return false;
1051}
1052
1053/// ParseOptionalVisibility
1054/// ::= /*empty*/
1055/// ::= 'default'
1056/// ::= 'hidden'
1057/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001058///
Chris Lattnerdf986172009-01-02 07:01:27 +00001059bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1060 switch (Lex.getKind()) {
1061 default: Res = GlobalValue::DefaultVisibility; return false;
1062 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1063 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1064 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1065 }
1066 Lex.Lex();
1067 return false;
1068}
1069
1070/// ParseOptionalCallingConv
1071/// ::= /*empty*/
1072/// ::= 'ccc'
1073/// ::= 'fastcc'
1074/// ::= 'coldcc'
1075/// ::= 'x86_stdcallcc'
1076/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001077/// ::= 'arm_apcscc'
1078/// ::= 'arm_aapcscc'
1079/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001080/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001081/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001082///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001083bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001084 switch (Lex.getKind()) {
1085 default: CC = CallingConv::C; return false;
1086 case lltok::kw_ccc: CC = CallingConv::C; break;
1087 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1088 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1089 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1090 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001091 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1092 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1093 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001094 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001095 case lltok::kw_cc: {
1096 unsigned ArbitraryCC;
1097 Lex.Lex();
1098 if (ParseUInt32(ArbitraryCC)) {
1099 return true;
1100 } else
1101 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1102 return false;
1103 }
1104 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001105 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001106
Chris Lattnerdf986172009-01-02 07:01:27 +00001107 Lex.Lex();
1108 return false;
1109}
1110
Chris Lattnerb8c46862009-12-30 05:31:19 +00001111/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001112/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattnerfe805242010-04-01 04:51:13 +00001113bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001114 do {
1115 if (Lex.getKind() != lltok::MetadataVar)
1116 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001117
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001118 std::string Name = Lex.getStrVal();
1119 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001120
Chris Lattner442ffa12009-12-29 21:53:55 +00001121 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001122 unsigned NodeID;
1123 SMLoc Loc = Lex.getLoc();
Chris Lattnere434d272009-12-30 04:56:59 +00001124 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner449c3102010-04-01 05:14:45 +00001125 ParseMDNodeID(Node, NodeID))
Chris Lattnere434d272009-12-30 04:56:59 +00001126 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001127
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001128 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner449c3102010-04-01 05:14:45 +00001129 if (Node) {
1130 // If we got the node, add it to the instruction.
1131 Inst->setMetadata(MDK, Node);
1132 } else {
1133 MDRef R = { Loc, MDK, NodeID };
1134 // Otherwise, remember that this should be resolved later.
1135 ForwardRefInstMetadata[Inst].push_back(R);
1136 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001137
1138 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001139 } while (EatIfPresent(lltok::comma));
1140 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001141}
1142
Chris Lattnerdf986172009-01-02 07:01:27 +00001143/// ParseOptionalAlignment
1144/// ::= /* empty */
1145/// ::= 'align' 4
1146bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1147 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001148 if (!EatIfPresent(lltok::kw_align))
1149 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001150 LocTy AlignLoc = Lex.getLoc();
1151 if (ParseUInt32(Alignment)) return true;
1152 if (!isPowerOf2_32(Alignment))
1153 return Error(AlignLoc, "alignment is not a power of two");
1154 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001155}
1156
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001157/// ParseOptionalCommaAlign
1158/// ::=
1159/// ::= ',' align 4
1160///
1161/// This returns with AteExtraComma set to true if it ate an excess comma at the
1162/// end.
1163bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1164 bool &AteExtraComma) {
1165 AteExtraComma = false;
1166 while (EatIfPresent(lltok::comma)) {
1167 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001168 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001169 AteExtraComma = true;
1170 return false;
1171 }
1172
1173 if (Lex.getKind() == lltok::kw_align) {
Devang Patelf633a062009-09-17 23:04:48 +00001174 if (ParseOptionalAlignment(Alignment)) return true;
1175 } else
1176 return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001177 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001178
Devang Patelf633a062009-09-17 23:04:48 +00001179 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001180}
1181
Charles Davis1e063d12010-02-12 00:31:15 +00001182/// ParseOptionalStackAlignment
1183/// ::= /* empty */
1184/// ::= 'alignstack' '(' 4 ')'
1185bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1186 Alignment = 0;
1187 if (!EatIfPresent(lltok::kw_alignstack))
1188 return false;
1189 LocTy ParenLoc = Lex.getLoc();
1190 if (!EatIfPresent(lltok::lparen))
1191 return Error(ParenLoc, "expected '('");
1192 LocTy AlignLoc = Lex.getLoc();
1193 if (ParseUInt32(Alignment)) return true;
1194 ParenLoc = Lex.getLoc();
1195 if (!EatIfPresent(lltok::rparen))
1196 return Error(ParenLoc, "expected ')'");
1197 if (!isPowerOf2_32(Alignment))
1198 return Error(AlignLoc, "stack alignment is not a power of two");
1199 return false;
1200}
Devang Patelf633a062009-09-17 23:04:48 +00001201
Chris Lattner628c13a2009-12-30 05:14:00 +00001202/// ParseIndexList - This parses the index list for an insert/extractvalue
1203/// instruction. This sets AteExtraComma in the case where we eat an extra
1204/// comma at the end of the line and find that it is followed by metadata.
1205/// Clients that don't allow metadata can call the version of this function that
1206/// only takes one argument.
1207///
Chris Lattnerdf986172009-01-02 07:01:27 +00001208/// ParseIndexList
1209/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001210///
1211bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1212 bool &AteExtraComma) {
1213 AteExtraComma = false;
1214
Chris Lattnerdf986172009-01-02 07:01:27 +00001215 if (Lex.getKind() != lltok::comma)
1216 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001217
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001218 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001219 if (Lex.getKind() == lltok::MetadataVar) {
1220 AteExtraComma = true;
1221 return false;
1222 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001223 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001224 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 Indices.push_back(Idx);
1226 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001227
Chris Lattnerdf986172009-01-02 07:01:27 +00001228 return false;
1229}
1230
1231//===----------------------------------------------------------------------===//
1232// Type Parsing.
1233//===----------------------------------------------------------------------===//
1234
1235/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001236bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1237 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001239
Chris Lattnerdf986172009-01-02 07:01:27 +00001240 // Verify no unresolved uprefs.
1241 if (!UpRefs.empty())
1242 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001243
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001244 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001245 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 return false;
1248}
1249
1250/// HandleUpRefs - Every time we finish a new layer of types, this function is
1251/// called. It loops through the UpRefs vector, which is a list of the
1252/// currently active types. For each type, if the up-reference is contained in
1253/// the newly completed type, we decrement the level count. When the level
1254/// count reaches zero, the up-referenced type is the type that is passed in:
1255/// thus we can complete the cycle.
1256///
1257PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1258 // If Ty isn't abstract, or if there are no up-references in it, then there is
1259 // nothing to resolve here.
1260 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001261
Chris Lattnerdf986172009-01-02 07:01:27 +00001262 PATypeHolder Ty(ty);
1263#if 0
David Greene0e28d762009-12-23 23:38:28 +00001264 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 << "' newly formed. Resolving upreferences.\n"
1266 << UpRefs.size() << " upreferences active!\n";
1267#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001268
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1270 // to zero), we resolve them all together before we resolve them to Ty. At
1271 // the end of the loop, if there is anything to resolve to Ty, it will be in
1272 // this variable.
1273 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001274
Chris Lattnerdf986172009-01-02 07:01:27 +00001275 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1276 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1277 bool ContainsType =
1278 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1279 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001280
Chris Lattnerdf986172009-01-02 07:01:27 +00001281#if 0
David Greene0e28d762009-12-23 23:38:28 +00001282 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001283 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1284 << (ContainsType ? "true" : "false")
1285 << " level=" << UpRefs[i].NestingLevel << "\n";
1286#endif
1287 if (!ContainsType)
1288 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 // Decrement level of upreference
1291 unsigned Level = --UpRefs[i].NestingLevel;
1292 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1295 if (Level != 0)
1296 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001297
Chris Lattnerdf986172009-01-02 07:01:27 +00001298#if 0
David Greene0e28d762009-12-23 23:38:28 +00001299 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001300#endif
1301 if (!TypeToResolve)
1302 TypeToResolve = UpRefs[i].UpRefTy;
1303 else
1304 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1305 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1306 --i; // Do not skip the next element.
1307 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001308
Chris Lattnerdf986172009-01-02 07:01:27 +00001309 if (TypeToResolve)
1310 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 return Ty;
1313}
1314
1315
1316/// ParseTypeRec - The recursive function used to process the internal
1317/// implementation details of types.
1318bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1319 switch (Lex.getKind()) {
1320 default:
1321 return TokError("expected type");
1322 case lltok::Type:
1323 // TypeRec ::= 'float' | 'void' (etc)
1324 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001325 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 break;
1327 case lltok::kw_opaque:
1328 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001329 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 Lex.Lex();
1331 break;
1332 case lltok::lbrace:
1333 // TypeRec ::= '{' ... '}'
1334 if (ParseStructType(Result, false))
1335 return true;
1336 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001337 case lltok::kw_union:
1338 // TypeRec ::= 'union' '{' ... '}'
1339 if (ParseUnionType(Result))
1340 return true;
1341 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001342 case lltok::lsquare:
1343 // TypeRec ::= '[' ... ']'
1344 Lex.Lex(); // eat the lsquare.
1345 if (ParseArrayVectorType(Result, false))
1346 return true;
1347 break;
1348 case lltok::less: // Either vector or packed struct.
1349 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001350 Lex.Lex();
1351 if (Lex.getKind() == lltok::lbrace) {
1352 if (ParseStructType(Result, true) ||
1353 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 } else if (ParseArrayVectorType(Result, true))
1356 return true;
1357 break;
1358 case lltok::LocalVar:
1359 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1360 // TypeRec ::= %foo
1361 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1362 Result = T;
1363 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001364 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1366 std::make_pair(Result,
1367 Lex.getLoc())));
1368 M->addTypeName(Lex.getStrVal(), Result.get());
1369 }
1370 Lex.Lex();
1371 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001372
Chris Lattnerdf986172009-01-02 07:01:27 +00001373 case lltok::LocalVarID:
1374 // TypeRec ::= %4
1375 if (Lex.getUIntVal() < NumberedTypes.size())
1376 Result = NumberedTypes[Lex.getUIntVal()];
1377 else {
1378 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1379 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1380 if (I != ForwardRefTypeIDs.end())
1381 Result = I->second.first;
1382 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001383 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001384 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1385 std::make_pair(Result,
1386 Lex.getLoc())));
1387 }
1388 }
1389 Lex.Lex();
1390 break;
1391 case lltok::backslash: {
1392 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001393 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001394 unsigned Val;
1395 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001396 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001397 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1398 Result = OT;
1399 break;
1400 }
1401 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001402
1403 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001404 while (1) {
1405 switch (Lex.getKind()) {
1406 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001407 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001408
1409 // TypeRec ::= TypeRec '*'
1410 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001411 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001412 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001413 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001414 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001415 if (!PointerType::isValidElementType(Result.get()))
1416 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001417 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 Lex.Lex();
1419 break;
1420
1421 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1422 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001423 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001425 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001426 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001427 if (!PointerType::isValidElementType(Result.get()))
1428 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001429 unsigned AddrSpace;
1430 if (ParseOptionalAddrSpace(AddrSpace) ||
1431 ParseToken(lltok::star, "expected '*' in address space"))
1432 return true;
1433
Owen Andersondebcb012009-07-29 22:17:13 +00001434 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 break;
1436 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001437
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1439 case lltok::lparen:
1440 if (ParseFunctionType(Result))
1441 return true;
1442 break;
1443 }
1444 }
1445}
1446
1447/// ParseParameterList
1448/// ::= '(' ')'
1449/// ::= '(' Arg (',' Arg)* ')'
1450/// Arg
1451/// ::= Type OptionalAttributes Value OptionalAttributes
1452bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1453 PerFunctionState &PFS) {
1454 if (ParseToken(lltok::lparen, "expected '(' in call"))
1455 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001456
Chris Lattnerdf986172009-01-02 07:01:27 +00001457 while (Lex.getKind() != lltok::rparen) {
1458 // If this isn't the first argument, we need a comma.
1459 if (!ArgList.empty() &&
1460 ParseToken(lltok::comma, "expected ',' in argument list"))
1461 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001462
Chris Lattnerdf986172009-01-02 07:01:27 +00001463 // Parse the argument.
1464 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001465 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001466 unsigned ArgAttrs1 = Attribute::None;
1467 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001468 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001469 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001470 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001471
Chris Lattner287881d2009-12-30 02:11:14 +00001472 // Otherwise, handle normal operands.
1473 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1474 ParseValue(ArgTy, V, PFS) ||
1475 // FIXME: Should not allow attributes after the argument, remove this
1476 // in LLVM 3.0.
1477 ParseOptionalAttrs(ArgAttrs2, 3))
1478 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001479 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1480 }
1481
1482 Lex.Lex(); // Lex the ')'.
1483 return false;
1484}
1485
1486
1487
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001488/// ParseArgumentList - Parse the argument list for a function type or function
1489/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001490/// ::= '(' ArgTypeListI ')'
1491/// ArgTypeListI
1492/// ::= /*empty*/
1493/// ::= '...'
1494/// ::= ArgTypeList ',' '...'
1495/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001496///
Chris Lattnerdf986172009-01-02 07:01:27 +00001497bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001498 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 isVarArg = false;
1500 assert(Lex.getKind() == lltok::lparen);
1501 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001502
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 if (Lex.getKind() == lltok::rparen) {
1504 // empty
1505 } else if (Lex.getKind() == lltok::dotdotdot) {
1506 isVarArg = true;
1507 Lex.Lex();
1508 } else {
1509 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001510 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001511 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001512 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001513
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001514 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1515 // types (such as a function returning a pointer to itself). If parsing a
1516 // function prototype, we require fully resolved types.
1517 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001518 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001519
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001520 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001521 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 if (Lex.getKind() == lltok::LocalVar ||
1524 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1525 Name = Lex.getStrVal();
1526 Lex.Lex();
1527 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001528
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001529 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001530 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531
Chris Lattnerdf986172009-01-02 07:01:27 +00001532 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001534 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001536 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001537 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001538 break;
1539 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001540
Chris Lattnerdf986172009-01-02 07:01:27 +00001541 // Otherwise must be an argument type.
1542 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001543 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001544 ParseOptionalAttrs(Attrs, 0)) return true;
1545
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001546 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001547 return Error(TypeLoc, "argument can not have void type");
1548
Chris Lattnerdf986172009-01-02 07:01:27 +00001549 if (Lex.getKind() == lltok::LocalVar ||
1550 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1551 Name = Lex.getStrVal();
1552 Lex.Lex();
1553 } else {
1554 Name = "";
1555 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001556
Duncan Sands47c51882010-02-16 14:50:09 +00001557 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001558 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001559
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1561 }
1562 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001564 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001565}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001566
Chris Lattnerdf986172009-01-02 07:01:27 +00001567/// ParseFunctionType
1568/// ::= Type ArgumentList OptionalAttrs
1569bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1570 assert(Lex.getKind() == lltok::lparen);
1571
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001572 if (!FunctionType::isValidReturnType(Result))
1573 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001574
Chris Lattnerdf986172009-01-02 07:01:27 +00001575 std::vector<ArgInfo> ArgList;
1576 bool isVarArg;
1577 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001578 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001579 // FIXME: Allow, but ignore attributes on function types!
1580 // FIXME: Remove in LLVM 3.0
1581 ParseOptionalAttrs(Attrs, 2))
1582 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Chris Lattnerdf986172009-01-02 07:01:27 +00001584 // Reject names on the arguments lists.
1585 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1586 if (!ArgList[i].Name.empty())
1587 return Error(ArgList[i].Loc, "argument name invalid in function type");
1588 if (!ArgList[i].Attrs != 0) {
1589 // Allow but ignore attributes on function types; this permits
1590 // auto-upgrade.
1591 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1592 }
1593 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 std::vector<const Type*> ArgListTy;
1596 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1597 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001598
Owen Andersondebcb012009-07-29 22:17:13 +00001599 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001600 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 return false;
1602}
1603
1604/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1605/// TypeRec
1606/// ::= '{' '}'
1607/// ::= '{' TypeRec (',' TypeRec)* '}'
1608/// ::= '<' '{' '}' '>'
1609/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1610bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1611 assert(Lex.getKind() == lltok::lbrace);
1612 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001614 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001615 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 return false;
1617 }
1618
1619 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001620 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001621 if (ParseTypeRec(Result)) return true;
1622 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001623
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001624 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001625 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001626 if (!StructType::isValidElementType(Result))
1627 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001629 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001630 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001631 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001632
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001633 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001634 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001635 if (!StructType::isValidElementType(Result))
1636 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001637
Chris Lattnerdf986172009-01-02 07:01:27 +00001638 ParamsList.push_back(Result);
1639 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001640
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001641 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1642 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001643
Chris Lattnerdf986172009-01-02 07:01:27 +00001644 std::vector<const Type*> ParamsListTy;
1645 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1646 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001647 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 return false;
1649}
1650
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001651/// ParseUnionType
1652/// TypeRec
1653/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1654bool LLParser::ParseUnionType(PATypeHolder &Result) {
1655 assert(Lex.getKind() == lltok::kw_union);
1656 Lex.Lex(); // Consume the 'union'
1657
1658 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1659
1660 SmallVector<PATypeHolder, 8> ParamsList;
1661 do {
1662 LocTy EltTyLoc = Lex.getLoc();
1663 if (ParseTypeRec(Result)) return true;
1664 ParamsList.push_back(Result);
1665
1666 if (Result->isVoidTy())
1667 return Error(EltTyLoc, "union element can not have void type");
1668 if (!UnionType::isValidElementType(Result))
1669 return Error(EltTyLoc, "invalid element type for union");
1670
1671 } while (EatIfPresent(lltok::comma)) ;
1672
1673 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1674 return true;
1675
1676 SmallVector<const Type*, 8> ParamsListTy;
1677 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1678 ParamsListTy.push_back(ParamsList[i].get());
1679 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1680 return false;
1681}
1682
Chris Lattnerdf986172009-01-02 07:01:27 +00001683/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1684/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001686/// ::= '[' APSINTVAL 'x' Types ']'
1687/// ::= '<' APSINTVAL 'x' Types '>'
1688bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1689 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1690 Lex.getAPSIntVal().getBitWidth() > 64)
1691 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Chris Lattnerdf986172009-01-02 07:01:27 +00001693 LocTy SizeLoc = Lex.getLoc();
1694 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001695 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001697 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1698 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001699
1700 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001701 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001703
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001704 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001705 return Error(TypeLoc, "array and vector element type cannot be void");
1706
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001707 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1708 "expected end of sequential type"))
1709 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001710
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001712 if (Size == 0)
1713 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 if ((unsigned)Size != Size)
1715 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001716 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001718 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001719 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001720 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001722 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 }
1724 return false;
1725}
1726
1727//===----------------------------------------------------------------------===//
1728// Function Semantic Analysis.
1729//===----------------------------------------------------------------------===//
1730
Chris Lattner09d9ef42009-10-28 03:39:23 +00001731LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1732 int functionNumber)
1733 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001734
1735 // Insert unnamed arguments into the NumberedVals list.
1736 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1737 AI != E; ++AI)
1738 if (!AI->hasName())
1739 NumberedVals.push_back(AI);
1740}
1741
1742LLParser::PerFunctionState::~PerFunctionState() {
1743 // If there were any forward referenced non-basicblock values, delete them.
1744 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1745 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1746 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001747 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001748 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001749 delete I->second.first;
1750 I->second.first = 0;
1751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001752
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1754 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1755 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001756 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001757 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 delete I->second.first;
1759 I->second.first = 0;
1760 }
1761}
1762
Chris Lattner09d9ef42009-10-28 03:39:23 +00001763bool LLParser::PerFunctionState::FinishFunction() {
1764 // Check to see if someone took the address of labels in this block.
1765 if (!P.ForwardRefBlockAddresses.empty()) {
1766 ValID FunctionID;
1767 if (!F.getName().empty()) {
1768 FunctionID.Kind = ValID::t_GlobalName;
1769 FunctionID.StrVal = F.getName();
1770 } else {
1771 FunctionID.Kind = ValID::t_GlobalID;
1772 FunctionID.UIntVal = FunctionNumber;
1773 }
1774
1775 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1776 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1777 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1778 // Resolve all these references.
1779 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1780 return true;
1781
1782 P.ForwardRefBlockAddresses.erase(FRBAI);
1783 }
1784 }
1785
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 if (!ForwardRefVals.empty())
1787 return P.Error(ForwardRefVals.begin()->second.second,
1788 "use of undefined value '%" + ForwardRefVals.begin()->first +
1789 "'");
1790 if (!ForwardRefValIDs.empty())
1791 return P.Error(ForwardRefValIDs.begin()->second.second,
1792 "use of undefined value '%" +
1793 utostr(ForwardRefValIDs.begin()->first) + "'");
1794 return false;
1795}
1796
1797
1798/// GetVal - Get a value with the specified name or ID, creating a
1799/// forward reference record if needed. This can return null if the value
1800/// exists but does not have the right type.
1801Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1802 const Type *Ty, LocTy Loc) {
1803 // Look this name up in the normal function symbol table.
1804 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001805
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 // If this is a forward reference for the value, see if we already created a
1807 // forward ref record.
1808 if (Val == 0) {
1809 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1810 I = ForwardRefVals.find(Name);
1811 if (I != ForwardRefVals.end())
1812 Val = I->second.first;
1813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 // If we have the value in the symbol table or fwd-ref table, return it.
1816 if (Val) {
1817 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001818 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 P.Error(Loc, "'%" + Name + "' is not a basic block");
1820 else
1821 P.Error(Loc, "'%" + Name + "' defined with type '" +
1822 Val->getType()->getDescription() + "'");
1823 return 0;
1824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001827 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 P.Error(Loc, "invalid use of a non-first-class type");
1829 return 0;
1830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Chris Lattnerdf986172009-01-02 07:01:27 +00001832 // Otherwise, create a new forward reference for this value and remember it.
1833 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001834 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001835 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 else
1837 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001838
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1840 return FwdVal;
1841}
1842
1843Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1844 LocTy Loc) {
1845 // Look this name up in the normal function symbol table.
1846 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001847
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 // If this is a forward reference for the value, see if we already created a
1849 // forward ref record.
1850 if (Val == 0) {
1851 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1852 I = ForwardRefValIDs.find(ID);
1853 if (I != ForwardRefValIDs.end())
1854 Val = I->second.first;
1855 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 // If we have the value in the symbol table or fwd-ref table, return it.
1858 if (Val) {
1859 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001860 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1862 else
1863 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1864 Val->getType()->getDescription() + "'");
1865 return 0;
1866 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001867
Duncan Sands47c51882010-02-16 14:50:09 +00001868 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 P.Error(Loc, "invalid use of a non-first-class type");
1870 return 0;
1871 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001872
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 // Otherwise, create a new forward reference for this value and remember it.
1874 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001875 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001876 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 else
1878 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001879
Chris Lattnerdf986172009-01-02 07:01:27 +00001880 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1881 return FwdVal;
1882}
1883
1884/// SetInstName - After an instruction is parsed and inserted into its
1885/// basic block, this installs its name.
1886bool LLParser::PerFunctionState::SetInstName(int NameID,
1887 const std::string &NameStr,
1888 LocTy NameLoc, Instruction *Inst) {
1889 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001890 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001891 if (NameID != -1 || !NameStr.empty())
1892 return P.Error(NameLoc, "instructions returning void cannot have a name");
1893 return false;
1894 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001895
Chris Lattnerdf986172009-01-02 07:01:27 +00001896 // If this was a numbered instruction, verify that the instruction is the
1897 // expected value and resolve any forward references.
1898 if (NameStr.empty()) {
1899 // If neither a name nor an ID was specified, just use the next ID.
1900 if (NameID == -1)
1901 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001902
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 if (unsigned(NameID) != NumberedVals.size())
1904 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1905 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001906
Chris Lattnerdf986172009-01-02 07:01:27 +00001907 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1908 ForwardRefValIDs.find(NameID);
1909 if (FI != ForwardRefValIDs.end()) {
1910 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001911 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001912 FI->second.first->getType()->getDescription() + "'");
1913 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001914 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001915 ForwardRefValIDs.erase(FI);
1916 }
1917
1918 NumberedVals.push_back(Inst);
1919 return false;
1920 }
1921
1922 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1923 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1924 FI = ForwardRefVals.find(NameStr);
1925 if (FI != ForwardRefVals.end()) {
1926 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001928 FI->second.first->getType()->getDescription() + "'");
1929 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001930 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 ForwardRefVals.erase(FI);
1932 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001933
Chris Lattnerdf986172009-01-02 07:01:27 +00001934 // Set the name on the instruction.
1935 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001936
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001938 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 NameStr + "'");
1940 return false;
1941}
1942
1943/// GetBB - Get a basic block with the specified name or ID, creating a
1944/// forward reference record if needed.
1945BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1946 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001947 return cast_or_null<BasicBlock>(GetVal(Name,
1948 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001949}
1950
1951BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001952 return cast_or_null<BasicBlock>(GetVal(ID,
1953 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001954}
1955
1956/// DefineBB - Define the specified basic block, which is either named or
1957/// unnamed. If there is an error, this returns null otherwise it returns
1958/// the block being defined.
1959BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1960 LocTy Loc) {
1961 BasicBlock *BB;
1962 if (Name.empty())
1963 BB = GetBB(NumberedVals.size(), Loc);
1964 else
1965 BB = GetBB(Name, Loc);
1966 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001967
Chris Lattnerdf986172009-01-02 07:01:27 +00001968 // Move the block to the end of the function. Forward ref'd blocks are
1969 // inserted wherever they happen to be referenced.
1970 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001971
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 // Remove the block from forward ref sets.
1973 if (Name.empty()) {
1974 ForwardRefValIDs.erase(NumberedVals.size());
1975 NumberedVals.push_back(BB);
1976 } else {
1977 // BB forward references are already in the function symbol table.
1978 ForwardRefVals.erase(Name);
1979 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001980
Chris Lattnerdf986172009-01-02 07:01:27 +00001981 return BB;
1982}
1983
1984//===----------------------------------------------------------------------===//
1985// Constants.
1986//===----------------------------------------------------------------------===//
1987
1988/// ParseValID - Parse an abstract value that doesn't necessarily have a
1989/// type implied. For example, if we parse "4" we don't know what integer type
1990/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001991/// sanity. PFS is used to convert function-local operands of metadata (since
1992/// metadata operands are not just parsed here but also converted to values).
1993/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001994bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 ID.Loc = Lex.getLoc();
1996 switch (Lex.getKind()) {
1997 default: return TokError("expected value token");
1998 case lltok::GlobalID: // @42
1999 ID.UIntVal = Lex.getUIntVal();
2000 ID.Kind = ValID::t_GlobalID;
2001 break;
2002 case lltok::GlobalVar: // @foo
2003 ID.StrVal = Lex.getStrVal();
2004 ID.Kind = ValID::t_GlobalName;
2005 break;
2006 case lltok::LocalVarID: // %42
2007 ID.UIntVal = Lex.getUIntVal();
2008 ID.Kind = ValID::t_LocalID;
2009 break;
2010 case lltok::LocalVar: // %foo
2011 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2012 ID.StrVal = Lex.getStrVal();
2013 ID.Kind = ValID::t_LocalName;
2014 break;
Chris Lattnere434d272009-12-30 04:56:59 +00002015 case lltok::exclaim: // !{...} MDNode, !"foo" MDString
Nick Lewycky21cc4462009-04-04 07:22:01 +00002016 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00002017
Chris Lattner3f5132a2009-12-29 22:40:21 +00002018 if (EatIfPresent(lltok::lbrace)) {
Nick Lewyckycb337992009-05-10 20:57:05 +00002019 SmallVector<Value*, 16> Elts;
Victor Hernandez24e64df2010-01-10 07:14:18 +00002020 if (ParseMDNodeVector(Elts, PFS) ||
Nick Lewycky21cc4462009-04-04 07:22:01 +00002021 ParseToken(lltok::rbrace, "expected end of metadata node"))
2022 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00002023
Victor Hernandez24e64df2010-01-10 07:14:18 +00002024 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner287881d2009-12-30 02:11:14 +00002025 ID.Kind = ValID::t_MDNode;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002026 return false;
2027 }
2028
Devang Patel923078c2009-07-01 19:21:12 +00002029 // Standalone metadata reference
2030 // !{ ..., !42, ... }
Chris Lattner860775c2009-12-30 04:13:37 +00002031 if (Lex.getKind() == lltok::APSInt) {
Chris Lattner4a72efc2009-12-30 04:15:23 +00002032 if (ParseMDNodeID(ID.MDNodeVal)) return true;
Chris Lattner287881d2009-12-30 02:11:14 +00002033 ID.Kind = ValID::t_MDNode;
Devang Patel923078c2009-07-01 19:21:12 +00002034 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00002035 }
2036
Nick Lewycky21cc4462009-04-04 07:22:01 +00002037 // MDString:
2038 // ::= '!' STRINGCONSTANT
Chris Lattner287881d2009-12-30 02:11:14 +00002039 if (ParseMDString(ID.MDStringVal)) return true;
2040 ID.Kind = ValID::t_MDString;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002041 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002042 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 ID.Kind = ValID::t_APSInt;
2045 break;
2046 case lltok::APFloat:
2047 ID.APFloatVal = Lex.getAPFloatVal();
2048 ID.Kind = ValID::t_APFloat;
2049 break;
2050 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002051 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 ID.Kind = ValID::t_Constant;
2053 break;
2054 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002055 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002056 ID.Kind = ValID::t_Constant;
2057 break;
2058 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2059 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2060 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Chris Lattnerdf986172009-01-02 07:01:27 +00002062 case lltok::lbrace: {
2063 // ValID ::= '{' ConstVector '}'
2064 Lex.Lex();
2065 SmallVector<Constant*, 16> Elts;
2066 if (ParseGlobalValueVector(Elts) ||
2067 ParseToken(lltok::rbrace, "expected end of struct constant"))
2068 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002069
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002070 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2071 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 ID.Kind = ValID::t_Constant;
2073 return false;
2074 }
2075 case lltok::less: {
2076 // ValID ::= '<' ConstVector '>' --> Vector.
2077 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2078 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002079 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 SmallVector<Constant*, 16> Elts;
2082 LocTy FirstEltLoc = Lex.getLoc();
2083 if (ParseGlobalValueVector(Elts) ||
2084 (isPackedStruct &&
2085 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2086 ParseToken(lltok::greater, "expected end of constant"))
2087 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002088
Chris Lattnerdf986172009-01-02 07:01:27 +00002089 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002090 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002091 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 ID.Kind = ValID::t_Constant;
2093 return false;
2094 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Chris Lattnerdf986172009-01-02 07:01:27 +00002096 if (Elts.empty())
2097 return Error(ID.Loc, "constant vector must not be empty");
2098
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002099 if (!Elts[0]->getType()->isIntegerTy() &&
2100 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 return Error(FirstEltLoc,
2102 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002103
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 // Verify that all the vector elements have the same type.
2105 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2106 if (Elts[i]->getType() != Elts[0]->getType())
2107 return Error(FirstEltLoc,
2108 "vector element #" + utostr(i) +
2109 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Owen Andersonaf7ec972009-07-28 21:19:26 +00002111 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002112 ID.Kind = ValID::t_Constant;
2113 return false;
2114 }
2115 case lltok::lsquare: { // Array Constant
2116 Lex.Lex();
2117 SmallVector<Constant*, 16> Elts;
2118 LocTy FirstEltLoc = Lex.getLoc();
2119 if (ParseGlobalValueVector(Elts) ||
2120 ParseToken(lltok::rsquare, "expected end of array constant"))
2121 return true;
2122
2123 // Handle empty element.
2124 if (Elts.empty()) {
2125 // Use undef instead of an array because it's inconvenient to determine
2126 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002127 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 return false;
2129 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002130
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002132 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002134
Owen Andersondebcb012009-07-29 22:17:13 +00002135 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002136
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002138 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002139 if (Elts[i]->getType() != Elts[0]->getType())
2140 return Error(FirstEltLoc,
2141 "array element #" + utostr(i) +
2142 " is not of type '" +Elts[0]->getType()->getDescription());
2143 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Owen Anderson1fd70962009-07-28 18:32:17 +00002145 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 ID.Kind = ValID::t_Constant;
2147 return false;
2148 }
2149 case lltok::kw_c: // c "foo"
2150 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002151 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2153 ID.Kind = ValID::t_Constant;
2154 return false;
2155
2156 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002157 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2158 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 Lex.Lex();
2160 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002161 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002162 ParseStringConstant(ID.StrVal) ||
2163 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 ParseToken(lltok::StringConstant, "expected constraint string"))
2165 return true;
2166 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002167 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 ID.Kind = ValID::t_InlineAsm;
2169 return false;
2170 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002171
Chris Lattner09d9ef42009-10-28 03:39:23 +00002172 case lltok::kw_blockaddress: {
2173 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2174 Lex.Lex();
2175
2176 ValID Fn, Label;
2177 LocTy FnLoc, LabelLoc;
2178
2179 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2180 ParseValID(Fn) ||
2181 ParseToken(lltok::comma, "expected comma in block address expression")||
2182 ParseValID(Label) ||
2183 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2184 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002185
Chris Lattner09d9ef42009-10-28 03:39:23 +00002186 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2187 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002188 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002189 return Error(Label.Loc, "expected basic block name in blockaddress");
2190
2191 // Make a global variable as a placeholder for this reference.
2192 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2193 false, GlobalValue::InternalLinkage,
2194 0, "");
2195 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2196 ID.ConstantVal = FwdRef;
2197 ID.Kind = ValID::t_Constant;
2198 return false;
2199 }
2200
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 case lltok::kw_trunc:
2202 case lltok::kw_zext:
2203 case lltok::kw_sext:
2204 case lltok::kw_fptrunc:
2205 case lltok::kw_fpext:
2206 case lltok::kw_bitcast:
2207 case lltok::kw_uitofp:
2208 case lltok::kw_sitofp:
2209 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002210 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002212 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002213 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002214 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 Constant *SrcVal;
2216 Lex.Lex();
2217 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2218 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002219 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 ParseType(DestTy) ||
2221 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2222 return true;
2223 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2224 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2225 SrcVal->getType()->getDescription() + "' to '" +
2226 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002227 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002228 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 ID.Kind = ValID::t_Constant;
2230 return false;
2231 }
2232 case lltok::kw_extractvalue: {
2233 Lex.Lex();
2234 Constant *Val;
2235 SmallVector<unsigned, 4> Indices;
2236 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2237 ParseGlobalTypeAndValue(Val) ||
2238 ParseIndexList(Indices) ||
2239 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2240 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002241
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002242 if (!Val->getType()->isAggregateType())
2243 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2245 Indices.end()))
2246 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002247 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002248 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 ID.Kind = ValID::t_Constant;
2250 return false;
2251 }
2252 case lltok::kw_insertvalue: {
2253 Lex.Lex();
2254 Constant *Val0, *Val1;
2255 SmallVector<unsigned, 4> Indices;
2256 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2257 ParseGlobalTypeAndValue(Val0) ||
2258 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2259 ParseGlobalTypeAndValue(Val1) ||
2260 ParseIndexList(Indices) ||
2261 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2262 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002263 if (!Val0->getType()->isAggregateType())
2264 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2266 Indices.end()))
2267 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002268 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002269 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 ID.Kind = ValID::t_Constant;
2271 return false;
2272 }
2273 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002274 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 unsigned PredVal, Opc = Lex.getUIntVal();
2276 Constant *Val0, *Val1;
2277 Lex.Lex();
2278 if (ParseCmpPredicate(PredVal, Opc) ||
2279 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2280 ParseGlobalTypeAndValue(Val0) ||
2281 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2282 ParseGlobalTypeAndValue(Val1) ||
2283 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2284 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002285
Chris Lattnerdf986172009-01-02 07:01:27 +00002286 if (Val0->getType() != Val1->getType())
2287 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002288
Chris Lattnerdf986172009-01-02 07:01:27 +00002289 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002290
Chris Lattnerdf986172009-01-02 07:01:27 +00002291 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002292 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002293 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002294 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002295 } else {
2296 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002297 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002298 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002300 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002301 }
2302 ID.Kind = ValID::t_Constant;
2303 return false;
2304 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002305
Chris Lattnerdf986172009-01-02 07:01:27 +00002306 // Binary Operators.
2307 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002308 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002310 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002311 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002312 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002313 case lltok::kw_udiv:
2314 case lltok::kw_sdiv:
2315 case lltok::kw_fdiv:
2316 case lltok::kw_urem:
2317 case lltok::kw_srem:
2318 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002319 bool NUW = false;
2320 bool NSW = false;
2321 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002322 unsigned Opc = Lex.getUIntVal();
2323 Constant *Val0, *Val1;
2324 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002325 LocTy ModifierLoc = Lex.getLoc();
2326 if (Opc == Instruction::Add ||
2327 Opc == Instruction::Sub ||
2328 Opc == Instruction::Mul) {
2329 if (EatIfPresent(lltok::kw_nuw))
2330 NUW = true;
2331 if (EatIfPresent(lltok::kw_nsw)) {
2332 NSW = true;
2333 if (EatIfPresent(lltok::kw_nuw))
2334 NUW = true;
2335 }
2336 } else if (Opc == Instruction::SDiv) {
2337 if (EatIfPresent(lltok::kw_exact))
2338 Exact = true;
2339 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002340 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2341 ParseGlobalTypeAndValue(Val0) ||
2342 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2343 ParseGlobalTypeAndValue(Val1) ||
2344 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2345 return true;
2346 if (Val0->getType() != Val1->getType())
2347 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002348 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002349 if (NUW)
2350 return Error(ModifierLoc, "nuw only applies to integer operations");
2351 if (NSW)
2352 return Error(ModifierLoc, "nsw only applies to integer operations");
2353 }
2354 // API compatibility: Accept either integer or floating-point types with
2355 // add, sub, and mul.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002356 if (!Val0->getType()->isIntOrIntVectorTy() &&
2357 !Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002359 unsigned Flags = 0;
2360 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2361 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2362 if (Exact) Flags |= SDivOperator::IsExact;
2363 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002364 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 ID.Kind = ValID::t_Constant;
2366 return false;
2367 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002368
Chris Lattnerdf986172009-01-02 07:01:27 +00002369 // Logical Operations
2370 case lltok::kw_shl:
2371 case lltok::kw_lshr:
2372 case lltok::kw_ashr:
2373 case lltok::kw_and:
2374 case lltok::kw_or:
2375 case lltok::kw_xor: {
2376 unsigned Opc = Lex.getUIntVal();
2377 Constant *Val0, *Val1;
2378 Lex.Lex();
2379 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2380 ParseGlobalTypeAndValue(Val0) ||
2381 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2382 ParseGlobalTypeAndValue(Val1) ||
2383 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2384 return true;
2385 if (Val0->getType() != Val1->getType())
2386 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002387 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 return Error(ID.Loc,
2389 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002390 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 ID.Kind = ValID::t_Constant;
2392 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002393 }
2394
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 case lltok::kw_getelementptr:
2396 case lltok::kw_shufflevector:
2397 case lltok::kw_insertelement:
2398 case lltok::kw_extractelement:
2399 case lltok::kw_select: {
2400 unsigned Opc = Lex.getUIntVal();
2401 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002402 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002403 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002404 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002405 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002406 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2407 ParseGlobalValueVector(Elts) ||
2408 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2409 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002410
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002412 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002413 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002414
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002416 (Value**)(Elts.data() + 1),
2417 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002419 ID.ConstantVal = InBounds ?
2420 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2421 Elts.data() + 1,
2422 Elts.size() - 1) :
2423 ConstantExpr::getGetElementPtr(Elts[0],
2424 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002425 } else if (Opc == Instruction::Select) {
2426 if (Elts.size() != 3)
2427 return Error(ID.Loc, "expected three operands to select");
2428 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2429 Elts[2]))
2430 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002431 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 } else if (Opc == Instruction::ShuffleVector) {
2433 if (Elts.size() != 3)
2434 return Error(ID.Loc, "expected three operands to shufflevector");
2435 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2436 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002437 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002438 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 } else if (Opc == Instruction::ExtractElement) {
2440 if (Elts.size() != 2)
2441 return Error(ID.Loc, "expected two operands to extractelement");
2442 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2443 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002444 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 } else {
2446 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2447 if (Elts.size() != 3)
2448 return Error(ID.Loc, "expected three operands to insertelement");
2449 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2450 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002451 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002452 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002454
Chris Lattnerdf986172009-01-02 07:01:27 +00002455 ID.Kind = ValID::t_Constant;
2456 return false;
2457 }
2458 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002459
Chris Lattnerdf986172009-01-02 07:01:27 +00002460 Lex.Lex();
2461 return false;
2462}
2463
2464/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002465bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2466 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002467 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002468 Value *V = NULL;
2469 bool Parsed = ParseValID(ID) ||
2470 ConvertValIDToValue(Ty, ID, V, NULL);
2471 if (V && !(C = dyn_cast<Constant>(V)))
2472 return Error(ID.Loc, "global values must be constants");
2473 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002474}
2475
Victor Hernandez92f238d2010-01-11 22:31:58 +00002476bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2477 PATypeHolder Type(Type::getVoidTy(Context));
2478 return ParseType(Type) ||
2479 ParseGlobalValue(Type, V);
2480}
2481
2482/// ParseGlobalValueVector
2483/// ::= /*empty*/
2484/// ::= TypeAndValue (',' TypeAndValue)*
2485bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2486 // Empty list.
2487 if (Lex.getKind() == lltok::rbrace ||
2488 Lex.getKind() == lltok::rsquare ||
2489 Lex.getKind() == lltok::greater ||
2490 Lex.getKind() == lltok::rparen)
2491 return false;
2492
2493 Constant *C;
2494 if (ParseGlobalTypeAndValue(C)) return true;
2495 Elts.push_back(C);
2496
2497 while (EatIfPresent(lltok::comma)) {
2498 if (ParseGlobalTypeAndValue(C)) return true;
2499 Elts.push_back(C);
2500 }
2501
2502 return false;
2503}
2504
2505
2506//===----------------------------------------------------------------------===//
2507// Function Parsing.
2508//===----------------------------------------------------------------------===//
2509
2510bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2511 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002512 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002513 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002514
Chris Lattnerdf986172009-01-02 07:01:27 +00002515 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002516 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002517 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002518 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2519 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2520 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002521 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002522 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2523 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2524 return (V == 0);
2525 case ValID::t_InlineAsm: {
2526 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2527 const FunctionType *FTy =
2528 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2529 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2530 return Error(ID.Loc, "invalid type for inline asm constraint string");
2531 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2532 return false;
2533 }
2534 case ValID::t_MDNode:
2535 if (!Ty->isMetadataTy())
2536 return Error(ID.Loc, "metadata value must have metadata type");
2537 V = ID.MDNodeVal;
2538 return false;
2539 case ValID::t_MDString:
2540 if (!Ty->isMetadataTy())
2541 return Error(ID.Loc, "metadata value must have metadata type");
2542 V = ID.MDStringVal;
2543 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 case ValID::t_GlobalName:
2545 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2546 return V == 0;
2547 case ValID::t_GlobalID:
2548 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2549 return V == 0;
2550 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002551 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002552 return Error(ID.Loc, "integer constant must have integer type");
2553 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002554 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002555 return false;
2556 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002557 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002558 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2559 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002560
Chris Lattnerdf986172009-01-02 07:01:27 +00002561 // The lexer has no type info, so builds all float and double FP constants
2562 // as double. Fix this here. Long double does not need this.
2563 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002564 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002565 bool Ignored;
2566 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2567 &Ignored);
2568 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002569 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002570
Chris Lattner959873d2009-01-05 18:24:23 +00002571 if (V->getType() != Ty)
2572 return Error(ID.Loc, "floating point constant does not have type '" +
2573 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002574
Chris Lattnerdf986172009-01-02 07:01:27 +00002575 return false;
2576 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002577 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002579 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002580 return false;
2581 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002582 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002583 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002584 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002585 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002586 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002588 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002589 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002590 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002591 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002592 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002594 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002595 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002596 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002597 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 return false;
2599 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002600 if (ID.ConstantVal->getType() != Ty) {
2601 // Allow a constant struct with a single member to be converted
2602 // to a union, if the union has a member which is the same type
2603 // as the struct member.
2604 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2605 return ParseUnionValue(utype, ID, V);
2606 }
2607
Chris Lattnerdf986172009-01-02 07:01:27 +00002608 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002609 }
2610
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 V = ID.ConstantVal;
2612 return false;
2613 }
2614}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002615
Chris Lattnerdf986172009-01-02 07:01:27 +00002616bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2617 V = 0;
2618 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002619 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002620 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002621}
2622
2623bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002624 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002625 return ParseType(T) ||
2626 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002627}
2628
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002629bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2630 PerFunctionState &PFS) {
2631 Value *V;
2632 Loc = Lex.getLoc();
2633 if (ParseTypeAndValue(V, PFS)) return true;
2634 if (!isa<BasicBlock>(V))
2635 return Error(Loc, "expected a basic block");
2636 BB = cast<BasicBlock>(V);
2637 return false;
2638}
2639
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002640bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2641 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2642 if (stype->getNumContainedTypes() != 1)
2643 return Error(ID.Loc, "constant expression type mismatch");
2644 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2645 if (index < 0)
2646 return Error(ID.Loc, "initializer type is not a member of the union");
2647
2648 V = ConstantUnion::get(
2649 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2650 return false;
2651 }
2652
2653 return Error(ID.Loc, "constant expression type mismatch");
2654}
2655
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002656
Chris Lattnerdf986172009-01-02 07:01:27 +00002657/// FunctionHeader
2658/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2659/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2660/// OptionalAlign OptGC
2661bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2662 // Parse the linkage.
2663 LocTy LinkageLoc = Lex.getLoc();
2664 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002665
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002666 unsigned Visibility, RetAttrs;
2667 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002668 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002669 LocTy RetTypeLoc = Lex.getLoc();
2670 if (ParseOptionalLinkage(Linkage) ||
2671 ParseOptionalVisibility(Visibility) ||
2672 ParseOptionalCallingConv(CC) ||
2673 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002674 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002675 return true;
2676
2677 // Verify that the linkage is ok.
2678 switch ((GlobalValue::LinkageTypes)Linkage) {
2679 case GlobalValue::ExternalLinkage:
2680 break; // always ok.
2681 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002682 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002683 if (isDefine)
2684 return Error(LinkageLoc, "invalid linkage for function definition");
2685 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002686 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002687 case GlobalValue::LinkerPrivateLinkage:
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 Lattner77e80de2010-04-17 20:45:56 +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))
Chris Lattnerfe805242010-04-01 04:51:13 +00002944 if (ParseInstructionMetadata(Inst))
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.
Chris Lattnerfe805242010-04-01 04:51:13 +00002952 if (ParseInstructionMetadata(Inst))
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 Gohmanae3a0be2009-06-04 22:49:04 +00003003 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00003004 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
3005 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003006 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003007 if (NUW)
3008 return Error(ModifierLoc, "nuw only applies to integer operations");
3009 if (NSW)
3010 return Error(ModifierLoc, "nsw only applies to integer operations");
3011 }
3012 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003013 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003014 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003015 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003016 }
3017 return Result;
3018 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003019 case lltok::kw_fadd:
3020 case lltok::kw_fsub:
3021 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3022
Dan Gohman59858cf2009-07-27 16:11:46 +00003023 case lltok::kw_sdiv: {
3024 bool Exact = false;
3025 if (EatIfPresent(lltok::kw_exact))
3026 Exact = true;
3027 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3028 if (!Result)
3029 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003030 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003031 return Result;
3032 }
3033
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003036 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003037 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003038 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003039 case lltok::kw_shl:
3040 case lltok::kw_lshr:
3041 case lltok::kw_ashr:
3042 case lltok::kw_and:
3043 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003044 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003045 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003046 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003047 // Casts.
3048 case lltok::kw_trunc:
3049 case lltok::kw_zext:
3050 case lltok::kw_sext:
3051 case lltok::kw_fptrunc:
3052 case lltok::kw_fpext:
3053 case lltok::kw_bitcast:
3054 case lltok::kw_uitofp:
3055 case lltok::kw_sitofp:
3056 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003057 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003058 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003059 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003060 // Other.
3061 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003062 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003063 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3064 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3065 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3066 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3067 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3068 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3069 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003070 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3071 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003072 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003073 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3074 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3075 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003076 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003078 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003080 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003081 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3083 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3084 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3085 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3086 }
3087}
3088
3089/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3090bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003091 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 switch (Lex.getKind()) {
3093 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3094 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3095 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3096 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3097 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3098 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3099 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3100 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3101 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3102 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3103 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3104 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3105 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3106 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3107 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3108 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3109 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3110 }
3111 } else {
3112 switch (Lex.getKind()) {
3113 default: TokError("expected icmp predicate (e.g. 'eq')");
3114 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3115 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3116 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3117 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3118 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3119 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3120 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3121 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3122 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3123 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3124 }
3125 }
3126 Lex.Lex();
3127 return false;
3128}
3129
3130//===----------------------------------------------------------------------===//
3131// Terminator Instructions.
3132//===----------------------------------------------------------------------===//
3133
3134/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003135/// ::= 'ret' void (',' !dbg, !1)*
3136/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3137/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003138/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003139int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3140 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003141 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003142 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003143
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003144 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003145 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003146 return false;
3147 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003148
Chris Lattnerdf986172009-01-02 07:01:27 +00003149 Value *RV;
3150 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003151
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003152 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003153 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003154 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003155 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003156 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003157 } else {
3158 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003159 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3160 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003161 SmallVector<Value*, 8> RVs;
3162 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003163
Devang Patelf633a062009-09-17 23:04:48 +00003164 do {
Devang Patel0475c912009-09-29 00:01:14 +00003165 // If optional custom metadata, e.g. !dbg is seen then this is the
3166 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003167 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003168 break;
3169 if (ParseTypeAndValue(RV, PFS)) return true;
3170 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003171 } while (EatIfPresent(lltok::comma));
3172
3173 RV = UndefValue::get(PFS.getFunction().getReturnType());
3174 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003175 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3176 BB->getInstList().push_back(I);
3177 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003178 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003179 }
3180 }
Devang Patelf633a062009-09-17 23:04:48 +00003181
Owen Anderson1d0be152009-08-13 21:58:54 +00003182 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003183 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003184}
3185
3186
3187/// ParseBr
3188/// ::= 'br' TypeAndValue
3189/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3190bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3191 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003192 Value *Op0;
3193 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003194 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003195
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3197 Inst = BranchInst::Create(BB);
3198 return false;
3199 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003200
Owen Anderson1d0be152009-08-13 21:58:54 +00003201 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003202 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003203
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003205 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003207 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003208 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 return false;
3212}
3213
3214/// ParseSwitch
3215/// Instruction
3216/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3217/// JumpTable
3218/// ::= (TypeAndValue ',' TypeAndValue)*
3219bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3220 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003221 Value *Cond;
3222 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3224 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003225 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3227 return true;
3228
Duncan Sands1df98592010-02-16 11:11:14 +00003229 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003230 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 // Parse the jump table pairs.
3233 SmallPtrSet<Value*, 32> SeenCases;
3234 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3235 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003236 Value *Constant;
3237 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003238
Chris Lattnerdf986172009-01-02 07:01:27 +00003239 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3240 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003241 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003243
Chris Lattnerdf986172009-01-02 07:01:27 +00003244 if (!SeenCases.insert(Constant))
3245 return Error(CondLoc, "duplicate case value in switch");
3246 if (!isa<ConstantInt>(Constant))
3247 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003248
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003249 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003251
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003253
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003254 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3256 SI->addCase(Table[i].first, Table[i].second);
3257 Inst = SI;
3258 return false;
3259}
3260
Chris Lattnerab21db72009-10-28 00:19:10 +00003261/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003262/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003263/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3264bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003265 LocTy AddrLoc;
3266 Value *Address;
3267 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003268 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3269 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003270 return true;
3271
Duncan Sands1df98592010-02-16 11:11:14 +00003272 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003273 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003274
3275 // Parse the destination list.
3276 SmallVector<BasicBlock*, 16> DestList;
3277
3278 if (Lex.getKind() != lltok::rsquare) {
3279 BasicBlock *DestBB;
3280 if (ParseTypeAndBasicBlock(DestBB, PFS))
3281 return true;
3282 DestList.push_back(DestBB);
3283
3284 while (EatIfPresent(lltok::comma)) {
3285 if (ParseTypeAndBasicBlock(DestBB, PFS))
3286 return true;
3287 DestList.push_back(DestBB);
3288 }
3289 }
3290
3291 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3292 return true;
3293
Chris Lattnerab21db72009-10-28 00:19:10 +00003294 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003295 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3296 IBI->addDestination(DestList[i]);
3297 Inst = IBI;
3298 return false;
3299}
3300
3301
Chris Lattnerdf986172009-01-02 07:01:27 +00003302/// ParseInvoke
3303/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3304/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3305bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3306 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003307 unsigned RetAttrs, FnAttrs;
3308 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003309 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003310 LocTy RetTypeLoc;
3311 ValID CalleeID;
3312 SmallVector<ParamInfo, 16> ArgList;
3313
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003314 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003315 if (ParseOptionalCallingConv(CC) ||
3316 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003317 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003318 ParseValID(CalleeID) ||
3319 ParseParameterList(ArgList, PFS) ||
3320 ParseOptionalAttrs(FnAttrs, 2) ||
3321 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003322 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003323 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003324 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003326
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 // If RetType is a non-function pointer type, then this is the short syntax
3328 // for the call, which means that RetType is just the return type. Infer the
3329 // rest of the function argument types from the arguments that are present.
3330 const PointerType *PFTy = 0;
3331 const FunctionType *Ty = 0;
3332 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3333 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3334 // Pull out the types of all of the arguments...
3335 std::vector<const Type*> ParamTypes;
3336 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3337 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003338
Chris Lattnerdf986172009-01-02 07:01:27 +00003339 if (!FunctionType::isValidReturnType(RetType))
3340 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003341
Owen Andersondebcb012009-07-29 22:17:13 +00003342 Ty = FunctionType::get(RetType, ParamTypes, false);
3343 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003345
Chris Lattnerdf986172009-01-02 07:01:27 +00003346 // Look up the callee.
3347 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003348 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003349
Chris Lattnerdf986172009-01-02 07:01:27 +00003350 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3351 // function attributes.
3352 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3353 if (FnAttrs & ObsoleteFuncAttrs) {
3354 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3355 FnAttrs &= ~ObsoleteFuncAttrs;
3356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003357
Chris Lattnerdf986172009-01-02 07:01:27 +00003358 // Set up the Attributes for the function.
3359 SmallVector<AttributeWithIndex, 8> Attrs;
3360 if (RetAttrs != Attribute::None)
3361 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003362
Chris Lattnerdf986172009-01-02 07:01:27 +00003363 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003364
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 // Loop through FunctionType's arguments and ensure they are specified
3366 // correctly. Also, gather any parameter attributes.
3367 FunctionType::param_iterator I = Ty->param_begin();
3368 FunctionType::param_iterator E = Ty->param_end();
3369 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3370 const Type *ExpectedTy = 0;
3371 if (I != E) {
3372 ExpectedTy = *I++;
3373 } else if (!Ty->isVarArg()) {
3374 return Error(ArgList[i].Loc, "too many arguments specified");
3375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003376
Chris Lattnerdf986172009-01-02 07:01:27 +00003377 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3378 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3379 ExpectedTy->getDescription() + "'");
3380 Args.push_back(ArgList[i].V);
3381 if (ArgList[i].Attrs != Attribute::None)
3382 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3383 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003384
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 if (I != E)
3386 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003387
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 if (FnAttrs != Attribute::None)
3389 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003390
Chris Lattnerdf986172009-01-02 07:01:27 +00003391 // Finish off the Attributes and check them
3392 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003393
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003394 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 Args.begin(), Args.end());
3396 II->setCallingConv(CC);
3397 II->setAttributes(PAL);
3398 Inst = II;
3399 return false;
3400}
3401
3402
3403
3404//===----------------------------------------------------------------------===//
3405// Binary Operators.
3406//===----------------------------------------------------------------------===//
3407
3408/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003409/// ::= ArithmeticOps TypeAndValue ',' Value
3410///
3411/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3412/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003413bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003414 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003415 LocTy Loc; Value *LHS, *RHS;
3416 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3417 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3418 ParseValue(LHS->getType(), RHS, PFS))
3419 return true;
3420
Chris Lattnere914b592009-01-05 08:24:46 +00003421 bool Valid;
3422 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003423 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003424 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003425 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3426 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003427 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003428 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3429 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003430 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003431
Chris Lattnere914b592009-01-05 08:24:46 +00003432 if (!Valid)
3433 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003434
Chris Lattnerdf986172009-01-02 07:01:27 +00003435 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3436 return false;
3437}
3438
3439/// ParseLogical
3440/// ::= ArithmeticOps TypeAndValue ',' Value {
3441bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3442 unsigned Opc) {
3443 LocTy Loc; Value *LHS, *RHS;
3444 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3446 ParseValue(LHS->getType(), RHS, PFS))
3447 return true;
3448
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003449 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003450 return Error(Loc,"instruction requires integer or integer vector operands");
3451
3452 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3453 return false;
3454}
3455
3456
3457/// ParseCompare
3458/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3459/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003460bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3461 unsigned Opc) {
3462 // Parse the integer/fp comparison predicate.
3463 LocTy Loc;
3464 unsigned Pred;
3465 Value *LHS, *RHS;
3466 if (ParseCmpPredicate(Pred, Opc) ||
3467 ParseTypeAndValue(LHS, Loc, PFS) ||
3468 ParseToken(lltok::comma, "expected ',' after compare value") ||
3469 ParseValue(LHS->getType(), RHS, PFS))
3470 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003471
Chris Lattnerdf986172009-01-02 07:01:27 +00003472 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003473 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003475 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003476 } else {
3477 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003478 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003479 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003480 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003481 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003482 }
3483 return false;
3484}
3485
3486//===----------------------------------------------------------------------===//
3487// Other Instructions.
3488//===----------------------------------------------------------------------===//
3489
3490
3491/// ParseCast
3492/// ::= CastOpc TypeAndValue 'to' Type
3493bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3494 unsigned Opc) {
3495 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003496 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003497 if (ParseTypeAndValue(Op, Loc, PFS) ||
3498 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3499 ParseType(DestTy))
3500 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003501
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003502 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3503 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 return Error(Loc, "invalid cast opcode for cast from '" +
3505 Op->getType()->getDescription() + "' to '" +
3506 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003507 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3509 return false;
3510}
3511
3512/// ParseSelect
3513/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3514bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3515 LocTy Loc;
3516 Value *Op0, *Op1, *Op2;
3517 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3518 ParseToken(lltok::comma, "expected ',' after select condition") ||
3519 ParseTypeAndValue(Op1, PFS) ||
3520 ParseToken(lltok::comma, "expected ',' after select value") ||
3521 ParseTypeAndValue(Op2, PFS))
3522 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003523
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3525 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003526
Chris Lattnerdf986172009-01-02 07:01:27 +00003527 Inst = SelectInst::Create(Op0, Op1, Op2);
3528 return false;
3529}
3530
Chris Lattner0088a5c2009-01-05 08:18:44 +00003531/// ParseVA_Arg
3532/// ::= 'va_arg' TypeAndValue ',' Type
3533bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003535 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003536 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 if (ParseTypeAndValue(Op, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003539 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003541
Chris Lattner0088a5c2009-01-05 08:18:44 +00003542 if (!EltTy->isFirstClassType())
3543 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003544
3545 Inst = new VAArgInst(Op, EltTy);
3546 return false;
3547}
3548
3549/// ParseExtractElement
3550/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3551bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3552 LocTy Loc;
3553 Value *Op0, *Op1;
3554 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3555 ParseToken(lltok::comma, "expected ',' after extract value") ||
3556 ParseTypeAndValue(Op1, PFS))
3557 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003558
Chris Lattnerdf986172009-01-02 07:01:27 +00003559 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3560 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003561
Eric Christophera3500da2009-07-25 02:28:41 +00003562 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003563 return false;
3564}
3565
3566/// ParseInsertElement
3567/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3568bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3569 LocTy Loc;
3570 Value *Op0, *Op1, *Op2;
3571 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3572 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3573 ParseTypeAndValue(Op1, PFS) ||
3574 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3575 ParseTypeAndValue(Op2, PFS))
3576 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003577
Chris Lattnerdf986172009-01-02 07:01:27 +00003578 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003579 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003580
Chris Lattnerdf986172009-01-02 07:01:27 +00003581 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3582 return false;
3583}
3584
3585/// ParseShuffleVector
3586/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3587bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3588 LocTy Loc;
3589 Value *Op0, *Op1, *Op2;
3590 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3591 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3592 ParseTypeAndValue(Op1, PFS) ||
3593 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3594 ParseTypeAndValue(Op2, PFS))
3595 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003596
Chris Lattnerdf986172009-01-02 07:01:27 +00003597 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3598 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003599
Chris Lattnerdf986172009-01-02 07:01:27 +00003600 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3601 return false;
3602}
3603
3604/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003605/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003606int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003607 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003608 Value *Op0, *Op1;
3609 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003610
Chris Lattnerdf986172009-01-02 07:01:27 +00003611 if (ParseType(Ty) ||
3612 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3613 ParseValue(Ty, Op0, PFS) ||
3614 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003615 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003616 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3617 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003618
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003619 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003620 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3621 while (1) {
3622 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003623
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003624 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003625 break;
3626
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003627 if (Lex.getKind() == lltok::MetadataVar) {
3628 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003629 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003630 }
Devang Patela43d46f2009-10-16 18:45:49 +00003631
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003632 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003633 ParseValue(Ty, Op0, PFS) ||
3634 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003635 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003636 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3637 return true;
3638 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003639
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 if (!Ty->isFirstClassType())
3641 return Error(TypeLoc, "phi node must have first class type");
3642
3643 PHINode *PN = PHINode::Create(Ty);
3644 PN->reserveOperandSpace(PHIVals.size());
3645 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3646 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3647 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003648 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003649}
3650
3651/// ParseCall
3652/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3653/// ParameterList OptionalAttrs
3654bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3655 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003656 unsigned RetAttrs, FnAttrs;
3657 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003658 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003659 LocTy RetTypeLoc;
3660 ValID CalleeID;
3661 SmallVector<ParamInfo, 16> ArgList;
3662 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003663
Chris Lattnerdf986172009-01-02 07:01:27 +00003664 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3665 ParseOptionalCallingConv(CC) ||
3666 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003667 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 ParseValID(CalleeID) ||
3669 ParseParameterList(ArgList, PFS) ||
3670 ParseOptionalAttrs(FnAttrs, 2))
3671 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003672
Chris Lattnerdf986172009-01-02 07:01:27 +00003673 // If RetType is a non-function pointer type, then this is the short syntax
3674 // for the call, which means that RetType is just the return type. Infer the
3675 // rest of the function argument types from the arguments that are present.
3676 const PointerType *PFTy = 0;
3677 const FunctionType *Ty = 0;
3678 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3679 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3680 // Pull out the types of all of the arguments...
3681 std::vector<const Type*> ParamTypes;
3682 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3683 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003684
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 if (!FunctionType::isValidReturnType(RetType))
3686 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003687
Owen Andersondebcb012009-07-29 22:17:13 +00003688 Ty = FunctionType::get(RetType, ParamTypes, false);
3689 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003690 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003691
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 // Look up the callee.
3693 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003694 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003695
Chris Lattnerdf986172009-01-02 07:01:27 +00003696 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3697 // function attributes.
3698 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3699 if (FnAttrs & ObsoleteFuncAttrs) {
3700 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3701 FnAttrs &= ~ObsoleteFuncAttrs;
3702 }
3703
3704 // Set up the Attributes for the function.
3705 SmallVector<AttributeWithIndex, 8> Attrs;
3706 if (RetAttrs != Attribute::None)
3707 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003708
Chris Lattnerdf986172009-01-02 07:01:27 +00003709 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003710
Chris Lattnerdf986172009-01-02 07:01:27 +00003711 // Loop through FunctionType's arguments and ensure they are specified
3712 // correctly. Also, gather any parameter attributes.
3713 FunctionType::param_iterator I = Ty->param_begin();
3714 FunctionType::param_iterator E = Ty->param_end();
3715 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3716 const Type *ExpectedTy = 0;
3717 if (I != E) {
3718 ExpectedTy = *I++;
3719 } else if (!Ty->isVarArg()) {
3720 return Error(ArgList[i].Loc, "too many arguments specified");
3721 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003722
Chris Lattnerdf986172009-01-02 07:01:27 +00003723 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3724 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3725 ExpectedTy->getDescription() + "'");
3726 Args.push_back(ArgList[i].V);
3727 if (ArgList[i].Attrs != Attribute::None)
3728 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3729 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003730
Chris Lattnerdf986172009-01-02 07:01:27 +00003731 if (I != E)
3732 return Error(CallLoc, "not enough parameters specified for call");
3733
3734 if (FnAttrs != Attribute::None)
3735 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3736
3737 // Finish off the Attributes and check them
3738 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003739
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3741 CI->setTailCall(isTail);
3742 CI->setCallingConv(CC);
3743 CI->setAttributes(PAL);
3744 Inst = CI;
3745 return false;
3746}
3747
3748//===----------------------------------------------------------------------===//
3749// Memory Instructions.
3750//===----------------------------------------------------------------------===//
3751
3752/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003753/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3754/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003755int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3756 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003757 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003758 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003759 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003760 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003761 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003762
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003763 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003764 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003765 if (Lex.getKind() == lltok::kw_align) {
3766 if (ParseOptionalAlignment(Alignment)) return true;
3767 } else if (Lex.getKind() == lltok::MetadataVar) {
3768 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003769 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003770 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3771 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3772 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003773 }
3774 }
3775
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003776 if (Size && !Size->getType()->isIntegerTy(32))
Chris Lattnerdf986172009-01-02 07:01:27 +00003777 return Error(SizeLoc, "element count must be i32");
3778
Victor Hernandez68afa542009-10-21 19:11:40 +00003779 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003780 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003781 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003782 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003783
3784 // Autoupgrade old malloc instruction to malloc call.
3785 // FIXME: Remove in LLVM 3.0.
3786 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003787 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3788 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003789 if (!MallocF)
3790 // Prototype malloc as "void *(int32)".
3791 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003792 MallocF = cast<Function>(
3793 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003794 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003795return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003796}
3797
3798/// ParseFree
3799/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003800bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3801 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003802 Value *Val; LocTy Loc;
3803 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003804 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003805 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003806 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003807 return false;
3808}
3809
3810/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003811/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003812int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3813 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003814 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003815 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003816 bool AteExtraComma = false;
3817 if (ParseTypeAndValue(Val, Loc, PFS) ||
3818 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3819 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003820
Duncan Sands1df98592010-02-16 11:11:14 +00003821 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003822 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3823 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003824
Chris Lattnerdf986172009-01-02 07:01:27 +00003825 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003826 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003827}
3828
3829/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003830/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003831int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3832 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003833 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003834 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003835 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003836 if (ParseTypeAndValue(Val, Loc, PFS) ||
3837 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003838 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3839 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003840 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003841
Duncan Sands1df98592010-02-16 11:11:14 +00003842 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003843 return Error(PtrLoc, "store operand must be a pointer");
3844 if (!Val->getType()->isFirstClassType())
3845 return Error(Loc, "store operand must be a first class value");
3846 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3847 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003848
Chris Lattnerdf986172009-01-02 07:01:27 +00003849 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003850 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003851}
3852
3853/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003854/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003855/// FIXME: Remove support for getresult in LLVM 3.0
3856bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3857 Value *Val; LocTy ValLoc, EltLoc;
3858 unsigned Element;
3859 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3860 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003861 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003862 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003863
Duncan Sands1df98592010-02-16 11:11:14 +00003864 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003865 return Error(ValLoc, "getresult inst requires an aggregate operand");
3866 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3867 return Error(EltLoc, "invalid getresult index for value");
3868 Inst = ExtractValueInst::Create(Val, Element);
3869 return false;
3870}
3871
3872/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003873/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003874int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003875 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003876
Dan Gohmandcb40a32009-07-29 15:58:36 +00003877 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003878
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003879 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003880
Duncan Sands1df98592010-02-16 11:11:14 +00003881 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003882 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003883
Chris Lattnerdf986172009-01-02 07:01:27 +00003884 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003885 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003886 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003887 if (Lex.getKind() == lltok::MetadataVar) {
3888 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003889 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003890 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003891 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003892 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003893 return Error(EltLoc, "getelementptr index must be an integer");
3894 Indices.push_back(Val);
3895 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003896
Chris Lattnerdf986172009-01-02 07:01:27 +00003897 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3898 Indices.begin(), Indices.end()))
3899 return Error(Loc, "invalid getelementptr indices");
3900 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003901 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003902 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003903 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003904}
3905
3906/// ParseExtractValue
3907/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003908int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003909 Value *Val; LocTy Loc;
3910 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003911 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003912 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003913 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003914 return true;
3915
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003916 if (!Val->getType()->isAggregateType())
3917 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003918
3919 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3920 Indices.end()))
3921 return Error(Loc, "invalid indices for extractvalue");
3922 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003923 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003924}
3925
3926/// ParseInsertValue
3927/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003928int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003929 Value *Val0, *Val1; LocTy Loc0, Loc1;
3930 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003931 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003932 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3933 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3934 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003935 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003936 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003937
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003938 if (!Val0->getType()->isAggregateType())
3939 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003940
Chris Lattnerdf986172009-01-02 07:01:27 +00003941 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3942 Indices.end()))
3943 return Error(Loc0, "invalid indices for insertvalue");
3944 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003945 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003946}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003947
3948//===----------------------------------------------------------------------===//
3949// Embedded metadata.
3950//===----------------------------------------------------------------------===//
3951
3952/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003953/// ::= Element (',' Element)*
3954/// Element
3955/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003956bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003957 PerFunctionState *PFS) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003958 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003959 // Null is a special case since it is typeless.
3960 if (EatIfPresent(lltok::kw_null)) {
3961 Elts.push_back(0);
3962 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003963 }
Chris Lattnera7352392009-12-30 04:42:57 +00003964
3965 Value *V = 0;
3966 PATypeHolder Ty(Type::getVoidTy(Context));
3967 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003968 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003969 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003970 return true;
3971
Nick Lewyckycb337992009-05-10 20:57:05 +00003972 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003973 } while (EatIfPresent(lltok::comma));
3974
3975 return false;
3976}