blob: dc545fff2daf51f622cd73b22e94961dc5b971d2 [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattnerad7d1e22009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000037}
38
39/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40/// module.
41bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000042 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 I != E; ++I) {
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
49
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
52
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
57 }
58 }
59 ForwardRefInstMetadata.clear();
60 }
61
62
Victor Hernandez68afa542009-10-21 19:11:40 +000063 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000064 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000065 if (MallocF) {
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000071 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000072 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000075 MallocF->eraseFromParent();
76 MallocF = NULL;
77 }
78 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000079
80
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
85 Function *TheFn = 0;
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
91
92 if (TheFn == 0)
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
94
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
98 0))
99 return true;
100
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
102 }
103
104
Chris Lattnerdf986172009-01-02 07:01:27 +0000105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
117 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000123
Devang Patel1c7eea62009-07-08 19:23:54 +0000124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000128
Devang Patel1c7eea62009-07-08 19:23:54 +0000129
Chris Lattnerdf986172009-01-02 07:01:27 +0000130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000133
Devang Patele4b27562009-08-28 23:24:31 +0000134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000136 return false;
137}
138
Chris Lattner09d9ef42009-10-28 03:39:23 +0000139bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
144 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000148 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000152 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000153 } else {
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
156 }
157
Chris Lattnercdfc9402009-11-01 01:27:45 +0000158 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
161
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
166 }
167 return false;
168}
169
170
Chris Lattnerdf986172009-01-02 07:01:27 +0000171//===----------------------------------------------------------------------===//
172// Top-Level Entities
173//===----------------------------------------------------------------------===//
174
175bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000176 while (1) {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000194
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
202 case lltok::kw_internal: // OptionalLinkage
203 case lltok::kw_weak: // OptionalLinkage
204 case lltok::kw_weak_odr: // OptionalLinkage
205 case lltok::kw_linkonce: // OptionalLinkage
206 case lltok::kw_linkonce_odr: // OptionalLinkage
207 case lltok::kw_appending: // OptionalLinkage
208 case lltok::kw_dllexport: // OptionalLinkage
209 case lltok::kw_common: // OptionalLinkage
210 case lltok::kw_dllimport: // OptionalLinkage
211 case lltok::kw_extern_weak: // OptionalLinkage
212 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 unsigned Linkage, Visibility;
214 if (ParseOptionalLinkage(Linkage) ||
215 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000216 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 return true;
218 break;
219 }
220 case lltok::kw_default: // OptionalVisibility
221 case lltok::kw_hidden: // OptionalVisibility
222 case lltok::kw_protected: { // OptionalVisibility
223 unsigned Visibility;
224 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000225 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000226 return true;
227 break;
228 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000229
Chris Lattnerdf986172009-01-02 07:01:27 +0000230 case lltok::kw_thread_local: // OptionalThreadLocal
231 case lltok::kw_addrspace: // OptionalAddrSpace
232 case lltok::kw_constant: // GlobalType
233 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000234 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000235 break;
236 }
237 }
238}
239
240
241/// toplevelentity
242/// ::= 'module' 'asm' STRINGCONSTANT
243bool LLParser::ParseModuleAsm() {
244 assert(Lex.getKind() == lltok::kw_module);
245 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000246
247 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
249 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000250
Chris Lattnerdf986172009-01-02 07:01:27 +0000251 const std::string &AsmSoFar = M->getModuleInlineAsm();
252 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000255 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return false;
257}
258
259/// toplevelentity
260/// ::= 'target' 'triple' '=' STRINGCONSTANT
261/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
262bool LLParser::ParseTargetDefinition() {
263 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000264 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 switch (Lex.Lex()) {
266 default: return TokError("unknown target property");
267 case lltok::kw_triple:
268 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000269 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
270 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000271 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000273 return false;
274 case lltok::kw_datalayout:
275 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000276 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
277 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000278 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000279 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000280 return false;
281 }
282}
283
284/// toplevelentity
285/// ::= 'deplibs' '=' '[' ']'
286/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
287bool LLParser::ParseDepLibs() {
288 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000289 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000290 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
291 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
292 return true;
293
294 if (EatIfPresent(lltok::rsquare))
295 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000296
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000297 std::string Str;
298 if (ParseStringConstant(Str)) return true;
299 M->addLibrary(Str);
300
301 while (EatIfPresent(lltok::comma)) {
302 if (ParseStringConstant(Str)) return true;
303 M->addLibrary(Str);
304 }
305
306 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000307}
308
Dan Gohman3845e502009-08-12 23:32:33 +0000309/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000310/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000311/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000312bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000313 unsigned TypeID = NumberedTypes.size();
314
315 // Handle the LocalVarID form.
316 if (Lex.getKind() == lltok::LocalVarID) {
317 if (Lex.getUIntVal() != TypeID)
318 return Error(Lex.getLoc(), "type expected to be numbered '%" +
319 utostr(TypeID) + "'");
320 Lex.Lex(); // eat LocalVarID;
321
322 if (ParseToken(lltok::equal, "expected '=' after name"))
323 return true;
324 }
325
Chris Lattnerdf986172009-01-02 07:01:27 +0000326 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000327 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000328
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 // See if this type was previously referenced.
333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
334 FI = ForwardRefTypeIDs.find(TypeID);
335 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000338
Chris Lattnerdf986172009-01-02 07:01:27 +0000339 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
340 Ty = FI->second.first.get();
341 ForwardRefTypeIDs.erase(FI);
342 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000343
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 return false;
347}
348
349/// toplevelentity
350/// ::= LocalVar '=' 'type' type
351bool LLParser::ParseNamedType() {
352 std::string Name = Lex.getStrVal();
353 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000354 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Owen Anderson1d0be152009-08-13 21:58:54 +0000356 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after name") ||
360 ParseType(Ty))
361 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists = M->addTypeName(Name, Ty);
365 if (!AlreadyExists) return false;
366
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
370 FI = ForwardRefTypes.find(Name);
371 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
374
Chris Lattnerdf986172009-01-02 07:01:27 +0000375 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
376 Ty = FI->second.first.get();
377 ForwardRefTypes.erase(FI);
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 // Inserting a name that is already defined, get the existing name.
381 const Type *Existing = M->getTypeByName(Name);
382 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattnerdf986172009-01-02 07:01:27 +0000384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Chris Lattnerdf986172009-01-02 07:01:27 +0000389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
391 Ty->getDescription() + "'");
392}
393
394
395/// toplevelentity
396/// ::= 'declare' FunctionHeader
397bool LLParser::ParseDeclare() {
398 assert(Lex.getKind() == lltok::kw_declare);
399 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattnerdf986172009-01-02 07:01:27 +0000401 Function *F;
402 return ParseFunctionHeader(F, false);
403}
404
405/// toplevelentity
406/// ::= 'define' FunctionHeader '{' ...
407bool LLParser::ParseDefine() {
408 assert(Lex.getKind() == lltok::kw_define);
409 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000414}
415
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000416/// ParseGlobalType
417/// ::= 'constant'
418/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000419bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
421 IsConstant = true;
422 else if (Lex.getKind() == lltok::kw_global)
423 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000424 else {
425 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000426 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000427 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000428 Lex.Lex();
429 return false;
430}
431
Dan Gohman3845e502009-08-12 23:32:33 +0000432/// ParseUnnamedGlobal:
433/// OptionalVisibility ALIAS ...
434/// OptionalLinkage OptionalVisibility ... -> global variable
435/// GlobalID '=' OptionalVisibility ALIAS ...
436/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
439 std::string Name;
440 LocTy NameLoc = Lex.getLoc();
441
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
446 utostr(VarID) + "'");
447 Lex.Lex(); // eat GlobalID;
448
449 if (ParseToken(lltok::equal, "expected '=' after name"))
450 return true;
451 }
452
453 bool HasLinkage;
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Dan Gohman3845e502009-08-12 23:32:33 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Chris Lattnerdf986172009-01-02 07:01:27 +0000464/// ParseNamedGlobal:
465/// GlobalVar '=' OptionalVisibility ALIAS ...
466/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
471 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000472
Chris Lattnerdf986172009-01-02 07:01:27 +0000473 bool HasLinkage;
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattnerdf986172009-01-02 07:01:27 +0000480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
483}
484
Devang Patel256be962009-07-20 19:00:08 +0000485// MDString:
486// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000487bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000488 std::string Str;
489 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000490 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000491 return false;
492}
493
494// MDNode:
495// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000496//
497/// This version of ParseMDNodeID returns the slot number and null in the case
498/// of a forward reference.
499bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
502
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
506 else
507 Result = 0;
508 return false;
509}
510
Chris Lattner4a72efc2009-12-30 04:15:23 +0000511bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000512 // !{ ..., !42, ... }
513 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000514 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000515
Chris Lattner449c3102010-04-01 05:14:45 +0000516 // If not a forward reference, just return it now.
517 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000518
Chris Lattner449c3102010-04-01 05:14:45 +0000519 // Otherwise, create MDNode forward reference.
Dan Gohman489b29b2010-08-20 22:02:26 +0000520 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
Devang Patel256be962009-07-20 19:00:08 +0000521 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000522
523 if (NumberedMetadata.size() <= MID)
524 NumberedMetadata.resize(MID+1);
525 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000526 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000527 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000528}
Devang Patel256be962009-07-20 19:00:08 +0000529
Chris Lattner84d03b12009-12-29 22:35:39 +0000530/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000531/// !foo = !{ !1, !2 }
532bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000533 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000534 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000535 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000536
Chris Lattner84d03b12009-12-29 22:35:39 +0000537 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000538 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000539 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000540 return true;
541
Dan Gohman17aa92c2010-07-21 23:38:33 +0000542 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000543 if (Lex.getKind() != lltok::rbrace)
544 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000545 if (ParseToken(lltok::exclaim, "Expected '!' here"))
546 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000547
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000548 MDNode *N = 0;
549 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000550 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000551 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000552
553 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
554 return true;
555
Devang Pateleff2ab62009-07-29 00:34:02 +0000556 return false;
557}
558
Devang Patel923078c2009-07-01 19:21:12 +0000559/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000560/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000561bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000562 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000563 Lex.Lex();
564 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000565
566 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000567 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000568 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000569 if (ParseUInt32(MetadataID) ||
570 ParseToken(lltok::equal, "expected '=' here") ||
571 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000572 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000573 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000574 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000575 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000576 return true;
577
Owen Anderson647e3012009-07-31 21:35:40 +0000578 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000579
580 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000581 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000582 FI = ForwardRefMDNodes.find(MetadataID);
583 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000584 MDNode *Temp = FI->second.first;
585 Temp->replaceAllUsesWith(Init);
586 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000587 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000588
589 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
590 } else {
591 if (MetadataID >= NumberedMetadata.size())
592 NumberedMetadata.resize(MetadataID+1);
593
594 if (NumberedMetadata[MetadataID] != 0)
595 return TokError("Metadata id is already used");
596 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000597 }
598
Devang Patel923078c2009-07-01 19:21:12 +0000599 return false;
600}
601
Chris Lattnerdf986172009-01-02 07:01:27 +0000602/// ParseAlias:
603/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
604/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000605/// ::= TypeAndValue
606/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000607/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000608///
609/// Everything through visibility has already been parsed.
610///
611bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
612 unsigned Visibility) {
613 assert(Lex.getKind() == lltok::kw_alias);
614 Lex.Lex();
615 unsigned Linkage;
616 LocTy LinkageLoc = Lex.getLoc();
617 if (ParseOptionalLinkage(Linkage))
618 return true;
619
620 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000621 Linkage != GlobalValue::WeakAnyLinkage &&
622 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000623 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000624 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000625 Linkage != GlobalValue::LinkerPrivateLinkage &&
626 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000627 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000628
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 Constant *Aliasee;
630 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000631 if (Lex.getKind() != lltok::kw_bitcast &&
632 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 if (ParseGlobalTypeAndValue(Aliasee)) return true;
634 } else {
635 // The bitcast dest type is not present, it is implied by the dest type.
636 ValID ID;
637 if (ParseValID(ID)) return true;
638 if (ID.Kind != ValID::t_Constant)
639 return Error(AliaseeLoc, "invalid aliasee");
640 Aliasee = ID.ConstantVal;
641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000642
Duncan Sands1df98592010-02-16 11:11:14 +0000643 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000644 return Error(AliaseeLoc, "alias must have pointer type");
645
646 // Okay, create the alias but do not insert it into the module yet.
647 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
648 (GlobalValue::LinkageTypes)Linkage, Name,
649 Aliasee);
650 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000651
Chris Lattnerdf986172009-01-02 07:01:27 +0000652 // See if this value already exists in the symbol table. If so, it is either
653 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000654 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 // See if this was a redefinition. If so, there is no entry in
656 // ForwardRefVals.
657 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
658 I = ForwardRefVals.find(Name);
659 if (I == ForwardRefVals.end())
660 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
661
662 // Otherwise, this was a definition of forward ref. Verify that types
663 // agree.
664 if (Val->getType() != GA->getType())
665 return Error(NameLoc,
666 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000667
Chris Lattnerdf986172009-01-02 07:01:27 +0000668 // If they agree, just RAUW the old value with the alias and remove the
669 // forward ref info.
670 Val->replaceAllUsesWith(GA);
671 Val->eraseFromParent();
672 ForwardRefVals.erase(I);
673 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000674
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 // Insert into the module, we know its name won't collide now.
676 M->getAliasList().push_back(GA);
677 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000678
Chris Lattnerdf986172009-01-02 07:01:27 +0000679 return false;
680}
681
682/// ParseGlobal
683/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
684/// OptionalAddrSpace GlobalType Type Const
685/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
686/// OptionalAddrSpace GlobalType Type Const
687///
688/// Everything through visibility has been parsed already.
689///
690bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
691 unsigned Linkage, bool HasLinkage,
692 unsigned Visibility) {
693 unsigned AddrSpace;
694 bool ThreadLocal, IsConstant;
695 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000696
Owen Anderson1d0be152009-08-13 21:58:54 +0000697 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000698 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
699 ParseOptionalAddrSpace(AddrSpace) ||
700 ParseGlobalType(IsConstant) ||
701 ParseType(Ty, TyLoc))
702 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000703
Chris Lattnerdf986172009-01-02 07:01:27 +0000704 // If the linkage is specified and is external, then no initializer is
705 // present.
706 Constant *Init = 0;
707 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000708 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 Linkage != GlobalValue::ExternalLinkage)) {
710 if (ParseGlobalValue(Ty, Init))
711 return true;
712 }
713
Duncan Sands1df98592010-02-16 11:11:14 +0000714 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000715 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000716
Chris Lattnerdf986172009-01-02 07:01:27 +0000717 GlobalVariable *GV = 0;
718
719 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000720 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000721 if (GlobalValue *GVal = M->getNamedValue(Name)) {
722 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
723 return Error(NameLoc, "redefinition of global '@" + Name + "'");
724 GV = cast<GlobalVariable>(GVal);
725 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 } else {
727 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
728 I = ForwardRefValIDs.find(NumberedVals.size());
729 if (I != ForwardRefValIDs.end()) {
730 GV = cast<GlobalVariable>(I->second.first);
731 ForwardRefValIDs.erase(I);
732 }
733 }
734
735 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000736 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000737 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000738 } else {
739 if (GV->getType()->getElementType() != Ty)
740 return Error(TyLoc,
741 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000742
Chris Lattnerdf986172009-01-02 07:01:27 +0000743 // Move the forward-reference to the correct spot in the module.
744 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
745 }
746
747 if (Name.empty())
748 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 // Set the parsed properties on the global.
751 if (Init)
752 GV->setInitializer(Init);
753 GV->setConstant(IsConstant);
754 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
755 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
756 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattnerdf986172009-01-02 07:01:27 +0000758 // Parse attributes on the global.
759 while (Lex.getKind() == lltok::comma) {
760 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000761
Chris Lattnerdf986172009-01-02 07:01:27 +0000762 if (Lex.getKind() == lltok::kw_section) {
763 Lex.Lex();
764 GV->setSection(Lex.getStrVal());
765 if (ParseToken(lltok::StringConstant, "expected global section string"))
766 return true;
767 } else if (Lex.getKind() == lltok::kw_align) {
768 unsigned Alignment;
769 if (ParseOptionalAlignment(Alignment)) return true;
770 GV->setAlignment(Alignment);
771 } else {
772 TokError("unknown global variable property!");
773 }
774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 return false;
777}
778
779
780//===----------------------------------------------------------------------===//
781// GlobalValue Reference/Resolution Routines.
782//===----------------------------------------------------------------------===//
783
784/// GetGlobalVal - Get a value with the specified name or ID, creating a
785/// forward reference record if needed. This can return null if the value
786/// exists but does not have the right type.
787GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
788 LocTy Loc) {
789 const PointerType *PTy = dyn_cast<PointerType>(Ty);
790 if (PTy == 0) {
791 Error(Loc, "global variable reference must have pointer type");
792 return 0;
793 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerdf986172009-01-02 07:01:27 +0000795 // Look this name up in the normal function symbol table.
796 GlobalValue *Val =
797 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 // If this is a forward reference for the value, see if we already created a
800 // forward ref record.
801 if (Val == 0) {
802 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
803 I = ForwardRefVals.find(Name);
804 if (I != ForwardRefVals.end())
805 Val = I->second.first;
806 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Chris Lattnerdf986172009-01-02 07:01:27 +0000808 // If we have the value in the symbol table or fwd-ref table, return it.
809 if (Val) {
810 if (Val->getType() == Ty) return Val;
811 Error(Loc, "'@" + Name + "' defined with type '" +
812 Val->getType()->getDescription() + "'");
813 return 0;
814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000815
Chris Lattnerdf986172009-01-02 07:01:27 +0000816 // Otherwise, create a new forward reference for this value and remember it.
817 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000818 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
819 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000820 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000821 Error(Loc, "function may not return opaque type");
822 return 0;
823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000825 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000826 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000827 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
828 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Chris Lattnerdf986172009-01-02 07:01:27 +0000831 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
832 return FwdVal;
833}
834
835GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
836 const PointerType *PTy = dyn_cast<PointerType>(Ty);
837 if (PTy == 0) {
838 Error(Loc, "global variable reference must have pointer type");
839 return 0;
840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000841
Chris Lattnerdf986172009-01-02 07:01:27 +0000842 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Chris Lattnerdf986172009-01-02 07:01:27 +0000844 // If this is a forward reference for the value, see if we already created a
845 // forward ref record.
846 if (Val == 0) {
847 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
848 I = ForwardRefValIDs.find(ID);
849 if (I != ForwardRefValIDs.end())
850 Val = I->second.first;
851 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000852
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 // If we have the value in the symbol table or fwd-ref table, return it.
854 if (Val) {
855 if (Val->getType() == Ty) return Val;
856 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
857 Val->getType()->getDescription() + "'");
858 return 0;
859 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000860
Chris Lattnerdf986172009-01-02 07:01:27 +0000861 // Otherwise, create a new forward reference for this value and remember it.
862 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000863 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
864 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000865 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000866 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000867 return 0;
868 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000869 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000870 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000871 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
872 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000873 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000874
Chris Lattnerdf986172009-01-02 07:01:27 +0000875 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
876 return FwdVal;
877}
878
879
880//===----------------------------------------------------------------------===//
881// Helper Routines.
882//===----------------------------------------------------------------------===//
883
884/// ParseToken - If the current token has the specified kind, eat it and return
885/// success. Otherwise, emit the specified error and return failure.
886bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
887 if (Lex.getKind() != T)
888 return TokError(ErrMsg);
889 Lex.Lex();
890 return false;
891}
892
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000893/// ParseStringConstant
894/// ::= StringConstant
895bool LLParser::ParseStringConstant(std::string &Result) {
896 if (Lex.getKind() != lltok::StringConstant)
897 return TokError("expected string constant");
898 Result = Lex.getStrVal();
899 Lex.Lex();
900 return false;
901}
902
903/// ParseUInt32
904/// ::= uint32
905bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000906 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
907 return TokError("expected integer");
908 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
909 if (Val64 != unsigned(Val64))
910 return TokError("expected 32-bit integer (too large)");
911 Val = Val64;
912 Lex.Lex();
913 return false;
914}
915
916
917/// ParseOptionalAddrSpace
918/// := /*empty*/
919/// := 'addrspace' '(' uint32 ')'
920bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
921 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000922 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000923 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000924 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000925 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000926 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000927}
Chris Lattnerdf986172009-01-02 07:01:27 +0000928
929/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
930/// indicates what kind of attribute list this is: 0: function arg, 1: result,
931/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000932/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000933bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
934 Attrs = Attribute::None;
935 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000936
Chris Lattnerdf986172009-01-02 07:01:27 +0000937 while (1) {
938 switch (Lex.getKind()) {
939 case lltok::kw_sext:
940 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000941 // Treat these as signext/zeroext if they occur in the argument list after
942 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
943 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
944 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000945 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000946 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 if (Lex.getKind() == lltok::kw_sext)
948 Attrs |= Attribute::SExt;
949 else
950 Attrs |= Attribute::ZExt;
951 break;
952 }
953 // FALL THROUGH.
954 default: // End of attributes.
955 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
956 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000957
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000958 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000959 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000960
Chris Lattnerdf986172009-01-02 07:01:27 +0000961 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000962 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
963 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
964 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
965 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
966 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
967 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
968 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
969 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000970
Devang Patel578efa92009-06-05 21:57:13 +0000971 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
972 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
973 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
974 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
975 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000976 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000977 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
978 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
979 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
980 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
981 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
982 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000983 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000984
Charles Davis1e063d12010-02-12 00:31:15 +0000985 case lltok::kw_alignstack: {
986 unsigned Alignment;
987 if (ParseOptionalStackAlignment(Alignment))
988 return true;
989 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
990 continue;
991 }
992
Chris Lattnerdf986172009-01-02 07:01:27 +0000993 case lltok::kw_align: {
994 unsigned Alignment;
995 if (ParseOptionalAlignment(Alignment))
996 return true;
997 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
998 continue;
999 }
Charles Davis1e063d12010-02-12 00:31:15 +00001000
Chris Lattnerdf986172009-01-02 07:01:27 +00001001 }
1002 Lex.Lex();
1003 }
1004}
1005
1006/// ParseOptionalLinkage
1007/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001008/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001009/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001010/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001011/// ::= 'internal'
1012/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001013/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001014/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001015/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001016/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001017/// ::= 'appending'
1018/// ::= 'dllexport'
1019/// ::= 'common'
1020/// ::= 'dllimport'
1021/// ::= 'extern_weak'
1022/// ::= 'external'
1023bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1024 HasLinkage = false;
1025 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001026 default: Res=GlobalValue::ExternalLinkage; return false;
1027 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1028 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001029 case lltok::kw_linker_private_weak:
1030 Res = GlobalValue::LinkerPrivateWeakLinkage;
1031 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001032 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1033 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1034 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1035 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1036 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001037 case lltok::kw_available_externally:
1038 Res = GlobalValue::AvailableExternallyLinkage;
1039 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001040 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1041 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1042 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1043 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1044 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1045 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001046 }
1047 Lex.Lex();
1048 HasLinkage = true;
1049 return false;
1050}
1051
1052/// ParseOptionalVisibility
1053/// ::= /*empty*/
1054/// ::= 'default'
1055/// ::= 'hidden'
1056/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001057///
Chris Lattnerdf986172009-01-02 07:01:27 +00001058bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1059 switch (Lex.getKind()) {
1060 default: Res = GlobalValue::DefaultVisibility; return false;
1061 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1062 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1063 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1064 }
1065 Lex.Lex();
1066 return false;
1067}
1068
1069/// ParseOptionalCallingConv
1070/// ::= /*empty*/
1071/// ::= 'ccc'
1072/// ::= 'fastcc'
1073/// ::= 'coldcc'
1074/// ::= 'x86_stdcallcc'
1075/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001076/// ::= 'x86_thiscallcc'
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 Korobeynikovded05e32010-05-16 09:08:45 +00001091 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001092 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1093 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1094 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001095 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001096 case lltok::kw_cc: {
1097 unsigned ArbitraryCC;
1098 Lex.Lex();
1099 if (ParseUInt32(ArbitraryCC)) {
1100 return true;
1101 } else
1102 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1103 return false;
1104 }
1105 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001106 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107
Chris Lattnerdf986172009-01-02 07:01:27 +00001108 Lex.Lex();
1109 return false;
1110}
1111
Chris Lattnerb8c46862009-12-30 05:31:19 +00001112/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001113/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattnerfe805242010-04-01 04:51:13 +00001114bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001115 do {
1116 if (Lex.getKind() != lltok::MetadataVar)
1117 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001118
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001119 std::string Name = Lex.getStrVal();
1120 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001121
Chris Lattner442ffa12009-12-29 21:53:55 +00001122 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001123 unsigned NodeID;
1124 SMLoc Loc = Lex.getLoc();
Chris Lattnere434d272009-12-30 04:56:59 +00001125 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner449c3102010-04-01 05:14:45 +00001126 ParseMDNodeID(Node, NodeID))
Chris Lattnere434d272009-12-30 04:56:59 +00001127 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001128
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001129 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner449c3102010-04-01 05:14:45 +00001130 if (Node) {
1131 // If we got the node, add it to the instruction.
1132 Inst->setMetadata(MDK, Node);
1133 } else {
1134 MDRef R = { Loc, MDK, NodeID };
1135 // Otherwise, remember that this should be resolved later.
1136 ForwardRefInstMetadata[Inst].push_back(R);
1137 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001138
1139 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001140 } while (EatIfPresent(lltok::comma));
1141 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001142}
1143
Chris Lattnerdf986172009-01-02 07:01:27 +00001144/// ParseOptionalAlignment
1145/// ::= /* empty */
1146/// ::= 'align' 4
1147bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1148 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001149 if (!EatIfPresent(lltok::kw_align))
1150 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001151 LocTy AlignLoc = Lex.getLoc();
1152 if (ParseUInt32(Alignment)) return true;
1153 if (!isPowerOf2_32(Alignment))
1154 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001155 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001156 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001157 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001158}
1159
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001160/// ParseOptionalCommaAlign
1161/// ::=
1162/// ::= ',' align 4
1163///
1164/// This returns with AteExtraComma set to true if it ate an excess comma at the
1165/// end.
1166bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1167 bool &AteExtraComma) {
1168 AteExtraComma = false;
1169 while (EatIfPresent(lltok::comma)) {
1170 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001171 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001172 AteExtraComma = true;
1173 return false;
1174 }
1175
Chris Lattner093eed12010-04-23 00:50:50 +00001176 if (Lex.getKind() != lltok::kw_align)
1177 return Error(Lex.getLoc(), "expected metadata or 'align'");
1178
Dan Gohman138aa2a2010-07-28 20:12:04 +00001179 LocTy AlignLoc = Lex.getLoc();
Chris Lattner093eed12010-04-23 00:50:50 +00001180 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001181 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001182
Devang Patelf633a062009-09-17 23:04:48 +00001183 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001184}
1185
Charles Davis1e063d12010-02-12 00:31:15 +00001186/// ParseOptionalStackAlignment
1187/// ::= /* empty */
1188/// ::= 'alignstack' '(' 4 ')'
1189bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1190 Alignment = 0;
1191 if (!EatIfPresent(lltok::kw_alignstack))
1192 return false;
1193 LocTy ParenLoc = Lex.getLoc();
1194 if (!EatIfPresent(lltok::lparen))
1195 return Error(ParenLoc, "expected '('");
1196 LocTy AlignLoc = Lex.getLoc();
1197 if (ParseUInt32(Alignment)) return true;
1198 ParenLoc = Lex.getLoc();
1199 if (!EatIfPresent(lltok::rparen))
1200 return Error(ParenLoc, "expected ')'");
1201 if (!isPowerOf2_32(Alignment))
1202 return Error(AlignLoc, "stack alignment is not a power of two");
1203 return false;
1204}
Devang Patelf633a062009-09-17 23:04:48 +00001205
Chris Lattner628c13a2009-12-30 05:14:00 +00001206/// ParseIndexList - This parses the index list for an insert/extractvalue
1207/// instruction. This sets AteExtraComma in the case where we eat an extra
1208/// comma at the end of the line and find that it is followed by metadata.
1209/// Clients that don't allow metadata can call the version of this function that
1210/// only takes one argument.
1211///
Chris Lattnerdf986172009-01-02 07:01:27 +00001212/// ParseIndexList
1213/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001214///
1215bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1216 bool &AteExtraComma) {
1217 AteExtraComma = false;
1218
Chris Lattnerdf986172009-01-02 07:01:27 +00001219 if (Lex.getKind() != lltok::comma)
1220 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001221
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001222 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001223 if (Lex.getKind() == lltok::MetadataVar) {
1224 AteExtraComma = true;
1225 return false;
1226 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001227 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001228 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 Indices.push_back(Idx);
1230 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001231
Chris Lattnerdf986172009-01-02 07:01:27 +00001232 return false;
1233}
1234
1235//===----------------------------------------------------------------------===//
1236// Type Parsing.
1237//===----------------------------------------------------------------------===//
1238
1239/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001240bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1241 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001243
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 // Verify no unresolved uprefs.
1245 if (!UpRefs.empty())
1246 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001247
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001248 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001249 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001250
Chris Lattnerdf986172009-01-02 07:01:27 +00001251 return false;
1252}
1253
1254/// HandleUpRefs - Every time we finish a new layer of types, this function is
1255/// called. It loops through the UpRefs vector, which is a list of the
1256/// currently active types. For each type, if the up-reference is contained in
1257/// the newly completed type, we decrement the level count. When the level
1258/// count reaches zero, the up-referenced type is the type that is passed in:
1259/// thus we can complete the cycle.
1260///
1261PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1262 // If Ty isn't abstract, or if there are no up-references in it, then there is
1263 // nothing to resolve here.
1264 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001265
Chris Lattnerdf986172009-01-02 07:01:27 +00001266 PATypeHolder Ty(ty);
1267#if 0
David Greene0e28d762009-12-23 23:38:28 +00001268 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 << "' newly formed. Resolving upreferences.\n"
1270 << UpRefs.size() << " upreferences active!\n";
1271#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001272
Chris Lattnerdf986172009-01-02 07:01:27 +00001273 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1274 // to zero), we resolve them all together before we resolve them to Ty. At
1275 // the end of the loop, if there is anything to resolve to Ty, it will be in
1276 // this variable.
1277 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001278
Chris Lattnerdf986172009-01-02 07:01:27 +00001279 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1280 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1281 bool ContainsType =
1282 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1283 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001284
Chris Lattnerdf986172009-01-02 07:01:27 +00001285#if 0
David Greene0e28d762009-12-23 23:38:28 +00001286 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1288 << (ContainsType ? "true" : "false")
1289 << " level=" << UpRefs[i].NestingLevel << "\n";
1290#endif
1291 if (!ContainsType)
1292 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 // Decrement level of upreference
1295 unsigned Level = --UpRefs[i].NestingLevel;
1296 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001297
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1299 if (Level != 0)
1300 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001301
Chris Lattnerdf986172009-01-02 07:01:27 +00001302#if 0
David Greene0e28d762009-12-23 23:38:28 +00001303 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001304#endif
1305 if (!TypeToResolve)
1306 TypeToResolve = UpRefs[i].UpRefTy;
1307 else
1308 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1309 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1310 --i; // Do not skip the next element.
1311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001312
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 if (TypeToResolve)
1314 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001315
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 return Ty;
1317}
1318
1319
1320/// ParseTypeRec - The recursive function used to process the internal
1321/// implementation details of types.
1322bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1323 switch (Lex.getKind()) {
1324 default:
1325 return TokError("expected type");
1326 case lltok::Type:
1327 // TypeRec ::= 'float' | 'void' (etc)
1328 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 break;
1331 case lltok::kw_opaque:
1332 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001333 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001334 Lex.Lex();
1335 break;
1336 case lltok::lbrace:
1337 // TypeRec ::= '{' ... '}'
1338 if (ParseStructType(Result, false))
1339 return true;
1340 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001341 case lltok::kw_union:
1342 // TypeRec ::= 'union' '{' ... '}'
1343 if (ParseUnionType(Result))
1344 return true;
1345 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 case lltok::lsquare:
1347 // TypeRec ::= '[' ... ']'
1348 Lex.Lex(); // eat the lsquare.
1349 if (ParseArrayVectorType(Result, false))
1350 return true;
1351 break;
1352 case lltok::less: // Either vector or packed struct.
1353 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001354 Lex.Lex();
1355 if (Lex.getKind() == lltok::lbrace) {
1356 if (ParseStructType(Result, true) ||
1357 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001358 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001359 } else if (ParseArrayVectorType(Result, true))
1360 return true;
1361 break;
1362 case lltok::LocalVar:
1363 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1364 // TypeRec ::= %foo
1365 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1366 Result = T;
1367 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001368 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001369 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1370 std::make_pair(Result,
1371 Lex.getLoc())));
1372 M->addTypeName(Lex.getStrVal(), Result.get());
1373 }
1374 Lex.Lex();
1375 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001376
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 case lltok::LocalVarID:
1378 // TypeRec ::= %4
1379 if (Lex.getUIntVal() < NumberedTypes.size())
1380 Result = NumberedTypes[Lex.getUIntVal()];
1381 else {
1382 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1383 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1384 if (I != ForwardRefTypeIDs.end())
1385 Result = I->second.first;
1386 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001387 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1389 std::make_pair(Result,
1390 Lex.getLoc())));
1391 }
1392 }
1393 Lex.Lex();
1394 break;
1395 case lltok::backslash: {
1396 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001397 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001398 unsigned Val;
1399 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001400 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1402 Result = OT;
1403 break;
1404 }
1405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001406
1407 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 while (1) {
1409 switch (Lex.getKind()) {
1410 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001411 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001412
1413 // TypeRec ::= TypeRec '*'
1414 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001415 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001417 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001418 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001419 if (!PointerType::isValidElementType(Result.get()))
1420 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001421 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001422 Lex.Lex();
1423 break;
1424
1425 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1426 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001427 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001429 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001430 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001431 if (!PointerType::isValidElementType(Result.get()))
1432 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 unsigned AddrSpace;
1434 if (ParseOptionalAddrSpace(AddrSpace) ||
1435 ParseToken(lltok::star, "expected '*' in address space"))
1436 return true;
1437
Owen Andersondebcb012009-07-29 22:17:13 +00001438 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 break;
1440 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001441
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1443 case lltok::lparen:
1444 if (ParseFunctionType(Result))
1445 return true;
1446 break;
1447 }
1448 }
1449}
1450
1451/// ParseParameterList
1452/// ::= '(' ')'
1453/// ::= '(' Arg (',' Arg)* ')'
1454/// Arg
1455/// ::= Type OptionalAttributes Value OptionalAttributes
1456bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1457 PerFunctionState &PFS) {
1458 if (ParseToken(lltok::lparen, "expected '(' in call"))
1459 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001460
Chris Lattnerdf986172009-01-02 07:01:27 +00001461 while (Lex.getKind() != lltok::rparen) {
1462 // If this isn't the first argument, we need a comma.
1463 if (!ArgList.empty() &&
1464 ParseToken(lltok::comma, "expected ',' in argument list"))
1465 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001466
Chris Lattnerdf986172009-01-02 07:01:27 +00001467 // Parse the argument.
1468 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001469 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001470 unsigned ArgAttrs1 = Attribute::None;
1471 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001472 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001473 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001474 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001475
Chris Lattner287881d2009-12-30 02:11:14 +00001476 // Otherwise, handle normal operands.
1477 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1478 ParseValue(ArgTy, V, PFS) ||
1479 // FIXME: Should not allow attributes after the argument, remove this
1480 // in LLVM 3.0.
1481 ParseOptionalAttrs(ArgAttrs2, 3))
1482 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001483 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1484 }
1485
1486 Lex.Lex(); // Lex the ')'.
1487 return false;
1488}
1489
1490
1491
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001492/// ParseArgumentList - Parse the argument list for a function type or function
1493/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001494/// ::= '(' ArgTypeListI ')'
1495/// ArgTypeListI
1496/// ::= /*empty*/
1497/// ::= '...'
1498/// ::= ArgTypeList ',' '...'
1499/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001500///
Chris Lattnerdf986172009-01-02 07:01:27 +00001501bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001502 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 isVarArg = false;
1504 assert(Lex.getKind() == lltok::lparen);
1505 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnerdf986172009-01-02 07:01:27 +00001507 if (Lex.getKind() == lltok::rparen) {
1508 // empty
1509 } else if (Lex.getKind() == lltok::dotdotdot) {
1510 isVarArg = true;
1511 Lex.Lex();
1512 } else {
1513 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001514 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001515 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001516 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001518 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1519 // types (such as a function returning a pointer to itself). If parsing a
1520 // function prototype, we require fully resolved types.
1521 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001522 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001524 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001525 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 if (Lex.getKind() == lltok::LocalVar ||
1528 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1529 Name = Lex.getStrVal();
1530 Lex.Lex();
1531 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001532
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001533 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001534 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001535
Chris Lattnerdf986172009-01-02 07:01:27 +00001536 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001537
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001538 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001539 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001540 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001541 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 break;
1543 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001544
Chris Lattnerdf986172009-01-02 07:01:27 +00001545 // Otherwise must be an argument type.
1546 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001547 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001548 ParseOptionalAttrs(Attrs, 0)) return true;
1549
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001550 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001551 return Error(TypeLoc, "argument can not have void type");
1552
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 if (Lex.getKind() == lltok::LocalVar ||
1554 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1555 Name = Lex.getStrVal();
1556 Lex.Lex();
1557 } else {
1558 Name = "";
1559 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001560
Duncan Sands47c51882010-02-16 14:50:09 +00001561 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001562 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1565 }
1566 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001567
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001568 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001569}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001570
Chris Lattnerdf986172009-01-02 07:01:27 +00001571/// ParseFunctionType
1572/// ::= Type ArgumentList OptionalAttrs
1573bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1574 assert(Lex.getKind() == lltok::lparen);
1575
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001576 if (!FunctionType::isValidReturnType(Result))
1577 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001578
Chris Lattnerdf986172009-01-02 07:01:27 +00001579 std::vector<ArgInfo> ArgList;
1580 bool isVarArg;
1581 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001582 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001583 // FIXME: Allow, but ignore attributes on function types!
1584 // FIXME: Remove in LLVM 3.0
1585 ParseOptionalAttrs(Attrs, 2))
1586 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001587
Chris Lattnerdf986172009-01-02 07:01:27 +00001588 // Reject names on the arguments lists.
1589 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1590 if (!ArgList[i].Name.empty())
1591 return Error(ArgList[i].Loc, "argument name invalid in function type");
1592 if (!ArgList[i].Attrs != 0) {
1593 // Allow but ignore attributes on function types; this permits
1594 // auto-upgrade.
1595 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1596 }
1597 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001598
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 std::vector<const Type*> ArgListTy;
1600 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1601 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Owen Andersondebcb012009-07-29 22:17:13 +00001603 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001604 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001605 return false;
1606}
1607
1608/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1609/// TypeRec
1610/// ::= '{' '}'
1611/// ::= '{' TypeRec (',' TypeRec)* '}'
1612/// ::= '<' '{' '}' '>'
1613/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1614bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1615 assert(Lex.getKind() == lltok::lbrace);
1616 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001618 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001619 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001620 return false;
1621 }
1622
1623 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001624 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 if (ParseTypeRec(Result)) return true;
1626 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001627
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001628 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001629 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001630 if (!StructType::isValidElementType(Result))
1631 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001632
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001633 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001634 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001635 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001636
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001637 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001638 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001639 if (!StructType::isValidElementType(Result))
1640 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001641
Chris Lattnerdf986172009-01-02 07:01:27 +00001642 ParamsList.push_back(Result);
1643 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001644
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001645 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1646 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 std::vector<const Type*> ParamsListTy;
1649 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1650 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001651 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001652 return false;
1653}
1654
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001655/// ParseUnionType
1656/// TypeRec
1657/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1658bool LLParser::ParseUnionType(PATypeHolder &Result) {
1659 assert(Lex.getKind() == lltok::kw_union);
1660 Lex.Lex(); // Consume the 'union'
1661
1662 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1663
1664 SmallVector<PATypeHolder, 8> ParamsList;
1665 do {
1666 LocTy EltTyLoc = Lex.getLoc();
1667 if (ParseTypeRec(Result)) return true;
1668 ParamsList.push_back(Result);
1669
1670 if (Result->isVoidTy())
1671 return Error(EltTyLoc, "union element can not have void type");
1672 if (!UnionType::isValidElementType(Result))
1673 return Error(EltTyLoc, "invalid element type for union");
1674
1675 } while (EatIfPresent(lltok::comma)) ;
1676
1677 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1678 return true;
1679
1680 SmallVector<const Type*, 8> ParamsListTy;
1681 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1682 ParamsListTy.push_back(ParamsList[i].get());
1683 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1684 return false;
1685}
1686
Chris Lattnerdf986172009-01-02 07:01:27 +00001687/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1688/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001689/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001690/// ::= '[' APSINTVAL 'x' Types ']'
1691/// ::= '<' APSINTVAL 'x' Types '>'
1692bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1693 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1694 Lex.getAPSIntVal().getBitWidth() > 64)
1695 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattnerdf986172009-01-02 07:01:27 +00001697 LocTy SizeLoc = Lex.getLoc();
1698 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001699 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001701 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1702 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001703
1704 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001705 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001707
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001708 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001709 return Error(TypeLoc, "array and vector element type cannot be void");
1710
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001711 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1712 "expected end of sequential type"))
1713 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001714
Chris Lattnerdf986172009-01-02 07:01:27 +00001715 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001716 if (Size == 0)
1717 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 if ((unsigned)Size != Size)
1719 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001720 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001722 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001724 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001725 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001726 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001727 }
1728 return false;
1729}
1730
1731//===----------------------------------------------------------------------===//
1732// Function Semantic Analysis.
1733//===----------------------------------------------------------------------===//
1734
Chris Lattner09d9ef42009-10-28 03:39:23 +00001735LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1736 int functionNumber)
1737 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001738
1739 // Insert unnamed arguments into the NumberedVals list.
1740 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1741 AI != E; ++AI)
1742 if (!AI->hasName())
1743 NumberedVals.push_back(AI);
1744}
1745
1746LLParser::PerFunctionState::~PerFunctionState() {
1747 // If there were any forward referenced non-basicblock values, delete them.
1748 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1749 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1750 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001751 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001752 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 delete I->second.first;
1754 I->second.first = 0;
1755 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001756
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1758 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1759 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001760 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001761 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 delete I->second.first;
1763 I->second.first = 0;
1764 }
1765}
1766
Chris Lattner09d9ef42009-10-28 03:39:23 +00001767bool LLParser::PerFunctionState::FinishFunction() {
1768 // Check to see if someone took the address of labels in this block.
1769 if (!P.ForwardRefBlockAddresses.empty()) {
1770 ValID FunctionID;
1771 if (!F.getName().empty()) {
1772 FunctionID.Kind = ValID::t_GlobalName;
1773 FunctionID.StrVal = F.getName();
1774 } else {
1775 FunctionID.Kind = ValID::t_GlobalID;
1776 FunctionID.UIntVal = FunctionNumber;
1777 }
1778
1779 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1780 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1781 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1782 // Resolve all these references.
1783 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1784 return true;
1785
1786 P.ForwardRefBlockAddresses.erase(FRBAI);
1787 }
1788 }
1789
Chris Lattnerdf986172009-01-02 07:01:27 +00001790 if (!ForwardRefVals.empty())
1791 return P.Error(ForwardRefVals.begin()->second.second,
1792 "use of undefined value '%" + ForwardRefVals.begin()->first +
1793 "'");
1794 if (!ForwardRefValIDs.empty())
1795 return P.Error(ForwardRefValIDs.begin()->second.second,
1796 "use of undefined value '%" +
1797 utostr(ForwardRefValIDs.begin()->first) + "'");
1798 return false;
1799}
1800
1801
1802/// GetVal - Get a value with the specified name or ID, creating a
1803/// forward reference record if needed. This can return null if the value
1804/// exists but does not have the right type.
1805Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1806 const Type *Ty, LocTy Loc) {
1807 // Look this name up in the normal function symbol table.
1808 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001809
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 // If this is a forward reference for the value, see if we already created a
1811 // forward ref record.
1812 if (Val == 0) {
1813 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1814 I = ForwardRefVals.find(Name);
1815 if (I != ForwardRefVals.end())
1816 Val = I->second.first;
1817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001818
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 // If we have the value in the symbol table or fwd-ref table, return it.
1820 if (Val) {
1821 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001822 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001823 P.Error(Loc, "'%" + Name + "' is not a basic block");
1824 else
1825 P.Error(Loc, "'%" + Name + "' defined with type '" +
1826 Val->getType()->getDescription() + "'");
1827 return 0;
1828 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001829
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001831 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001832 P.Error(Loc, "invalid use of a non-first-class type");
1833 return 0;
1834 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001835
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 // Otherwise, create a new forward reference for this value and remember it.
1837 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001838 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001839 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 else
1841 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842
Chris Lattnerdf986172009-01-02 07:01:27 +00001843 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1844 return FwdVal;
1845}
1846
1847Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1848 LocTy Loc) {
1849 // Look this name up in the normal function symbol table.
1850 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001851
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 // If this is a forward reference for the value, see if we already created a
1853 // forward ref record.
1854 if (Val == 0) {
1855 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1856 I = ForwardRefValIDs.find(ID);
1857 if (I != ForwardRefValIDs.end())
1858 Val = I->second.first;
1859 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001860
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 // If we have the value in the symbol table or fwd-ref table, return it.
1862 if (Val) {
1863 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001864 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001865 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1866 else
1867 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1868 Val->getType()->getDescription() + "'");
1869 return 0;
1870 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871
Duncan Sands47c51882010-02-16 14:50:09 +00001872 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 P.Error(Loc, "invalid use of a non-first-class type");
1874 return 0;
1875 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001876
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 // Otherwise, create a new forward reference for this value and remember it.
1878 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001879 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001880 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 else
1882 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001883
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1885 return FwdVal;
1886}
1887
1888/// SetInstName - After an instruction is parsed and inserted into its
1889/// basic block, this installs its name.
1890bool LLParser::PerFunctionState::SetInstName(int NameID,
1891 const std::string &NameStr,
1892 LocTy NameLoc, Instruction *Inst) {
1893 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001894 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001895 if (NameID != -1 || !NameStr.empty())
1896 return P.Error(NameLoc, "instructions returning void cannot have a name");
1897 return false;
1898 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001899
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 // If this was a numbered instruction, verify that the instruction is the
1901 // expected value and resolve any forward references.
1902 if (NameStr.empty()) {
1903 // If neither a name nor an ID was specified, just use the next ID.
1904 if (NameID == -1)
1905 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001906
Chris Lattnerdf986172009-01-02 07:01:27 +00001907 if (unsigned(NameID) != NumberedVals.size())
1908 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1909 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001910
Chris Lattnerdf986172009-01-02 07:01:27 +00001911 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1912 ForwardRefValIDs.find(NameID);
1913 if (FI != ForwardRefValIDs.end()) {
1914 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 FI->second.first->getType()->getDescription() + "'");
1917 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001918 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 ForwardRefValIDs.erase(FI);
1920 }
1921
1922 NumberedVals.push_back(Inst);
1923 return false;
1924 }
1925
1926 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1927 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1928 FI = ForwardRefVals.find(NameStr);
1929 if (FI != ForwardRefVals.end()) {
1930 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001931 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001932 FI->second.first->getType()->getDescription() + "'");
1933 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001934 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001935 ForwardRefVals.erase(FI);
1936 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 // Set the name on the instruction.
1939 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001940
Chris Lattnerdf986172009-01-02 07:01:27 +00001941 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001942 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 NameStr + "'");
1944 return false;
1945}
1946
1947/// GetBB - Get a basic block with the specified name or ID, creating a
1948/// forward reference record if needed.
1949BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1950 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001951 return cast_or_null<BasicBlock>(GetVal(Name,
1952 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001953}
1954
1955BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001956 return cast_or_null<BasicBlock>(GetVal(ID,
1957 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001958}
1959
1960/// DefineBB - Define the specified basic block, which is either named or
1961/// unnamed. If there is an error, this returns null otherwise it returns
1962/// the block being defined.
1963BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1964 LocTy Loc) {
1965 BasicBlock *BB;
1966 if (Name.empty())
1967 BB = GetBB(NumberedVals.size(), Loc);
1968 else
1969 BB = GetBB(Name, Loc);
1970 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001971
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 // Move the block to the end of the function. Forward ref'd blocks are
1973 // inserted wherever they happen to be referenced.
1974 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001975
Chris Lattnerdf986172009-01-02 07:01:27 +00001976 // Remove the block from forward ref sets.
1977 if (Name.empty()) {
1978 ForwardRefValIDs.erase(NumberedVals.size());
1979 NumberedVals.push_back(BB);
1980 } else {
1981 // BB forward references are already in the function symbol table.
1982 ForwardRefVals.erase(Name);
1983 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001984
Chris Lattnerdf986172009-01-02 07:01:27 +00001985 return BB;
1986}
1987
1988//===----------------------------------------------------------------------===//
1989// Constants.
1990//===----------------------------------------------------------------------===//
1991
1992/// ParseValID - Parse an abstract value that doesn't necessarily have a
1993/// type implied. For example, if we parse "4" we don't know what integer type
1994/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001995/// sanity. PFS is used to convert function-local operands of metadata (since
1996/// metadata operands are not just parsed here but also converted to values).
1997/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001998bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 ID.Loc = Lex.getLoc();
2000 switch (Lex.getKind()) {
2001 default: return TokError("expected value token");
2002 case lltok::GlobalID: // @42
2003 ID.UIntVal = Lex.getUIntVal();
2004 ID.Kind = ValID::t_GlobalID;
2005 break;
2006 case lltok::GlobalVar: // @foo
2007 ID.StrVal = Lex.getStrVal();
2008 ID.Kind = ValID::t_GlobalName;
2009 break;
2010 case lltok::LocalVarID: // %42
2011 ID.UIntVal = Lex.getUIntVal();
2012 ID.Kind = ValID::t_LocalID;
2013 break;
2014 case lltok::LocalVar: // %foo
2015 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2016 ID.StrVal = Lex.getStrVal();
2017 ID.Kind = ValID::t_LocalName;
2018 break;
Dan Gohman83448032010-07-14 18:26:50 +00002019 case lltok::exclaim: // !42, !{...}, or !"foo"
2020 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 ID.Kind = ValID::t_APSInt;
2024 break;
2025 case lltok::APFloat:
2026 ID.APFloatVal = Lex.getAPFloatVal();
2027 ID.Kind = ValID::t_APFloat;
2028 break;
2029 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002030 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 ID.Kind = ValID::t_Constant;
2032 break;
2033 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002034 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 ID.Kind = ValID::t_Constant;
2036 break;
2037 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2038 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2039 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002040
Chris Lattnerdf986172009-01-02 07:01:27 +00002041 case lltok::lbrace: {
2042 // ValID ::= '{' ConstVector '}'
2043 Lex.Lex();
2044 SmallVector<Constant*, 16> Elts;
2045 if (ParseGlobalValueVector(Elts) ||
2046 ParseToken(lltok::rbrace, "expected end of struct constant"))
2047 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002048
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002049 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2050 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002051 ID.Kind = ValID::t_Constant;
2052 return false;
2053 }
2054 case lltok::less: {
2055 // ValID ::= '<' ConstVector '>' --> Vector.
2056 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2057 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002058 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002059
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 SmallVector<Constant*, 16> Elts;
2061 LocTy FirstEltLoc = Lex.getLoc();
2062 if (ParseGlobalValueVector(Elts) ||
2063 (isPackedStruct &&
2064 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2065 ParseToken(lltok::greater, "expected end of constant"))
2066 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002067
Chris Lattnerdf986172009-01-02 07:01:27 +00002068 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002069 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002070 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002071 ID.Kind = ValID::t_Constant;
2072 return false;
2073 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002074
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 if (Elts.empty())
2076 return Error(ID.Loc, "constant vector must not be empty");
2077
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002078 if (!Elts[0]->getType()->isIntegerTy() &&
2079 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 return Error(FirstEltLoc,
2081 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082
Chris Lattnerdf986172009-01-02 07:01:27 +00002083 // Verify that all the vector elements have the same type.
2084 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2085 if (Elts[i]->getType() != Elts[0]->getType())
2086 return Error(FirstEltLoc,
2087 "vector element #" + utostr(i) +
2088 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089
Owen Andersonaf7ec972009-07-28 21:19:26 +00002090 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 ID.Kind = ValID::t_Constant;
2092 return false;
2093 }
2094 case lltok::lsquare: { // Array Constant
2095 Lex.Lex();
2096 SmallVector<Constant*, 16> Elts;
2097 LocTy FirstEltLoc = Lex.getLoc();
2098 if (ParseGlobalValueVector(Elts) ||
2099 ParseToken(lltok::rsquare, "expected end of array constant"))
2100 return true;
2101
2102 // Handle empty element.
2103 if (Elts.empty()) {
2104 // Use undef instead of an array because it's inconvenient to determine
2105 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002106 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002107 return false;
2108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109
Chris Lattnerdf986172009-01-02 07:01:27 +00002110 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002111 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002112 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002113
Owen Andersondebcb012009-07-29 22:17:13 +00002114 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002115
Chris Lattnerdf986172009-01-02 07:01:27 +00002116 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002117 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002118 if (Elts[i]->getType() != Elts[0]->getType())
2119 return Error(FirstEltLoc,
2120 "array element #" + utostr(i) +
2121 " is not of type '" +Elts[0]->getType()->getDescription());
2122 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002123
Owen Anderson1fd70962009-07-28 18:32:17 +00002124 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 ID.Kind = ValID::t_Constant;
2126 return false;
2127 }
2128 case lltok::kw_c: // c "foo"
2129 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002130 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2132 ID.Kind = ValID::t_Constant;
2133 return false;
2134
2135 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002136 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2137 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 Lex.Lex();
2139 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002140 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002141 ParseStringConstant(ID.StrVal) ||
2142 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002143 ParseToken(lltok::StringConstant, "expected constraint string"))
2144 return true;
2145 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002146 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 ID.Kind = ValID::t_InlineAsm;
2148 return false;
2149 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002150
Chris Lattner09d9ef42009-10-28 03:39:23 +00002151 case lltok::kw_blockaddress: {
2152 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2153 Lex.Lex();
2154
2155 ValID Fn, Label;
2156 LocTy FnLoc, LabelLoc;
2157
2158 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2159 ParseValID(Fn) ||
2160 ParseToken(lltok::comma, "expected comma in block address expression")||
2161 ParseValID(Label) ||
2162 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2163 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002164
Chris Lattner09d9ef42009-10-28 03:39:23 +00002165 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2166 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002167 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002168 return Error(Label.Loc, "expected basic block name in blockaddress");
2169
2170 // Make a global variable as a placeholder for this reference.
2171 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2172 false, GlobalValue::InternalLinkage,
2173 0, "");
2174 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2175 ID.ConstantVal = FwdRef;
2176 ID.Kind = ValID::t_Constant;
2177 return false;
2178 }
2179
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 case lltok::kw_trunc:
2181 case lltok::kw_zext:
2182 case lltok::kw_sext:
2183 case lltok::kw_fptrunc:
2184 case lltok::kw_fpext:
2185 case lltok::kw_bitcast:
2186 case lltok::kw_uitofp:
2187 case lltok::kw_sitofp:
2188 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002189 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002191 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002193 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 Constant *SrcVal;
2195 Lex.Lex();
2196 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2197 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002198 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002199 ParseType(DestTy) ||
2200 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2201 return true;
2202 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2203 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2204 SrcVal->getType()->getDescription() + "' to '" +
2205 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002206 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002207 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 ID.Kind = ValID::t_Constant;
2209 return false;
2210 }
2211 case lltok::kw_extractvalue: {
2212 Lex.Lex();
2213 Constant *Val;
2214 SmallVector<unsigned, 4> Indices;
2215 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2216 ParseGlobalTypeAndValue(Val) ||
2217 ParseIndexList(Indices) ||
2218 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2219 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002220
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002221 if (!Val->getType()->isAggregateType())
2222 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002223 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2224 Indices.end()))
2225 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002226 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002227 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 ID.Kind = ValID::t_Constant;
2229 return false;
2230 }
2231 case lltok::kw_insertvalue: {
2232 Lex.Lex();
2233 Constant *Val0, *Val1;
2234 SmallVector<unsigned, 4> Indices;
2235 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2236 ParseGlobalTypeAndValue(Val0) ||
2237 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2238 ParseGlobalTypeAndValue(Val1) ||
2239 ParseIndexList(Indices) ||
2240 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2241 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002242 if (!Val0->getType()->isAggregateType())
2243 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2245 Indices.end()))
2246 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002247 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002248 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_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002253 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 unsigned PredVal, Opc = Lex.getUIntVal();
2255 Constant *Val0, *Val1;
2256 Lex.Lex();
2257 if (ParseCmpPredicate(PredVal, Opc) ||
2258 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2259 ParseGlobalTypeAndValue(Val0) ||
2260 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2261 ParseGlobalTypeAndValue(Val1) ||
2262 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2263 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002264
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 if (Val0->getType() != Val1->getType())
2266 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002267
Chris Lattnerdf986172009-01-02 07:01:27 +00002268 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002269
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002271 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002273 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002274 } else {
2275 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002276 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002277 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002279 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 }
2281 ID.Kind = ValID::t_Constant;
2282 return false;
2283 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002284
Chris Lattnerdf986172009-01-02 07:01:27 +00002285 // Binary Operators.
2286 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002287 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002288 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002289 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002291 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002292 case lltok::kw_udiv:
2293 case lltok::kw_sdiv:
2294 case lltok::kw_fdiv:
2295 case lltok::kw_urem:
2296 case lltok::kw_srem:
2297 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002298 bool NUW = false;
2299 bool NSW = false;
2300 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002301 unsigned Opc = Lex.getUIntVal();
2302 Constant *Val0, *Val1;
2303 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002304 LocTy ModifierLoc = Lex.getLoc();
2305 if (Opc == Instruction::Add ||
2306 Opc == Instruction::Sub ||
2307 Opc == Instruction::Mul) {
2308 if (EatIfPresent(lltok::kw_nuw))
2309 NUW = true;
2310 if (EatIfPresent(lltok::kw_nsw)) {
2311 NSW = true;
2312 if (EatIfPresent(lltok::kw_nuw))
2313 NUW = true;
2314 }
2315 } else if (Opc == Instruction::SDiv) {
2316 if (EatIfPresent(lltok::kw_exact))
2317 Exact = true;
2318 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2320 ParseGlobalTypeAndValue(Val0) ||
2321 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2322 ParseGlobalTypeAndValue(Val1) ||
2323 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2324 return true;
2325 if (Val0->getType() != Val1->getType())
2326 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002327 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002328 if (NUW)
2329 return Error(ModifierLoc, "nuw only applies to integer operations");
2330 if (NSW)
2331 return Error(ModifierLoc, "nsw only applies to integer operations");
2332 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002333 // Check that the type is valid for the operator.
2334 switch (Opc) {
2335 case Instruction::Add:
2336 case Instruction::Sub:
2337 case Instruction::Mul:
2338 case Instruction::UDiv:
2339 case Instruction::SDiv:
2340 case Instruction::URem:
2341 case Instruction::SRem:
2342 if (!Val0->getType()->isIntOrIntVectorTy())
2343 return Error(ID.Loc, "constexpr requires integer operands");
2344 break;
2345 case Instruction::FAdd:
2346 case Instruction::FSub:
2347 case Instruction::FMul:
2348 case Instruction::FDiv:
2349 case Instruction::FRem:
2350 if (!Val0->getType()->isFPOrFPVectorTy())
2351 return Error(ID.Loc, "constexpr requires fp operands");
2352 break;
2353 default: llvm_unreachable("Unknown binary operator!");
2354 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002355 unsigned Flags = 0;
2356 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2357 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2358 if (Exact) Flags |= SDivOperator::IsExact;
2359 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002360 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002361 ID.Kind = ValID::t_Constant;
2362 return false;
2363 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002364
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 // Logical Operations
2366 case lltok::kw_shl:
2367 case lltok::kw_lshr:
2368 case lltok::kw_ashr:
2369 case lltok::kw_and:
2370 case lltok::kw_or:
2371 case lltok::kw_xor: {
2372 unsigned Opc = Lex.getUIntVal();
2373 Constant *Val0, *Val1;
2374 Lex.Lex();
2375 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2376 ParseGlobalTypeAndValue(Val0) ||
2377 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2378 ParseGlobalTypeAndValue(Val1) ||
2379 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2380 return true;
2381 if (Val0->getType() != Val1->getType())
2382 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002383 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002384 return Error(ID.Loc,
2385 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002386 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 ID.Kind = ValID::t_Constant;
2388 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002389 }
2390
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 case lltok::kw_getelementptr:
2392 case lltok::kw_shufflevector:
2393 case lltok::kw_insertelement:
2394 case lltok::kw_extractelement:
2395 case lltok::kw_select: {
2396 unsigned Opc = Lex.getUIntVal();
2397 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002398 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002399 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002400 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002401 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2403 ParseGlobalValueVector(Elts) ||
2404 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2405 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002408 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002410
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002412 (Value**)(Elts.data() + 1),
2413 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002415 ID.ConstantVal = InBounds ?
2416 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2417 Elts.data() + 1,
2418 Elts.size() - 1) :
2419 ConstantExpr::getGetElementPtr(Elts[0],
2420 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002421 } else if (Opc == Instruction::Select) {
2422 if (Elts.size() != 3)
2423 return Error(ID.Loc, "expected three operands to select");
2424 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2425 Elts[2]))
2426 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002427 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 } else if (Opc == Instruction::ShuffleVector) {
2429 if (Elts.size() != 3)
2430 return Error(ID.Loc, "expected three operands to shufflevector");
2431 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2432 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002433 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002434 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 } else if (Opc == Instruction::ExtractElement) {
2436 if (Elts.size() != 2)
2437 return Error(ID.Loc, "expected two operands to extractelement");
2438 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2439 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002440 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002441 } else {
2442 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2443 if (Elts.size() != 3)
2444 return Error(ID.Loc, "expected three operands to insertelement");
2445 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2446 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002447 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002448 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002450
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 ID.Kind = ValID::t_Constant;
2452 return false;
2453 }
2454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002455
Chris Lattnerdf986172009-01-02 07:01:27 +00002456 Lex.Lex();
2457 return false;
2458}
2459
2460/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002461bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2462 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002463 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002464 Value *V = NULL;
2465 bool Parsed = ParseValID(ID) ||
2466 ConvertValIDToValue(Ty, ID, V, NULL);
2467 if (V && !(C = dyn_cast<Constant>(V)))
2468 return Error(ID.Loc, "global values must be constants");
2469 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002470}
2471
Victor Hernandez92f238d2010-01-11 22:31:58 +00002472bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2473 PATypeHolder Type(Type::getVoidTy(Context));
2474 return ParseType(Type) ||
2475 ParseGlobalValue(Type, V);
2476}
2477
2478/// ParseGlobalValueVector
2479/// ::= /*empty*/
2480/// ::= TypeAndValue (',' TypeAndValue)*
2481bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2482 // Empty list.
2483 if (Lex.getKind() == lltok::rbrace ||
2484 Lex.getKind() == lltok::rsquare ||
2485 Lex.getKind() == lltok::greater ||
2486 Lex.getKind() == lltok::rparen)
2487 return false;
2488
2489 Constant *C;
2490 if (ParseGlobalTypeAndValue(C)) return true;
2491 Elts.push_back(C);
2492
2493 while (EatIfPresent(lltok::comma)) {
2494 if (ParseGlobalTypeAndValue(C)) return true;
2495 Elts.push_back(C);
2496 }
2497
2498 return false;
2499}
2500
Dan Gohman83448032010-07-14 18:26:50 +00002501/// ParseMetadataValue
2502/// ::= !42
2503/// ::= !{...}
2504/// ::= !"string"
2505bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2506 assert(Lex.getKind() == lltok::exclaim);
2507 Lex.Lex();
2508
2509 // MDNode:
2510 // !{ ... }
2511 if (EatIfPresent(lltok::lbrace)) {
2512 SmallVector<Value*, 16> Elts;
2513 if (ParseMDNodeVector(Elts, PFS) ||
2514 ParseToken(lltok::rbrace, "expected end of metadata node"))
2515 return true;
2516
2517 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2518 ID.Kind = ValID::t_MDNode;
2519 return false;
2520 }
2521
2522 // Standalone metadata reference
2523 // !42
2524 if (Lex.getKind() == lltok::APSInt) {
2525 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2526 ID.Kind = ValID::t_MDNode;
2527 return false;
2528 }
2529
2530 // MDString:
2531 // ::= '!' STRINGCONSTANT
2532 if (ParseMDString(ID.MDStringVal)) return true;
2533 ID.Kind = ValID::t_MDString;
2534 return false;
2535}
2536
Victor Hernandez92f238d2010-01-11 22:31:58 +00002537
2538//===----------------------------------------------------------------------===//
2539// Function Parsing.
2540//===----------------------------------------------------------------------===//
2541
2542bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2543 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002544 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002546
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002548 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002549 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002550 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2551 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2552 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002553 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002554 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2555 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2556 return (V == 0);
2557 case ValID::t_InlineAsm: {
2558 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2559 const FunctionType *FTy =
2560 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2561 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2562 return Error(ID.Loc, "invalid type for inline asm constraint string");
2563 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2564 return false;
2565 }
2566 case ValID::t_MDNode:
2567 if (!Ty->isMetadataTy())
2568 return Error(ID.Loc, "metadata value must have metadata type");
2569 V = ID.MDNodeVal;
2570 return false;
2571 case ValID::t_MDString:
2572 if (!Ty->isMetadataTy())
2573 return Error(ID.Loc, "metadata value must have metadata type");
2574 V = ID.MDStringVal;
2575 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 case ValID::t_GlobalName:
2577 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2578 return V == 0;
2579 case ValID::t_GlobalID:
2580 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2581 return V == 0;
2582 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002583 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002584 return Error(ID.Loc, "integer constant must have integer type");
2585 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002586 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 return false;
2588 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002589 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2591 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002592
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 // The lexer has no type info, so builds all float and double FP constants
2594 // as double. Fix this here. Long double does not need this.
2595 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002596 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 bool Ignored;
2598 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2599 &Ignored);
2600 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002601 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002602
Chris Lattner959873d2009-01-05 18:24:23 +00002603 if (V->getType() != Ty)
2604 return Error(ID.Loc, "floating point constant does not have type '" +
2605 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002606
Chris Lattnerdf986172009-01-02 07:01:27 +00002607 return false;
2608 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002609 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002610 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002611 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 return false;
2613 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002614 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002615 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002616 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002617 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002618 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002620 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002621 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002622 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002623 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002624 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002626 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002627 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002628 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002629 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 return false;
2631 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002632 if (ID.ConstantVal->getType() != Ty) {
2633 // Allow a constant struct with a single member to be converted
2634 // to a union, if the union has a member which is the same type
2635 // as the struct member.
2636 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2637 return ParseUnionValue(utype, ID, V);
2638 }
2639
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002641 }
2642
Chris Lattnerdf986172009-01-02 07:01:27 +00002643 V = ID.ConstantVal;
2644 return false;
2645 }
2646}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002647
Chris Lattnerdf986172009-01-02 07:01:27 +00002648bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2649 V = 0;
2650 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002651 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002652 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002653}
2654
2655bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002656 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002657 return ParseType(T) ||
2658 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002659}
2660
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002661bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2662 PerFunctionState &PFS) {
2663 Value *V;
2664 Loc = Lex.getLoc();
2665 if (ParseTypeAndValue(V, PFS)) return true;
2666 if (!isa<BasicBlock>(V))
2667 return Error(Loc, "expected a basic block");
2668 BB = cast<BasicBlock>(V);
2669 return false;
2670}
2671
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002672bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2673 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2674 if (stype->getNumContainedTypes() != 1)
2675 return Error(ID.Loc, "constant expression type mismatch");
2676 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2677 if (index < 0)
2678 return Error(ID.Loc, "initializer type is not a member of the union");
2679
2680 V = ConstantUnion::get(
2681 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2682 return false;
2683 }
2684
2685 return Error(ID.Loc, "constant expression type mismatch");
2686}
2687
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002688
Chris Lattnerdf986172009-01-02 07:01:27 +00002689/// FunctionHeader
2690/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2691/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2692/// OptionalAlign OptGC
2693bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2694 // Parse the linkage.
2695 LocTy LinkageLoc = Lex.getLoc();
2696 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002698 unsigned Visibility, RetAttrs;
2699 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002700 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 LocTy RetTypeLoc = Lex.getLoc();
2702 if (ParseOptionalLinkage(Linkage) ||
2703 ParseOptionalVisibility(Visibility) ||
2704 ParseOptionalCallingConv(CC) ||
2705 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002706 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002707 return true;
2708
2709 // Verify that the linkage is ok.
2710 switch ((GlobalValue::LinkageTypes)Linkage) {
2711 case GlobalValue::ExternalLinkage:
2712 break; // always ok.
2713 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002714 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 if (isDefine)
2716 return Error(LinkageLoc, "invalid linkage for function definition");
2717 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002718 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002719 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002720 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002722 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002723 case GlobalValue::LinkOnceAnyLinkage:
2724 case GlobalValue::LinkOnceODRLinkage:
2725 case GlobalValue::WeakAnyLinkage:
2726 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 case GlobalValue::DLLExportLinkage:
2728 if (!isDefine)
2729 return Error(LinkageLoc, "invalid linkage for function declaration");
2730 break;
2731 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002732 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 return Error(LinkageLoc, "invalid function linkage type");
2734 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002735
Chris Lattner99bb3152009-01-05 08:00:30 +00002736 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002737 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002738 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002739
Chris Lattnerdf986172009-01-02 07:01:27 +00002740 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002741
2742 std::string FunctionName;
2743 if (Lex.getKind() == lltok::GlobalVar) {
2744 FunctionName = Lex.getStrVal();
2745 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2746 unsigned NameID = Lex.getUIntVal();
2747
2748 if (NameID != NumberedVals.size())
2749 return TokError("function expected to be numbered '%" +
2750 utostr(NumberedVals.size()) + "'");
2751 } else {
2752 return TokError("expected function name");
2753 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002754
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002755 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002756
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002757 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002759
Chris Lattnerdf986172009-01-02 07:01:27 +00002760 std::vector<ArgInfo> ArgList;
2761 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002764 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002765 std::string GC;
2766
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002767 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002768 ParseOptionalAttrs(FuncAttrs, 2) ||
2769 (EatIfPresent(lltok::kw_section) &&
2770 ParseStringConstant(Section)) ||
2771 ParseOptionalAlignment(Alignment) ||
2772 (EatIfPresent(lltok::kw_gc) &&
2773 ParseStringConstant(GC)))
2774 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002775
2776 // If the alignment was parsed as an attribute, move to the alignment field.
2777 if (FuncAttrs & Attribute::Alignment) {
2778 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2779 FuncAttrs &= ~Attribute::Alignment;
2780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 // Okay, if we got here, the function is syntactically valid. Convert types
2783 // and do semantic checks.
2784 std::vector<const Type*> ParamTypeList;
2785 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002786 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002787 // attributes.
2788 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2789 if (FuncAttrs & ObsoleteFuncAttrs) {
2790 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2791 FuncAttrs &= ~ObsoleteFuncAttrs;
2792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002793
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 if (RetAttrs != Attribute::None)
2795 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002796
Chris Lattnerdf986172009-01-02 07:01:27 +00002797 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2798 ParamTypeList.push_back(ArgList[i].Type);
2799 if (ArgList[i].Attrs != Attribute::None)
2800 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2801 }
2802
2803 if (FuncAttrs != Attribute::None)
2804 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2805
2806 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002807
Benjamin Kramerf0127052010-01-05 13:12:22 +00002808 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2810
Owen Andersonfba933c2009-07-01 23:57:11 +00002811 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002812 FunctionType::get(RetType, ParamTypeList, isVarArg);
2813 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002814
2815 Fn = 0;
2816 if (!FunctionName.empty()) {
2817 // If this was a definition of a forward reference, remove the definition
2818 // from the forward reference table and fill in the forward ref.
2819 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2820 ForwardRefVals.find(FunctionName);
2821 if (FRVI != ForwardRefVals.end()) {
2822 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002823 if (Fn->getType() != PFT)
2824 return Error(FRVI->second.second, "invalid forward reference to "
2825 "function '" + FunctionName + "' with wrong type!");
2826
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 ForwardRefVals.erase(FRVI);
2828 } else if ((Fn = M->getFunction(FunctionName))) {
2829 // If this function already exists in the symbol table, then it is
2830 // multiply defined. We accept a few cases for old backwards compat.
2831 // FIXME: Remove this stuff for LLVM 3.0.
2832 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2833 (!Fn->isDeclaration() && isDefine)) {
2834 // If the redefinition has different type or different attributes,
2835 // reject it. If both have bodies, reject it.
2836 return Error(NameLoc, "invalid redefinition of function '" +
2837 FunctionName + "'");
2838 } else if (Fn->isDeclaration()) {
2839 // Make sure to strip off any argument names so we can't get conflicts.
2840 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2841 AI != AE; ++AI)
2842 AI->setName("");
2843 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002844 } else if (M->getNamedValue(FunctionName)) {
2845 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002846 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002847
Dan Gohman41905542009-08-29 23:37:49 +00002848 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002849 // If this is a definition of a forward referenced function, make sure the
2850 // types agree.
2851 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2852 = ForwardRefValIDs.find(NumberedVals.size());
2853 if (I != ForwardRefValIDs.end()) {
2854 Fn = cast<Function>(I->second.first);
2855 if (Fn->getType() != PFT)
2856 return Error(NameLoc, "type of definition and forward reference of '@" +
2857 utostr(NumberedVals.size()) +"' disagree");
2858 ForwardRefValIDs.erase(I);
2859 }
2860 }
2861
2862 if (Fn == 0)
2863 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2864 else // Move the forward-reference to the correct spot in the module.
2865 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2866
2867 if (FunctionName.empty())
2868 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002869
Chris Lattnerdf986172009-01-02 07:01:27 +00002870 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2871 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2872 Fn->setCallingConv(CC);
2873 Fn->setAttributes(PAL);
2874 Fn->setAlignment(Alignment);
2875 Fn->setSection(Section);
2876 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 // Add all of the arguments we parsed to the function.
2879 Function::arg_iterator ArgIt = Fn->arg_begin();
2880 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002881 // If we run out of arguments in the Function prototype, exit early.
2882 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2883 if (ArgIt == Fn->arg_end()) break;
2884
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 // If the argument has a name, insert it into the argument symbol table.
2886 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002887
Chris Lattnerdf986172009-01-02 07:01:27 +00002888 // Set the name, if it conflicted, it will be auto-renamed.
2889 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnerdf986172009-01-02 07:01:27 +00002891 if (ArgIt->getNameStr() != ArgList[i].Name)
2892 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2893 ArgList[i].Name + "'");
2894 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002895
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 return false;
2897}
2898
2899
2900/// ParseFunctionBody
2901/// ::= '{' BasicBlock+ '}'
2902/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2903///
2904bool LLParser::ParseFunctionBody(Function &Fn) {
2905 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2906 return TokError("expected '{' in function body");
2907 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002908
Chris Lattner09d9ef42009-10-28 03:39:23 +00002909 int FunctionNumber = -1;
2910 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2911
2912 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002913
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002914 // We need at least one basic block.
2915 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2916 return TokError("function body requires at least one basic block");
2917
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2919 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002920
Chris Lattnerdf986172009-01-02 07:01:27 +00002921 // Eat the }.
2922 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002923
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002925 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002926}
2927
2928/// ParseBasicBlock
2929/// ::= LabelStr? Instruction*
2930bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2931 // If this basic block starts out with a name, remember it.
2932 std::string Name;
2933 LocTy NameLoc = Lex.getLoc();
2934 if (Lex.getKind() == lltok::LabelStr) {
2935 Name = Lex.getStrVal();
2936 Lex.Lex();
2937 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002938
Chris Lattnerdf986172009-01-02 07:01:27 +00002939 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2940 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002941
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002943
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 // Parse the instructions in this block until we get a terminator.
2945 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002946 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002947 do {
2948 // This instruction may have three possibilities for a name: a) none
2949 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2950 LocTy NameLoc = Lex.getLoc();
2951 int NameID = -1;
2952 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002953
Chris Lattnerdf986172009-01-02 07:01:27 +00002954 if (Lex.getKind() == lltok::LocalVarID) {
2955 NameID = Lex.getUIntVal();
2956 Lex.Lex();
2957 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2958 return true;
2959 } else if (Lex.getKind() == lltok::LocalVar ||
2960 // FIXME: REMOVE IN LLVM 3.0
2961 Lex.getKind() == lltok::StringConstant) {
2962 NameStr = Lex.getStrVal();
2963 Lex.Lex();
2964 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2965 return true;
2966 }
Devang Patelf633a062009-09-17 23:04:48 +00002967
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002968 switch (ParseInstruction(Inst, BB, PFS)) {
2969 default: assert(0 && "Unknown ParseInstruction result!");
2970 case InstError: return true;
2971 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002972 BB->getInstList().push_back(Inst);
2973
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002974 // With a normal result, we check to see if the instruction is followed by
2975 // a comma and metadata.
2976 if (EatIfPresent(lltok::comma))
Chris Lattnerfe805242010-04-01 04:51:13 +00002977 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002978 return true;
2979 break;
2980 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002981 BB->getInstList().push_back(Inst);
2982
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002983 // If the instruction parser ate an extra comma at the end of it, it
2984 // *must* be followed by metadata.
Chris Lattnerfe805242010-04-01 04:51:13 +00002985 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002986 return true;
2987 break;
2988 }
Devang Patelf633a062009-09-17 23:04:48 +00002989
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 // Set the name on the instruction.
2991 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2992 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002993
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 return false;
2995}
2996
2997//===----------------------------------------------------------------------===//
2998// Instruction Parsing.
2999//===----------------------------------------------------------------------===//
3000
3001/// ParseInstruction - Parse one of the many different instructions.
3002///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003003int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3004 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003005 lltok::Kind Token = Lex.getKind();
3006 if (Token == lltok::Eof)
3007 return TokError("found end of file when expecting more instructions");
3008 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003009 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003010 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003011
Chris Lattnerdf986172009-01-02 07:01:27 +00003012 switch (Token) {
3013 default: return Error(Loc, "expected instruction opcode");
3014 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003015 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3016 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003017 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3018 case lltok::kw_br: return ParseBr(Inst, PFS);
3019 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003020 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003021 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3022 // Binary Operators.
3023 case lltok::kw_add:
3024 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00003025 case lltok::kw_mul: {
3026 bool NUW = false;
3027 bool NSW = false;
3028 LocTy ModifierLoc = Lex.getLoc();
3029 if (EatIfPresent(lltok::kw_nuw))
3030 NUW = true;
3031 if (EatIfPresent(lltok::kw_nsw)) {
3032 NSW = true;
3033 if (EatIfPresent(lltok::kw_nuw))
3034 NUW = true;
3035 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003036 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003037 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003038 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003039 if (NUW)
3040 return Error(ModifierLoc, "nuw only applies to integer operations");
3041 if (NSW)
3042 return Error(ModifierLoc, "nsw only applies to integer operations");
3043 }
3044 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003045 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003046 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003047 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003048 }
3049 return Result;
3050 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003051 case lltok::kw_fadd:
3052 case lltok::kw_fsub:
3053 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3054
Dan Gohman59858cf2009-07-27 16:11:46 +00003055 case lltok::kw_sdiv: {
3056 bool Exact = false;
3057 if (EatIfPresent(lltok::kw_exact))
3058 Exact = true;
3059 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3060 if (!Result)
3061 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003062 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003063 return Result;
3064 }
3065
Chris Lattnerdf986172009-01-02 07:01:27 +00003066 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003068 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003069 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003070 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 case lltok::kw_shl:
3072 case lltok::kw_lshr:
3073 case lltok::kw_ashr:
3074 case lltok::kw_and:
3075 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003076 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003078 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 // Casts.
3080 case lltok::kw_trunc:
3081 case lltok::kw_zext:
3082 case lltok::kw_sext:
3083 case lltok::kw_fptrunc:
3084 case lltok::kw_fpext:
3085 case lltok::kw_bitcast:
3086 case lltok::kw_uitofp:
3087 case lltok::kw_sitofp:
3088 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003089 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003091 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 // Other.
3093 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003094 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3096 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3097 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3098 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3099 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3100 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3101 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003102 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3103 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003104 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003105 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3106 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3107 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003108 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003110 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003112 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003113 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003114 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3115 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3116 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3117 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3118 }
3119}
3120
3121/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3122bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003123 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003124 switch (Lex.getKind()) {
3125 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3126 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3127 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3128 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3129 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3130 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3131 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3132 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3133 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3134 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3135 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3136 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3137 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3138 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3139 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3140 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3141 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3142 }
3143 } else {
3144 switch (Lex.getKind()) {
3145 default: TokError("expected icmp predicate (e.g. 'eq')");
3146 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3147 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3148 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3149 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3150 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3151 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3152 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3153 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3154 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3155 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3156 }
3157 }
3158 Lex.Lex();
3159 return false;
3160}
3161
3162//===----------------------------------------------------------------------===//
3163// Terminator Instructions.
3164//===----------------------------------------------------------------------===//
3165
3166/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003167/// ::= 'ret' void (',' !dbg, !1)*
3168/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3169/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003170/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003171int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3172 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003173 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003174 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003175
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003176 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003177 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 return false;
3179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003180
Chris Lattnerdf986172009-01-02 07:01:27 +00003181 Value *RV;
3182 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003183
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003184 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003185 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003186 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003187 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003188 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003189 } else {
3190 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003191 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3192 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003193 SmallVector<Value*, 8> RVs;
3194 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003195
Devang Patelf633a062009-09-17 23:04:48 +00003196 do {
Devang Patel0475c912009-09-29 00:01:14 +00003197 // If optional custom metadata, e.g. !dbg is seen then this is the
3198 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003199 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003200 break;
3201 if (ParseTypeAndValue(RV, PFS)) return true;
3202 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003203 } while (EatIfPresent(lltok::comma));
3204
3205 RV = UndefValue::get(PFS.getFunction().getReturnType());
3206 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003207 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3208 BB->getInstList().push_back(I);
3209 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003210 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 }
3212 }
Devang Patelf633a062009-09-17 23:04:48 +00003213
Owen Anderson1d0be152009-08-13 21:58:54 +00003214 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003215 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003216}
3217
3218
3219/// ParseBr
3220/// ::= 'br' TypeAndValue
3221/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3222bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3223 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003224 Value *Op0;
3225 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003227
Chris Lattnerdf986172009-01-02 07:01:27 +00003228 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3229 Inst = BranchInst::Create(BB);
3230 return false;
3231 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003232
Owen Anderson1d0be152009-08-13 21:58:54 +00003233 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003234 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003235
Chris Lattnerdf986172009-01-02 07:01:27 +00003236 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003237 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003239 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003242 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 return false;
3244}
3245
3246/// ParseSwitch
3247/// Instruction
3248/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3249/// JumpTable
3250/// ::= (TypeAndValue ',' TypeAndValue)*
3251bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3252 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003253 Value *Cond;
3254 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3256 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003257 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003258 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3259 return true;
3260
Duncan Sands1df98592010-02-16 11:11:14 +00003261 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003263
Chris Lattnerdf986172009-01-02 07:01:27 +00003264 // Parse the jump table pairs.
3265 SmallPtrSet<Value*, 32> SeenCases;
3266 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3267 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003268 Value *Constant;
3269 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003270
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3272 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003273 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003274 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 if (!SeenCases.insert(Constant))
3277 return Error(CondLoc, "duplicate case value in switch");
3278 if (!isa<ConstantInt>(Constant))
3279 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003280
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003281 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003282 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003283
Chris Lattnerdf986172009-01-02 07:01:27 +00003284 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003285
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003286 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003287 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3288 SI->addCase(Table[i].first, Table[i].second);
3289 Inst = SI;
3290 return false;
3291}
3292
Chris Lattnerab21db72009-10-28 00:19:10 +00003293/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003294/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003295/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3296bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003297 LocTy AddrLoc;
3298 Value *Address;
3299 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003300 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3301 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003302 return true;
3303
Duncan Sands1df98592010-02-16 11:11:14 +00003304 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003305 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003306
3307 // Parse the destination list.
3308 SmallVector<BasicBlock*, 16> DestList;
3309
3310 if (Lex.getKind() != lltok::rsquare) {
3311 BasicBlock *DestBB;
3312 if (ParseTypeAndBasicBlock(DestBB, PFS))
3313 return true;
3314 DestList.push_back(DestBB);
3315
3316 while (EatIfPresent(lltok::comma)) {
3317 if (ParseTypeAndBasicBlock(DestBB, PFS))
3318 return true;
3319 DestList.push_back(DestBB);
3320 }
3321 }
3322
3323 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3324 return true;
3325
Chris Lattnerab21db72009-10-28 00:19:10 +00003326 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003327 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3328 IBI->addDestination(DestList[i]);
3329 Inst = IBI;
3330 return false;
3331}
3332
3333
Chris Lattnerdf986172009-01-02 07:01:27 +00003334/// ParseInvoke
3335/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3336/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3337bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3338 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003339 unsigned RetAttrs, FnAttrs;
3340 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003341 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003342 LocTy RetTypeLoc;
3343 ValID CalleeID;
3344 SmallVector<ParamInfo, 16> ArgList;
3345
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003346 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003347 if (ParseOptionalCallingConv(CC) ||
3348 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003349 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003350 ParseValID(CalleeID) ||
3351 ParseParameterList(ArgList, PFS) ||
3352 ParseOptionalAttrs(FnAttrs, 2) ||
3353 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003354 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003355 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003356 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003357 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003358
Chris Lattnerdf986172009-01-02 07:01:27 +00003359 // If RetType is a non-function pointer type, then this is the short syntax
3360 // for the call, which means that RetType is just the return type. Infer the
3361 // rest of the function argument types from the arguments that are present.
3362 const PointerType *PFTy = 0;
3363 const FunctionType *Ty = 0;
3364 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3365 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3366 // Pull out the types of all of the arguments...
3367 std::vector<const Type*> ParamTypes;
3368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3369 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003370
Chris Lattnerdf986172009-01-02 07:01:27 +00003371 if (!FunctionType::isValidReturnType(RetType))
3372 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003373
Owen Andersondebcb012009-07-29 22:17:13 +00003374 Ty = FunctionType::get(RetType, ParamTypes, false);
3375 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003377
Chris Lattnerdf986172009-01-02 07:01:27 +00003378 // Look up the callee.
3379 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003380 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003381
Chris Lattnerdf986172009-01-02 07:01:27 +00003382 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3383 // function attributes.
3384 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3385 if (FnAttrs & ObsoleteFuncAttrs) {
3386 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3387 FnAttrs &= ~ObsoleteFuncAttrs;
3388 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 // Set up the Attributes for the function.
3391 SmallVector<AttributeWithIndex, 8> Attrs;
3392 if (RetAttrs != Attribute::None)
3393 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003396
Chris Lattnerdf986172009-01-02 07:01:27 +00003397 // Loop through FunctionType's arguments and ensure they are specified
3398 // correctly. Also, gather any parameter attributes.
3399 FunctionType::param_iterator I = Ty->param_begin();
3400 FunctionType::param_iterator E = Ty->param_end();
3401 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3402 const Type *ExpectedTy = 0;
3403 if (I != E) {
3404 ExpectedTy = *I++;
3405 } else if (!Ty->isVarArg()) {
3406 return Error(ArgList[i].Loc, "too many arguments specified");
3407 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003408
Chris Lattnerdf986172009-01-02 07:01:27 +00003409 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3410 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3411 ExpectedTy->getDescription() + "'");
3412 Args.push_back(ArgList[i].V);
3413 if (ArgList[i].Attrs != Attribute::None)
3414 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3415 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003416
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 if (I != E)
3418 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003419
Chris Lattnerdf986172009-01-02 07:01:27 +00003420 if (FnAttrs != Attribute::None)
3421 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003422
Chris Lattnerdf986172009-01-02 07:01:27 +00003423 // Finish off the Attributes and check them
3424 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003425
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003426 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003427 Args.begin(), Args.end());
3428 II->setCallingConv(CC);
3429 II->setAttributes(PAL);
3430 Inst = II;
3431 return false;
3432}
3433
3434
3435
3436//===----------------------------------------------------------------------===//
3437// Binary Operators.
3438//===----------------------------------------------------------------------===//
3439
3440/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003441/// ::= ArithmeticOps TypeAndValue ',' Value
3442///
3443/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3444/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003445bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003446 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 LocTy Loc; Value *LHS, *RHS;
3448 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3449 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3450 ParseValue(LHS->getType(), RHS, PFS))
3451 return true;
3452
Chris Lattnere914b592009-01-05 08:24:46 +00003453 bool Valid;
3454 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003455 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003456 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003457 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3458 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003459 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003460 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3461 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003462 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003463
Chris Lattnere914b592009-01-05 08:24:46 +00003464 if (!Valid)
3465 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003466
Chris Lattnerdf986172009-01-02 07:01:27 +00003467 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3468 return false;
3469}
3470
3471/// ParseLogical
3472/// ::= ArithmeticOps TypeAndValue ',' Value {
3473bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3474 unsigned Opc) {
3475 LocTy Loc; Value *LHS, *RHS;
3476 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3478 ParseValue(LHS->getType(), RHS, PFS))
3479 return true;
3480
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003481 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003482 return Error(Loc,"instruction requires integer or integer vector operands");
3483
3484 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3485 return false;
3486}
3487
3488
3489/// ParseCompare
3490/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3491/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003492bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3493 unsigned Opc) {
3494 // Parse the integer/fp comparison predicate.
3495 LocTy Loc;
3496 unsigned Pred;
3497 Value *LHS, *RHS;
3498 if (ParseCmpPredicate(Pred, Opc) ||
3499 ParseTypeAndValue(LHS, Loc, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after compare value") ||
3501 ParseValue(LHS->getType(), RHS, PFS))
3502 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003503
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003505 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003507 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003508 } else {
3509 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003510 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003511 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003512 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003513 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003514 }
3515 return false;
3516}
3517
3518//===----------------------------------------------------------------------===//
3519// Other Instructions.
3520//===----------------------------------------------------------------------===//
3521
3522
3523/// ParseCast
3524/// ::= CastOpc TypeAndValue 'to' Type
3525bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3526 unsigned Opc) {
3527 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003528 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003529 if (ParseTypeAndValue(Op, Loc, PFS) ||
3530 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3531 ParseType(DestTy))
3532 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003533
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003534 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3535 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003536 return Error(Loc, "invalid cast opcode for cast from '" +
3537 Op->getType()->getDescription() + "' to '" +
3538 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003539 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3541 return false;
3542}
3543
3544/// ParseSelect
3545/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3546bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3547 LocTy Loc;
3548 Value *Op0, *Op1, *Op2;
3549 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3550 ParseToken(lltok::comma, "expected ',' after select condition") ||
3551 ParseTypeAndValue(Op1, PFS) ||
3552 ParseToken(lltok::comma, "expected ',' after select value") ||
3553 ParseTypeAndValue(Op2, PFS))
3554 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003555
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3557 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003558
Chris Lattnerdf986172009-01-02 07:01:27 +00003559 Inst = SelectInst::Create(Op0, Op1, Op2);
3560 return false;
3561}
3562
Chris Lattner0088a5c2009-01-05 08:18:44 +00003563/// ParseVA_Arg
3564/// ::= 'va_arg' TypeAndValue ',' Type
3565bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003566 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003567 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003568 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003569 if (ParseTypeAndValue(Op, PFS) ||
3570 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003571 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003572 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003573
Chris Lattner0088a5c2009-01-05 08:18:44 +00003574 if (!EltTy->isFirstClassType())
3575 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003576
3577 Inst = new VAArgInst(Op, EltTy);
3578 return false;
3579}
3580
3581/// ParseExtractElement
3582/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3583bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3584 LocTy Loc;
3585 Value *Op0, *Op1;
3586 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3587 ParseToken(lltok::comma, "expected ',' after extract value") ||
3588 ParseTypeAndValue(Op1, PFS))
3589 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003590
Chris Lattnerdf986172009-01-02 07:01:27 +00003591 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3592 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003593
Eric Christophera3500da2009-07-25 02:28:41 +00003594 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003595 return false;
3596}
3597
3598/// ParseInsertElement
3599/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3600bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3601 LocTy Loc;
3602 Value *Op0, *Op1, *Op2;
3603 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3604 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3605 ParseTypeAndValue(Op1, PFS) ||
3606 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3607 ParseTypeAndValue(Op2, PFS))
3608 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003611 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003612
Chris Lattnerdf986172009-01-02 07:01:27 +00003613 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3614 return false;
3615}
3616
3617/// ParseShuffleVector
3618/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3619bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3620 LocTy Loc;
3621 Value *Op0, *Op1, *Op2;
3622 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3623 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3624 ParseTypeAndValue(Op1, PFS) ||
3625 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3626 ParseTypeAndValue(Op2, PFS))
3627 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003628
Chris Lattnerdf986172009-01-02 07:01:27 +00003629 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3630 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003631
Chris Lattnerdf986172009-01-02 07:01:27 +00003632 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3633 return false;
3634}
3635
3636/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003637/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003638int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003639 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 Value *Op0, *Op1;
3641 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003642
Chris Lattnerdf986172009-01-02 07:01:27 +00003643 if (ParseType(Ty) ||
3644 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3645 ParseValue(Ty, Op0, PFS) ||
3646 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003647 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003648 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3649 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003650
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003651 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003652 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3653 while (1) {
3654 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003655
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003656 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003657 break;
3658
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003659 if (Lex.getKind() == lltok::MetadataVar) {
3660 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003661 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003662 }
Devang Patela43d46f2009-10-16 18:45:49 +00003663
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003664 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 ParseValue(Ty, Op0, PFS) ||
3666 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003667 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3669 return true;
3670 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003671
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 if (!Ty->isFirstClassType())
3673 return Error(TypeLoc, "phi node must have first class type");
3674
3675 PHINode *PN = PHINode::Create(Ty);
3676 PN->reserveOperandSpace(PHIVals.size());
3677 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3678 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3679 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003680 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003681}
3682
3683/// ParseCall
3684/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3685/// ParameterList OptionalAttrs
3686bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3687 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003688 unsigned RetAttrs, FnAttrs;
3689 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003690 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 LocTy RetTypeLoc;
3692 ValID CalleeID;
3693 SmallVector<ParamInfo, 16> ArgList;
3694 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003695
Chris Lattnerdf986172009-01-02 07:01:27 +00003696 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3697 ParseOptionalCallingConv(CC) ||
3698 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003699 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003700 ParseValID(CalleeID) ||
3701 ParseParameterList(ArgList, PFS) ||
3702 ParseOptionalAttrs(FnAttrs, 2))
3703 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003704
Chris Lattnerdf986172009-01-02 07:01:27 +00003705 // If RetType is a non-function pointer type, then this is the short syntax
3706 // for the call, which means that RetType is just the return type. Infer the
3707 // rest of the function argument types from the arguments that are present.
3708 const PointerType *PFTy = 0;
3709 const FunctionType *Ty = 0;
3710 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3711 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3712 // Pull out the types of all of the arguments...
3713 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003714 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3715 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003716
Chris Lattnerdf986172009-01-02 07:01:27 +00003717 if (!FunctionType::isValidReturnType(RetType))
3718 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003719
Owen Andersondebcb012009-07-29 22:17:13 +00003720 Ty = FunctionType::get(RetType, ParamTypes, false);
3721 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003723
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 // Look up the callee.
3725 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003726 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003727
Chris Lattnerdf986172009-01-02 07:01:27 +00003728 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3729 // function attributes.
3730 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3731 if (FnAttrs & ObsoleteFuncAttrs) {
3732 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3733 FnAttrs &= ~ObsoleteFuncAttrs;
3734 }
3735
3736 // Set up the Attributes for the function.
3737 SmallVector<AttributeWithIndex, 8> Attrs;
3738 if (RetAttrs != Attribute::None)
3739 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003740
Chris Lattnerdf986172009-01-02 07:01:27 +00003741 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003742
Chris Lattnerdf986172009-01-02 07:01:27 +00003743 // Loop through FunctionType's arguments and ensure they are specified
3744 // correctly. Also, gather any parameter attributes.
3745 FunctionType::param_iterator I = Ty->param_begin();
3746 FunctionType::param_iterator E = Ty->param_end();
3747 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3748 const Type *ExpectedTy = 0;
3749 if (I != E) {
3750 ExpectedTy = *I++;
3751 } else if (!Ty->isVarArg()) {
3752 return Error(ArgList[i].Loc, "too many arguments specified");
3753 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003754
Chris Lattnerdf986172009-01-02 07:01:27 +00003755 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3756 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3757 ExpectedTy->getDescription() + "'");
3758 Args.push_back(ArgList[i].V);
3759 if (ArgList[i].Attrs != Attribute::None)
3760 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003762
Chris Lattnerdf986172009-01-02 07:01:27 +00003763 if (I != E)
3764 return Error(CallLoc, "not enough parameters specified for call");
3765
3766 if (FnAttrs != Attribute::None)
3767 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3768
3769 // Finish off the Attributes and check them
3770 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003771
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3773 CI->setTailCall(isTail);
3774 CI->setCallingConv(CC);
3775 CI->setAttributes(PAL);
3776 Inst = CI;
3777 return false;
3778}
3779
3780//===----------------------------------------------------------------------===//
3781// Memory Instructions.
3782//===----------------------------------------------------------------------===//
3783
3784/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003785/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3786/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003787int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3788 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003789 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003790 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003791 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003792 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003793 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003794
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003795 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003796 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003797 if (Lex.getKind() == lltok::kw_align) {
3798 if (ParseOptionalAlignment(Alignment)) return true;
3799 } else if (Lex.getKind() == lltok::MetadataVar) {
3800 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003801 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003802 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3803 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3804 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003805 }
3806 }
3807
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003808 if (Size && !Size->getType()->isIntegerTy())
3809 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003810
Victor Hernandez68afa542009-10-21 19:11:40 +00003811 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003812 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003813 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003814 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003815
3816 // Autoupgrade old malloc instruction to malloc call.
3817 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003818 if (Size && !Size->getType()->isIntegerTy(32))
3819 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003820 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003821 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3822 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003823 if (!MallocF)
3824 // Prototype malloc as "void *(int32)".
3825 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003826 MallocF = cast<Function>(
3827 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003828 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003829return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003830}
3831
3832/// ParseFree
3833/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003834bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3835 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003836 Value *Val; LocTy Loc;
3837 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003838 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003839 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003840 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003841 return false;
3842}
3843
3844/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003845/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003846int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3847 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003848 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003849 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003850 bool AteExtraComma = false;
3851 if (ParseTypeAndValue(Val, Loc, PFS) ||
3852 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3853 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003854
Duncan Sands1df98592010-02-16 11:11:14 +00003855 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003856 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3857 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003858
Chris Lattnerdf986172009-01-02 07:01:27 +00003859 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003860 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003861}
3862
3863/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003864/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003865int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3866 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003867 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003868 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003869 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003870 if (ParseTypeAndValue(Val, Loc, PFS) ||
3871 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003872 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3873 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003874 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003875
Duncan Sands1df98592010-02-16 11:11:14 +00003876 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003877 return Error(PtrLoc, "store operand must be a pointer");
3878 if (!Val->getType()->isFirstClassType())
3879 return Error(Loc, "store operand must be a first class value");
3880 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3881 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003882
Chris Lattnerdf986172009-01-02 07:01:27 +00003883 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003884 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003885}
3886
3887/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003888/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003889/// FIXME: Remove support for getresult in LLVM 3.0
3890bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3891 Value *Val; LocTy ValLoc, EltLoc;
3892 unsigned Element;
3893 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3894 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003895 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003896 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003897
Duncan Sands1df98592010-02-16 11:11:14 +00003898 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003899 return Error(ValLoc, "getresult inst requires an aggregate operand");
3900 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3901 return Error(EltLoc, "invalid getresult index for value");
3902 Inst = ExtractValueInst::Create(Val, Element);
3903 return false;
3904}
3905
3906/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003907/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003908int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003909 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003910
Dan Gohmandcb40a32009-07-29 15:58:36 +00003911 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003912
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003913 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003914
Duncan Sands1df98592010-02-16 11:11:14 +00003915 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003916 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003917
Chris Lattnerdf986172009-01-02 07:01:27 +00003918 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003919 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003920 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003921 if (Lex.getKind() == lltok::MetadataVar) {
3922 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003923 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003924 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003925 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003926 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003927 return Error(EltLoc, "getelementptr index must be an integer");
3928 Indices.push_back(Val);
3929 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003930
Chris Lattnerdf986172009-01-02 07:01:27 +00003931 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3932 Indices.begin(), Indices.end()))
3933 return Error(Loc, "invalid getelementptr indices");
3934 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003935 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003936 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003937 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003938}
3939
3940/// ParseExtractValue
3941/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003942int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003943 Value *Val; LocTy Loc;
3944 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003945 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003946 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003947 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003948 return true;
3949
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003950 if (!Val->getType()->isAggregateType())
3951 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003952
3953 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3954 Indices.end()))
3955 return Error(Loc, "invalid indices for extractvalue");
3956 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003957 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003958}
3959
3960/// ParseInsertValue
3961/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003962int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003963 Value *Val0, *Val1; LocTy Loc0, Loc1;
3964 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003965 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003966 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3967 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3968 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003969 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003970 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003971
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003972 if (!Val0->getType()->isAggregateType())
3973 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003974
Chris Lattnerdf986172009-01-02 07:01:27 +00003975 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3976 Indices.end()))
3977 return Error(Loc0, "invalid indices for insertvalue");
3978 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003979 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003980}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003981
3982//===----------------------------------------------------------------------===//
3983// Embedded metadata.
3984//===----------------------------------------------------------------------===//
3985
3986/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003987/// ::= Element (',' Element)*
3988/// Element
3989/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003990bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003991 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003992 // Check for an empty list.
3993 if (Lex.getKind() == lltok::rbrace)
3994 return false;
3995
Nick Lewycky21cc4462009-04-04 07:22:01 +00003996 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003997 // Null is a special case since it is typeless.
3998 if (EatIfPresent(lltok::kw_null)) {
3999 Elts.push_back(0);
4000 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004001 }
Chris Lattnera7352392009-12-30 04:42:57 +00004002
4003 Value *V = 0;
4004 PATypeHolder Ty(Type::getVoidTy(Context));
4005 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00004006 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00004007 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00004008 return true;
4009
Nick Lewyckycb337992009-05-10 20:57:05 +00004010 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004011 } while (EatIfPresent(lltok::comma));
4012
4013 return false;
4014}