blob: 3948071c420546c52ce1d688a3eb78493d330307 [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.
Chris Lattner42991ee2009-12-29 22:01:50 +0000520
521 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000523 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000526
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000530 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000531 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532}
Devang Patel256be962009-07-20 19:00:08 +0000533
Chris Lattner84d03b12009-12-29 22:35:39 +0000534/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000535/// !foo = !{ !1, !2 }
536bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000537 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000538 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000539 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000540
Chris Lattner84d03b12009-12-29 22:35:39 +0000541 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000542 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000543 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000544 return true;
545
Devang Patel3e30c2a2010-01-05 20:41:31 +0000546 SmallVector<MDNode *, 8> Elts;
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000547 if (Lex.getKind() != lltok::rbrace)
548 do {
549 // Null is a special case since it is typeless.
550 if (EatIfPresent(lltok::kw_null)) {
551 Elts.push_back(0);
552 continue;
553 }
Devang Patel69d02e02010-01-05 21:47:32 +0000554
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000555 if (ParseToken(lltok::exclaim, "Expected '!' here"))
556 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000557
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000558 MDNode *N = 0;
559 if (ParseMDNodeID(N)) return true;
560 Elts.push_back(N);
561 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000562
563 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
564 return true;
565
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000567 return false;
568}
569
Devang Patel923078c2009-07-01 19:21:12 +0000570/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000571/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000572bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000573 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000574 Lex.Lex();
575 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000576
577 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000578 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000579 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000580 if (ParseUInt32(MetadataID) ||
581 ParseToken(lltok::equal, "expected '=' here") ||
582 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000583 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000584 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000585 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000586 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000587 return true;
588
Owen Anderson647e3012009-07-31 21:35:40 +0000589 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000590
591 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000592 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000593 FI = ForwardRefMDNodes.find(MetadataID);
594 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000595 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000596 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000597
598 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
599 } else {
600 if (MetadataID >= NumberedMetadata.size())
601 NumberedMetadata.resize(MetadataID+1);
602
603 if (NumberedMetadata[MetadataID] != 0)
604 return TokError("Metadata id is already used");
605 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000606 }
607
Devang Patel923078c2009-07-01 19:21:12 +0000608 return false;
609}
610
Chris Lattnerdf986172009-01-02 07:01:27 +0000611/// ParseAlias:
612/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
613/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000614/// ::= TypeAndValue
615/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000616/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000617///
618/// Everything through visibility has already been parsed.
619///
620bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
621 unsigned Visibility) {
622 assert(Lex.getKind() == lltok::kw_alias);
623 Lex.Lex();
624 unsigned Linkage;
625 LocTy LinkageLoc = Lex.getLoc();
626 if (ParseOptionalLinkage(Linkage))
627 return true;
628
629 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000630 Linkage != GlobalValue::WeakAnyLinkage &&
631 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000632 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000633 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000634 Linkage != GlobalValue::LinkerPrivateLinkage &&
635 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000636 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000637
Chris Lattnerdf986172009-01-02 07:01:27 +0000638 Constant *Aliasee;
639 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000640 if (Lex.getKind() != lltok::kw_bitcast &&
641 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000642 if (ParseGlobalTypeAndValue(Aliasee)) return true;
643 } else {
644 // The bitcast dest type is not present, it is implied by the dest type.
645 ValID ID;
646 if (ParseValID(ID)) return true;
647 if (ID.Kind != ValID::t_Constant)
648 return Error(AliaseeLoc, "invalid aliasee");
649 Aliasee = ID.ConstantVal;
650 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000651
Duncan Sands1df98592010-02-16 11:11:14 +0000652 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000653 return Error(AliaseeLoc, "alias must have pointer type");
654
655 // Okay, create the alias but do not insert it into the module yet.
656 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
657 (GlobalValue::LinkageTypes)Linkage, Name,
658 Aliasee);
659 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000660
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 // See if this value already exists in the symbol table. If so, it is either
662 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000663 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000664 // See if this was a redefinition. If so, there is no entry in
665 // ForwardRefVals.
666 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
667 I = ForwardRefVals.find(Name);
668 if (I == ForwardRefVals.end())
669 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
670
671 // Otherwise, this was a definition of forward ref. Verify that types
672 // agree.
673 if (Val->getType() != GA->getType())
674 return Error(NameLoc,
675 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 // If they agree, just RAUW the old value with the alias and remove the
678 // forward ref info.
679 Val->replaceAllUsesWith(GA);
680 Val->eraseFromParent();
681 ForwardRefVals.erase(I);
682 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000683
Chris Lattnerdf986172009-01-02 07:01:27 +0000684 // Insert into the module, we know its name won't collide now.
685 M->getAliasList().push_back(GA);
686 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000687
Chris Lattnerdf986172009-01-02 07:01:27 +0000688 return false;
689}
690
691/// ParseGlobal
692/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
693/// OptionalAddrSpace GlobalType Type Const
694/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
695/// OptionalAddrSpace GlobalType Type Const
696///
697/// Everything through visibility has been parsed already.
698///
699bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
700 unsigned Linkage, bool HasLinkage,
701 unsigned Visibility) {
702 unsigned AddrSpace;
703 bool ThreadLocal, IsConstant;
704 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000705
Owen Anderson1d0be152009-08-13 21:58:54 +0000706 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000707 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
708 ParseOptionalAddrSpace(AddrSpace) ||
709 ParseGlobalType(IsConstant) ||
710 ParseType(Ty, TyLoc))
711 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000712
Chris Lattnerdf986172009-01-02 07:01:27 +0000713 // If the linkage is specified and is external, then no initializer is
714 // present.
715 Constant *Init = 0;
716 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000717 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 Linkage != GlobalValue::ExternalLinkage)) {
719 if (ParseGlobalValue(Ty, Init))
720 return true;
721 }
722
Duncan Sands1df98592010-02-16 11:11:14 +0000723 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000724 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000725
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 GlobalVariable *GV = 0;
727
728 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000729 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000730 if (GlobalValue *GVal = M->getNamedValue(Name)) {
731 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
732 return Error(NameLoc, "redefinition of global '@" + Name + "'");
733 GV = cast<GlobalVariable>(GVal);
734 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000735 } else {
736 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
737 I = ForwardRefValIDs.find(NumberedVals.size());
738 if (I != ForwardRefValIDs.end()) {
739 GV = cast<GlobalVariable>(I->second.first);
740 ForwardRefValIDs.erase(I);
741 }
742 }
743
744 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000745 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000746 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000747 } else {
748 if (GV->getType()->getElementType() != Ty)
749 return Error(TyLoc,
750 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751
Chris Lattnerdf986172009-01-02 07:01:27 +0000752 // Move the forward-reference to the correct spot in the module.
753 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
754 }
755
756 if (Name.empty())
757 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 // Set the parsed properties on the global.
760 if (Init)
761 GV->setInitializer(Init);
762 GV->setConstant(IsConstant);
763 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
764 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
765 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766
Chris Lattnerdf986172009-01-02 07:01:27 +0000767 // Parse attributes on the global.
768 while (Lex.getKind() == lltok::comma) {
769 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Chris Lattnerdf986172009-01-02 07:01:27 +0000771 if (Lex.getKind() == lltok::kw_section) {
772 Lex.Lex();
773 GV->setSection(Lex.getStrVal());
774 if (ParseToken(lltok::StringConstant, "expected global section string"))
775 return true;
776 } else if (Lex.getKind() == lltok::kw_align) {
777 unsigned Alignment;
778 if (ParseOptionalAlignment(Alignment)) return true;
779 GV->setAlignment(Alignment);
780 } else {
781 TokError("unknown global variable property!");
782 }
783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 return false;
786}
787
788
789//===----------------------------------------------------------------------===//
790// GlobalValue Reference/Resolution Routines.
791//===----------------------------------------------------------------------===//
792
793/// GetGlobalVal - Get a value with the specified name or ID, creating a
794/// forward reference record if needed. This can return null if the value
795/// exists but does not have the right type.
796GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
797 LocTy Loc) {
798 const PointerType *PTy = dyn_cast<PointerType>(Ty);
799 if (PTy == 0) {
800 Error(Loc, "global variable reference must have pointer type");
801 return 0;
802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000803
Chris Lattnerdf986172009-01-02 07:01:27 +0000804 // Look this name up in the normal function symbol table.
805 GlobalValue *Val =
806 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Chris Lattnerdf986172009-01-02 07:01:27 +0000808 // If this is a forward reference for the value, see if we already created a
809 // forward ref record.
810 if (Val == 0) {
811 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
812 I = ForwardRefVals.find(Name);
813 if (I != ForwardRefVals.end())
814 Val = I->second.first;
815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000816
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 // If we have the value in the symbol table or fwd-ref table, return it.
818 if (Val) {
819 if (Val->getType() == Ty) return Val;
820 Error(Loc, "'@" + Name + "' defined with type '" +
821 Val->getType()->getDescription() + "'");
822 return 0;
823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Chris Lattnerdf986172009-01-02 07:01:27 +0000825 // Otherwise, create a new forward reference for this value and remember it.
826 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000827 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
828 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000829 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000830 Error(Loc, "function may not return opaque type");
831 return 0;
832 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000833
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000834 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000835 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000836 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
837 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000839
Chris Lattnerdf986172009-01-02 07:01:27 +0000840 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
841 return FwdVal;
842}
843
844GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
845 const PointerType *PTy = dyn_cast<PointerType>(Ty);
846 if (PTy == 0) {
847 Error(Loc, "global variable reference must have pointer type");
848 return 0;
849 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000850
Chris Lattnerdf986172009-01-02 07:01:27 +0000851 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000852
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 // If this is a forward reference for the value, see if we already created a
854 // forward ref record.
855 if (Val == 0) {
856 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
857 I = ForwardRefValIDs.find(ID);
858 if (I != ForwardRefValIDs.end())
859 Val = I->second.first;
860 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000861
Chris Lattnerdf986172009-01-02 07:01:27 +0000862 // If we have the value in the symbol table or fwd-ref table, return it.
863 if (Val) {
864 if (Val->getType() == Ty) return Val;
865 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
866 Val->getType()->getDescription() + "'");
867 return 0;
868 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000869
Chris Lattnerdf986172009-01-02 07:01:27 +0000870 // Otherwise, create a new forward reference for this value and remember it.
871 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000872 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
873 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000874 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000875 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000876 return 0;
877 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000878 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000879 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000880 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
881 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000882 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000883
Chris Lattnerdf986172009-01-02 07:01:27 +0000884 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
885 return FwdVal;
886}
887
888
889//===----------------------------------------------------------------------===//
890// Helper Routines.
891//===----------------------------------------------------------------------===//
892
893/// ParseToken - If the current token has the specified kind, eat it and return
894/// success. Otherwise, emit the specified error and return failure.
895bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
896 if (Lex.getKind() != T)
897 return TokError(ErrMsg);
898 Lex.Lex();
899 return false;
900}
901
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000902/// ParseStringConstant
903/// ::= StringConstant
904bool LLParser::ParseStringConstant(std::string &Result) {
905 if (Lex.getKind() != lltok::StringConstant)
906 return TokError("expected string constant");
907 Result = Lex.getStrVal();
908 Lex.Lex();
909 return false;
910}
911
912/// ParseUInt32
913/// ::= uint32
914bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
916 return TokError("expected integer");
917 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
918 if (Val64 != unsigned(Val64))
919 return TokError("expected 32-bit integer (too large)");
920 Val = Val64;
921 Lex.Lex();
922 return false;
923}
924
925
926/// ParseOptionalAddrSpace
927/// := /*empty*/
928/// := 'addrspace' '(' uint32 ')'
929bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
930 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000931 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000934 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000935 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000936}
Chris Lattnerdf986172009-01-02 07:01:27 +0000937
938/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
939/// indicates what kind of attribute list this is: 0: function arg, 1: result,
940/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000941/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000942bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
943 Attrs = Attribute::None;
944 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000945
Chris Lattnerdf986172009-01-02 07:01:27 +0000946 while (1) {
947 switch (Lex.getKind()) {
948 case lltok::kw_sext:
949 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000950 // Treat these as signext/zeroext if they occur in the argument list after
951 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
952 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
953 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000954 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000955 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000956 if (Lex.getKind() == lltok::kw_sext)
957 Attrs |= Attribute::SExt;
958 else
959 Attrs |= Attribute::ZExt;
960 break;
961 }
962 // FALL THROUGH.
963 default: // End of attributes.
964 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
965 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000966
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000967 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000969
Chris Lattnerdf986172009-01-02 07:01:27 +0000970 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000971 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
972 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
973 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
974 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
975 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
976 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
977 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
978 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000979
Devang Patel578efa92009-06-05 21:57:13 +0000980 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
981 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
982 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
983 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
984 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000985 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000986 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
987 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
988 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
989 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
990 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
991 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000992 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000993
Charles Davis1e063d12010-02-12 00:31:15 +0000994 case lltok::kw_alignstack: {
995 unsigned Alignment;
996 if (ParseOptionalStackAlignment(Alignment))
997 return true;
998 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
999 continue;
1000 }
1001
Chris Lattnerdf986172009-01-02 07:01:27 +00001002 case lltok::kw_align: {
1003 unsigned Alignment;
1004 if (ParseOptionalAlignment(Alignment))
1005 return true;
1006 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1007 continue;
1008 }
Charles Davis1e063d12010-02-12 00:31:15 +00001009
Chris Lattnerdf986172009-01-02 07:01:27 +00001010 }
1011 Lex.Lex();
1012 }
1013}
1014
1015/// ParseOptionalLinkage
1016/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001017/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001018/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001019/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001020/// ::= 'internal'
1021/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001022/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001023/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001024/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001025/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001026/// ::= 'appending'
1027/// ::= 'dllexport'
1028/// ::= 'common'
1029/// ::= 'dllimport'
1030/// ::= 'extern_weak'
1031/// ::= 'external'
1032bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1033 HasLinkage = false;
1034 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001035 default: Res=GlobalValue::ExternalLinkage; return false;
1036 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1037 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001038 case lltok::kw_linker_private_weak:
1039 Res = GlobalValue::LinkerPrivateWeakLinkage;
1040 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001041 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1042 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1043 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1044 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1045 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001046 case lltok::kw_available_externally:
1047 Res = GlobalValue::AvailableExternallyLinkage;
1048 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001049 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1050 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1051 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1052 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1053 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1054 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001055 }
1056 Lex.Lex();
1057 HasLinkage = true;
1058 return false;
1059}
1060
1061/// ParseOptionalVisibility
1062/// ::= /*empty*/
1063/// ::= 'default'
1064/// ::= 'hidden'
1065/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001066///
Chris Lattnerdf986172009-01-02 07:01:27 +00001067bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1068 switch (Lex.getKind()) {
1069 default: Res = GlobalValue::DefaultVisibility; return false;
1070 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1071 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1072 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1073 }
1074 Lex.Lex();
1075 return false;
1076}
1077
1078/// ParseOptionalCallingConv
1079/// ::= /*empty*/
1080/// ::= 'ccc'
1081/// ::= 'fastcc'
1082/// ::= 'coldcc'
1083/// ::= 'x86_stdcallcc'
1084/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001085/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001086/// ::= 'arm_apcscc'
1087/// ::= 'arm_aapcscc'
1088/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001089/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001090/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001091///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001092bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001093 switch (Lex.getKind()) {
1094 default: CC = CallingConv::C; return false;
1095 case lltok::kw_ccc: CC = CallingConv::C; break;
1096 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1097 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1098 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1099 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001100 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001101 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1102 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1103 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001104 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001105 case lltok::kw_cc: {
1106 unsigned ArbitraryCC;
1107 Lex.Lex();
1108 if (ParseUInt32(ArbitraryCC)) {
1109 return true;
1110 } else
1111 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1112 return false;
1113 }
1114 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001116
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 Lex.Lex();
1118 return false;
1119}
1120
Chris Lattnerb8c46862009-12-30 05:31:19 +00001121/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001122/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattnerfe805242010-04-01 04:51:13 +00001123bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001124 do {
1125 if (Lex.getKind() != lltok::MetadataVar)
1126 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001127
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001128 std::string Name = Lex.getStrVal();
1129 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001130
Chris Lattner442ffa12009-12-29 21:53:55 +00001131 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001132 unsigned NodeID;
1133 SMLoc Loc = Lex.getLoc();
Chris Lattnere434d272009-12-30 04:56:59 +00001134 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner449c3102010-04-01 05:14:45 +00001135 ParseMDNodeID(Node, NodeID))
Chris Lattnere434d272009-12-30 04:56:59 +00001136 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001137
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001138 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner449c3102010-04-01 05:14:45 +00001139 if (Node) {
1140 // If we got the node, add it to the instruction.
1141 Inst->setMetadata(MDK, Node);
1142 } else {
1143 MDRef R = { Loc, MDK, NodeID };
1144 // Otherwise, remember that this should be resolved later.
1145 ForwardRefInstMetadata[Inst].push_back(R);
1146 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001147
1148 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001149 } while (EatIfPresent(lltok::comma));
1150 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001151}
1152
Chris Lattnerdf986172009-01-02 07:01:27 +00001153/// ParseOptionalAlignment
1154/// ::= /* empty */
1155/// ::= 'align' 4
1156bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1157 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001158 if (!EatIfPresent(lltok::kw_align))
1159 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001160 LocTy AlignLoc = Lex.getLoc();
1161 if (ParseUInt32(Alignment)) return true;
1162 if (!isPowerOf2_32(Alignment))
1163 return Error(AlignLoc, "alignment is not a power of two");
1164 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001165}
1166
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001167/// ParseOptionalCommaAlign
1168/// ::=
1169/// ::= ',' align 4
1170///
1171/// This returns with AteExtraComma set to true if it ate an excess comma at the
1172/// end.
1173bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1174 bool &AteExtraComma) {
1175 AteExtraComma = false;
1176 while (EatIfPresent(lltok::comma)) {
1177 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001178 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001179 AteExtraComma = true;
1180 return false;
1181 }
1182
Chris Lattner093eed12010-04-23 00:50:50 +00001183 if (Lex.getKind() != lltok::kw_align)
1184 return Error(Lex.getLoc(), "expected metadata or 'align'");
1185
1186 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001187 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001188
Devang Patelf633a062009-09-17 23:04:48 +00001189 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001190}
1191
Charles Davis1e063d12010-02-12 00:31:15 +00001192/// ParseOptionalStackAlignment
1193/// ::= /* empty */
1194/// ::= 'alignstack' '(' 4 ')'
1195bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1196 Alignment = 0;
1197 if (!EatIfPresent(lltok::kw_alignstack))
1198 return false;
1199 LocTy ParenLoc = Lex.getLoc();
1200 if (!EatIfPresent(lltok::lparen))
1201 return Error(ParenLoc, "expected '('");
1202 LocTy AlignLoc = Lex.getLoc();
1203 if (ParseUInt32(Alignment)) return true;
1204 ParenLoc = Lex.getLoc();
1205 if (!EatIfPresent(lltok::rparen))
1206 return Error(ParenLoc, "expected ')'");
1207 if (!isPowerOf2_32(Alignment))
1208 return Error(AlignLoc, "stack alignment is not a power of two");
1209 return false;
1210}
Devang Patelf633a062009-09-17 23:04:48 +00001211
Chris Lattner628c13a2009-12-30 05:14:00 +00001212/// ParseIndexList - This parses the index list for an insert/extractvalue
1213/// instruction. This sets AteExtraComma in the case where we eat an extra
1214/// comma at the end of the line and find that it is followed by metadata.
1215/// Clients that don't allow metadata can call the version of this function that
1216/// only takes one argument.
1217///
Chris Lattnerdf986172009-01-02 07:01:27 +00001218/// ParseIndexList
1219/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001220///
1221bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1222 bool &AteExtraComma) {
1223 AteExtraComma = false;
1224
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 if (Lex.getKind() != lltok::comma)
1226 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001227
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001228 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001229 if (Lex.getKind() == lltok::MetadataVar) {
1230 AteExtraComma = true;
1231 return false;
1232 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001233 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001234 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001235 Indices.push_back(Idx);
1236 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001237
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 return false;
1239}
1240
1241//===----------------------------------------------------------------------===//
1242// Type Parsing.
1243//===----------------------------------------------------------------------===//
1244
1245/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001246bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1247 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001249
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 // Verify no unresolved uprefs.
1251 if (!UpRefs.empty())
1252 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001253
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001254 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001255 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001256
Chris Lattnerdf986172009-01-02 07:01:27 +00001257 return false;
1258}
1259
1260/// HandleUpRefs - Every time we finish a new layer of types, this function is
1261/// called. It loops through the UpRefs vector, which is a list of the
1262/// currently active types. For each type, if the up-reference is contained in
1263/// the newly completed type, we decrement the level count. When the level
1264/// count reaches zero, the up-referenced type is the type that is passed in:
1265/// thus we can complete the cycle.
1266///
1267PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1268 // If Ty isn't abstract, or if there are no up-references in it, then there is
1269 // nothing to resolve here.
1270 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 PATypeHolder Ty(ty);
1273#if 0
David Greene0e28d762009-12-23 23:38:28 +00001274 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001275 << "' newly formed. Resolving upreferences.\n"
1276 << UpRefs.size() << " upreferences active!\n";
1277#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001278
Chris Lattnerdf986172009-01-02 07:01:27 +00001279 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1280 // to zero), we resolve them all together before we resolve them to Ty. At
1281 // the end of the loop, if there is anything to resolve to Ty, it will be in
1282 // this variable.
1283 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001284
Chris Lattnerdf986172009-01-02 07:01:27 +00001285 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1286 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1287 bool ContainsType =
1288 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1289 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290
Chris Lattnerdf986172009-01-02 07:01:27 +00001291#if 0
David Greene0e28d762009-12-23 23:38:28 +00001292 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1294 << (ContainsType ? "true" : "false")
1295 << " level=" << UpRefs[i].NestingLevel << "\n";
1296#endif
1297 if (!ContainsType)
1298 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001299
Chris Lattnerdf986172009-01-02 07:01:27 +00001300 // Decrement level of upreference
1301 unsigned Level = --UpRefs[i].NestingLevel;
1302 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001303
Chris Lattnerdf986172009-01-02 07:01:27 +00001304 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1305 if (Level != 0)
1306 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001307
Chris Lattnerdf986172009-01-02 07:01:27 +00001308#if 0
David Greene0e28d762009-12-23 23:38:28 +00001309 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001310#endif
1311 if (!TypeToResolve)
1312 TypeToResolve = UpRefs[i].UpRefTy;
1313 else
1314 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1315 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1316 --i; // Do not skip the next element.
1317 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001318
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 if (TypeToResolve)
1320 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001321
Chris Lattnerdf986172009-01-02 07:01:27 +00001322 return Ty;
1323}
1324
1325
1326/// ParseTypeRec - The recursive function used to process the internal
1327/// implementation details of types.
1328bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1329 switch (Lex.getKind()) {
1330 default:
1331 return TokError("expected type");
1332 case lltok::Type:
1333 // TypeRec ::= 'float' | 'void' (etc)
1334 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001335 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001336 break;
1337 case lltok::kw_opaque:
1338 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001339 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 Lex.Lex();
1341 break;
1342 case lltok::lbrace:
1343 // TypeRec ::= '{' ... '}'
1344 if (ParseStructType(Result, false))
1345 return true;
1346 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001347 case lltok::kw_union:
1348 // TypeRec ::= 'union' '{' ... '}'
1349 if (ParseUnionType(Result))
1350 return true;
1351 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 case lltok::lsquare:
1353 // TypeRec ::= '[' ... ']'
1354 Lex.Lex(); // eat the lsquare.
1355 if (ParseArrayVectorType(Result, false))
1356 return true;
1357 break;
1358 case lltok::less: // Either vector or packed struct.
1359 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001360 Lex.Lex();
1361 if (Lex.getKind() == lltok::lbrace) {
1362 if (ParseStructType(Result, true) ||
1363 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 } else if (ParseArrayVectorType(Result, true))
1366 return true;
1367 break;
1368 case lltok::LocalVar:
1369 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1370 // TypeRec ::= %foo
1371 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1372 Result = T;
1373 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001374 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001375 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1376 std::make_pair(Result,
1377 Lex.getLoc())));
1378 M->addTypeName(Lex.getStrVal(), Result.get());
1379 }
1380 Lex.Lex();
1381 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001382
Chris Lattnerdf986172009-01-02 07:01:27 +00001383 case lltok::LocalVarID:
1384 // TypeRec ::= %4
1385 if (Lex.getUIntVal() < NumberedTypes.size())
1386 Result = NumberedTypes[Lex.getUIntVal()];
1387 else {
1388 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1389 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1390 if (I != ForwardRefTypeIDs.end())
1391 Result = I->second.first;
1392 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001393 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1395 std::make_pair(Result,
1396 Lex.getLoc())));
1397 }
1398 }
1399 Lex.Lex();
1400 break;
1401 case lltok::backslash: {
1402 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001403 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001404 unsigned Val;
1405 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001406 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1408 Result = OT;
1409 break;
1410 }
1411 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001412
1413 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001414 while (1) {
1415 switch (Lex.getKind()) {
1416 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001417 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001418
1419 // TypeRec ::= TypeRec '*'
1420 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001421 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001422 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001423 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001424 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001425 if (!PointerType::isValidElementType(Result.get()))
1426 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001427 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 Lex.Lex();
1429 break;
1430
1431 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1432 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001433 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001434 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001435 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001436 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001437 if (!PointerType::isValidElementType(Result.get()))
1438 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 unsigned AddrSpace;
1440 if (ParseOptionalAddrSpace(AddrSpace) ||
1441 ParseToken(lltok::star, "expected '*' in address space"))
1442 return true;
1443
Owen Andersondebcb012009-07-29 22:17:13 +00001444 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 break;
1446 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001447
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1449 case lltok::lparen:
1450 if (ParseFunctionType(Result))
1451 return true;
1452 break;
1453 }
1454 }
1455}
1456
1457/// ParseParameterList
1458/// ::= '(' ')'
1459/// ::= '(' Arg (',' Arg)* ')'
1460/// Arg
1461/// ::= Type OptionalAttributes Value OptionalAttributes
1462bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1463 PerFunctionState &PFS) {
1464 if (ParseToken(lltok::lparen, "expected '(' in call"))
1465 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001466
Chris Lattnerdf986172009-01-02 07:01:27 +00001467 while (Lex.getKind() != lltok::rparen) {
1468 // If this isn't the first argument, we need a comma.
1469 if (!ArgList.empty() &&
1470 ParseToken(lltok::comma, "expected ',' in argument list"))
1471 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001472
Chris Lattnerdf986172009-01-02 07:01:27 +00001473 // Parse the argument.
1474 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001475 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001476 unsigned ArgAttrs1 = Attribute::None;
1477 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001478 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001479 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001480 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001481
Chris Lattner287881d2009-12-30 02:11:14 +00001482 // Otherwise, handle normal operands.
1483 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1484 ParseValue(ArgTy, V, PFS) ||
1485 // FIXME: Should not allow attributes after the argument, remove this
1486 // in LLVM 3.0.
1487 ParseOptionalAttrs(ArgAttrs2, 3))
1488 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001489 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1490 }
1491
1492 Lex.Lex(); // Lex the ')'.
1493 return false;
1494}
1495
1496
1497
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001498/// ParseArgumentList - Parse the argument list for a function type or function
1499/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001500/// ::= '(' ArgTypeListI ')'
1501/// ArgTypeListI
1502/// ::= /*empty*/
1503/// ::= '...'
1504/// ::= ArgTypeList ',' '...'
1505/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001506///
Chris Lattnerdf986172009-01-02 07:01:27 +00001507bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001508 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001509 isVarArg = false;
1510 assert(Lex.getKind() == lltok::lparen);
1511 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattnerdf986172009-01-02 07:01:27 +00001513 if (Lex.getKind() == lltok::rparen) {
1514 // empty
1515 } else if (Lex.getKind() == lltok::dotdotdot) {
1516 isVarArg = true;
1517 Lex.Lex();
1518 } else {
1519 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001520 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001521 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001524 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1525 // types (such as a function returning a pointer to itself). If parsing a
1526 // function prototype, we require fully resolved types.
1527 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001528 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001529
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001530 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001531 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001532
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 if (Lex.getKind() == lltok::LocalVar ||
1534 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1535 Name = Lex.getStrVal();
1536 Lex.Lex();
1537 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001538
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001539 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001540 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001544 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001545 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001546 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001547 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001548 break;
1549 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Chris Lattnerdf986172009-01-02 07:01:27 +00001551 // Otherwise must be an argument type.
1552 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001553 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001554 ParseOptionalAttrs(Attrs, 0)) return true;
1555
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001556 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001557 return Error(TypeLoc, "argument can not have void type");
1558
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 if (Lex.getKind() == lltok::LocalVar ||
1560 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1561 Name = Lex.getStrVal();
1562 Lex.Lex();
1563 } else {
1564 Name = "";
1565 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001566
Duncan Sands47c51882010-02-16 14:50:09 +00001567 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001568 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001569
Chris Lattnerdf986172009-01-02 07:01:27 +00001570 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1571 }
1572 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001573
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001574 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001575}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Chris Lattnerdf986172009-01-02 07:01:27 +00001577/// ParseFunctionType
1578/// ::= Type ArgumentList OptionalAttrs
1579bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1580 assert(Lex.getKind() == lltok::lparen);
1581
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001582 if (!FunctionType::isValidReturnType(Result))
1583 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001584
Chris Lattnerdf986172009-01-02 07:01:27 +00001585 std::vector<ArgInfo> ArgList;
1586 bool isVarArg;
1587 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001588 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001589 // FIXME: Allow, but ignore attributes on function types!
1590 // FIXME: Remove in LLVM 3.0
1591 ParseOptionalAttrs(Attrs, 2))
1592 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001593
Chris Lattnerdf986172009-01-02 07:01:27 +00001594 // Reject names on the arguments lists.
1595 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1596 if (!ArgList[i].Name.empty())
1597 return Error(ArgList[i].Loc, "argument name invalid in function type");
1598 if (!ArgList[i].Attrs != 0) {
1599 // Allow but ignore attributes on function types; this permits
1600 // auto-upgrade.
1601 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1602 }
1603 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001604
Chris Lattnerdf986172009-01-02 07:01:27 +00001605 std::vector<const Type*> ArgListTy;
1606 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1607 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001608
Owen Andersondebcb012009-07-29 22:17:13 +00001609 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001610 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001611 return false;
1612}
1613
1614/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1615/// TypeRec
1616/// ::= '{' '}'
1617/// ::= '{' TypeRec (',' TypeRec)* '}'
1618/// ::= '<' '{' '}' '>'
1619/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1620bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1621 assert(Lex.getKind() == lltok::lbrace);
1622 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001623
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001624 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001625 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001626 return false;
1627 }
1628
1629 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001630 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001631 if (ParseTypeRec(Result)) return true;
1632 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001634 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001635 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001636 if (!StructType::isValidElementType(Result))
1637 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001639 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001640 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001643 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001644 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001645 if (!StructType::isValidElementType(Result))
1646 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 ParamsList.push_back(Result);
1649 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001650
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001651 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1652 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001653
Chris Lattnerdf986172009-01-02 07:01:27 +00001654 std::vector<const Type*> ParamsListTy;
1655 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1656 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001657 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001658 return false;
1659}
1660
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001661/// ParseUnionType
1662/// TypeRec
1663/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1664bool LLParser::ParseUnionType(PATypeHolder &Result) {
1665 assert(Lex.getKind() == lltok::kw_union);
1666 Lex.Lex(); // Consume the 'union'
1667
1668 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1669
1670 SmallVector<PATypeHolder, 8> ParamsList;
1671 do {
1672 LocTy EltTyLoc = Lex.getLoc();
1673 if (ParseTypeRec(Result)) return true;
1674 ParamsList.push_back(Result);
1675
1676 if (Result->isVoidTy())
1677 return Error(EltTyLoc, "union element can not have void type");
1678 if (!UnionType::isValidElementType(Result))
1679 return Error(EltTyLoc, "invalid element type for union");
1680
1681 } while (EatIfPresent(lltok::comma)) ;
1682
1683 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1684 return true;
1685
1686 SmallVector<const Type*, 8> ParamsListTy;
1687 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1688 ParamsListTy.push_back(ParamsList[i].get());
1689 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1690 return false;
1691}
1692
Chris Lattnerdf986172009-01-02 07:01:27 +00001693/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1694/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001695/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001696/// ::= '[' APSINTVAL 'x' Types ']'
1697/// ::= '<' APSINTVAL 'x' Types '>'
1698bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1699 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1700 Lex.getAPSIntVal().getBitWidth() > 64)
1701 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnerdf986172009-01-02 07:01:27 +00001703 LocTy SizeLoc = Lex.getLoc();
1704 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001705 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001706
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001707 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1708 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001709
1710 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001711 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001712 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001713
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001714 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001715 return Error(TypeLoc, "array and vector element type cannot be void");
1716
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001717 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1718 "expected end of sequential type"))
1719 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001722 if (Size == 0)
1723 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001724 if ((unsigned)Size != Size)
1725 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001726 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001727 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001728 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001729 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001730 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001731 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001732 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001733 }
1734 return false;
1735}
1736
1737//===----------------------------------------------------------------------===//
1738// Function Semantic Analysis.
1739//===----------------------------------------------------------------------===//
1740
Chris Lattner09d9ef42009-10-28 03:39:23 +00001741LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1742 int functionNumber)
1743 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001744
1745 // Insert unnamed arguments into the NumberedVals list.
1746 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1747 AI != E; ++AI)
1748 if (!AI->hasName())
1749 NumberedVals.push_back(AI);
1750}
1751
1752LLParser::PerFunctionState::~PerFunctionState() {
1753 // If there were any forward referenced non-basicblock values, delete them.
1754 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1755 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1756 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001757 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001758 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 delete I->second.first;
1760 I->second.first = 0;
1761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattnerdf986172009-01-02 07:01:27 +00001763 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1764 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1765 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001766 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001767 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001768 delete I->second.first;
1769 I->second.first = 0;
1770 }
1771}
1772
Chris Lattner09d9ef42009-10-28 03:39:23 +00001773bool LLParser::PerFunctionState::FinishFunction() {
1774 // Check to see if someone took the address of labels in this block.
1775 if (!P.ForwardRefBlockAddresses.empty()) {
1776 ValID FunctionID;
1777 if (!F.getName().empty()) {
1778 FunctionID.Kind = ValID::t_GlobalName;
1779 FunctionID.StrVal = F.getName();
1780 } else {
1781 FunctionID.Kind = ValID::t_GlobalID;
1782 FunctionID.UIntVal = FunctionNumber;
1783 }
1784
1785 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1786 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1787 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1788 // Resolve all these references.
1789 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1790 return true;
1791
1792 P.ForwardRefBlockAddresses.erase(FRBAI);
1793 }
1794 }
1795
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 if (!ForwardRefVals.empty())
1797 return P.Error(ForwardRefVals.begin()->second.second,
1798 "use of undefined value '%" + ForwardRefVals.begin()->first +
1799 "'");
1800 if (!ForwardRefValIDs.empty())
1801 return P.Error(ForwardRefValIDs.begin()->second.second,
1802 "use of undefined value '%" +
1803 utostr(ForwardRefValIDs.begin()->first) + "'");
1804 return false;
1805}
1806
1807
1808/// GetVal - Get a value with the specified name or ID, creating a
1809/// forward reference record if needed. This can return null if the value
1810/// exists but does not have the right type.
1811Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1812 const Type *Ty, LocTy Loc) {
1813 // Look this name up in the normal function symbol table.
1814 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815
Chris Lattnerdf986172009-01-02 07:01:27 +00001816 // If this is a forward reference for the value, see if we already created a
1817 // forward ref record.
1818 if (Val == 0) {
1819 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1820 I = ForwardRefVals.find(Name);
1821 if (I != ForwardRefVals.end())
1822 Val = I->second.first;
1823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001824
Chris Lattnerdf986172009-01-02 07:01:27 +00001825 // If we have the value in the symbol table or fwd-ref table, return it.
1826 if (Val) {
1827 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001828 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 P.Error(Loc, "'%" + Name + "' is not a basic block");
1830 else
1831 P.Error(Loc, "'%" + Name + "' defined with type '" +
1832 Val->getType()->getDescription() + "'");
1833 return 0;
1834 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001835
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001837 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 P.Error(Loc, "invalid use of a non-first-class type");
1839 return 0;
1840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 // Otherwise, create a new forward reference for this value and remember it.
1843 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001844 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001845 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001846 else
1847 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1850 return FwdVal;
1851}
1852
1853Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1854 LocTy Loc) {
1855 // Look this name up in the normal function symbol table.
1856 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Chris Lattnerdf986172009-01-02 07:01:27 +00001858 // If this is a forward reference for the value, see if we already created a
1859 // forward ref record.
1860 if (Val == 0) {
1861 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1862 I = ForwardRefValIDs.find(ID);
1863 if (I != ForwardRefValIDs.end())
1864 Val = I->second.first;
1865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 // If we have the value in the symbol table or fwd-ref table, return it.
1868 if (Val) {
1869 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001870 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001871 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1872 else
1873 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1874 Val->getType()->getDescription() + "'");
1875 return 0;
1876 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001877
Duncan Sands47c51882010-02-16 14:50:09 +00001878 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001879 P.Error(Loc, "invalid use of a non-first-class type");
1880 return 0;
1881 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 // Otherwise, create a new forward reference for this value and remember it.
1884 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001885 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001886 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 else
1888 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001889
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1891 return FwdVal;
1892}
1893
1894/// SetInstName - After an instruction is parsed and inserted into its
1895/// basic block, this installs its name.
1896bool LLParser::PerFunctionState::SetInstName(int NameID,
1897 const std::string &NameStr,
1898 LocTy NameLoc, Instruction *Inst) {
1899 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001900 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 if (NameID != -1 || !NameStr.empty())
1902 return P.Error(NameLoc, "instructions returning void cannot have a name");
1903 return false;
1904 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001905
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 // If this was a numbered instruction, verify that the instruction is the
1907 // expected value and resolve any forward references.
1908 if (NameStr.empty()) {
1909 // If neither a name nor an ID was specified, just use the next ID.
1910 if (NameID == -1)
1911 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 if (unsigned(NameID) != NumberedVals.size())
1914 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1915 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1918 ForwardRefValIDs.find(NameID);
1919 if (FI != ForwardRefValIDs.end()) {
1920 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 FI->second.first->getType()->getDescription() + "'");
1923 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001924 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 ForwardRefValIDs.erase(FI);
1926 }
1927
1928 NumberedVals.push_back(Inst);
1929 return false;
1930 }
1931
1932 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1933 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1934 FI = ForwardRefVals.find(NameStr);
1935 if (FI != ForwardRefVals.end()) {
1936 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 FI->second.first->getType()->getDescription() + "'");
1939 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001940 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001941 ForwardRefVals.erase(FI);
1942 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001943
Chris Lattnerdf986172009-01-02 07:01:27 +00001944 // Set the name on the instruction.
1945 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001946
Chris Lattnerdf986172009-01-02 07:01:27 +00001947 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001948 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001949 NameStr + "'");
1950 return false;
1951}
1952
1953/// GetBB - Get a basic block with the specified name or ID, creating a
1954/// forward reference record if needed.
1955BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1956 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001957 return cast_or_null<BasicBlock>(GetVal(Name,
1958 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001959}
1960
1961BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001962 return cast_or_null<BasicBlock>(GetVal(ID,
1963 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001964}
1965
1966/// DefineBB - Define the specified basic block, which is either named or
1967/// unnamed. If there is an error, this returns null otherwise it returns
1968/// the block being defined.
1969BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1970 LocTy Loc) {
1971 BasicBlock *BB;
1972 if (Name.empty())
1973 BB = GetBB(NumberedVals.size(), Loc);
1974 else
1975 BB = GetBB(Name, Loc);
1976 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001977
Chris Lattnerdf986172009-01-02 07:01:27 +00001978 // Move the block to the end of the function. Forward ref'd blocks are
1979 // inserted wherever they happen to be referenced.
1980 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001981
Chris Lattnerdf986172009-01-02 07:01:27 +00001982 // Remove the block from forward ref sets.
1983 if (Name.empty()) {
1984 ForwardRefValIDs.erase(NumberedVals.size());
1985 NumberedVals.push_back(BB);
1986 } else {
1987 // BB forward references are already in the function symbol table.
1988 ForwardRefVals.erase(Name);
1989 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Chris Lattnerdf986172009-01-02 07:01:27 +00001991 return BB;
1992}
1993
1994//===----------------------------------------------------------------------===//
1995// Constants.
1996//===----------------------------------------------------------------------===//
1997
1998/// ParseValID - Parse an abstract value that doesn't necessarily have a
1999/// type implied. For example, if we parse "4" we don't know what integer type
2000/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002001/// sanity. PFS is used to convert function-local operands of metadata (since
2002/// metadata operands are not just parsed here but also converted to values).
2003/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002004bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002005 ID.Loc = Lex.getLoc();
2006 switch (Lex.getKind()) {
2007 default: return TokError("expected value token");
2008 case lltok::GlobalID: // @42
2009 ID.UIntVal = Lex.getUIntVal();
2010 ID.Kind = ValID::t_GlobalID;
2011 break;
2012 case lltok::GlobalVar: // @foo
2013 ID.StrVal = Lex.getStrVal();
2014 ID.Kind = ValID::t_GlobalName;
2015 break;
2016 case lltok::LocalVarID: // %42
2017 ID.UIntVal = Lex.getUIntVal();
2018 ID.Kind = ValID::t_LocalID;
2019 break;
2020 case lltok::LocalVar: // %foo
2021 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2022 ID.StrVal = Lex.getStrVal();
2023 ID.Kind = ValID::t_LocalName;
2024 break;
Chris Lattnere434d272009-12-30 04:56:59 +00002025 case lltok::exclaim: // !{...} MDNode, !"foo" MDString
Nick Lewycky21cc4462009-04-04 07:22:01 +00002026 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00002027
Chris Lattner3f5132a2009-12-29 22:40:21 +00002028 if (EatIfPresent(lltok::lbrace)) {
Nick Lewyckycb337992009-05-10 20:57:05 +00002029 SmallVector<Value*, 16> Elts;
Victor Hernandez24e64df2010-01-10 07:14:18 +00002030 if (ParseMDNodeVector(Elts, PFS) ||
Nick Lewycky21cc4462009-04-04 07:22:01 +00002031 ParseToken(lltok::rbrace, "expected end of metadata node"))
2032 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00002033
Victor Hernandez24e64df2010-01-10 07:14:18 +00002034 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner287881d2009-12-30 02:11:14 +00002035 ID.Kind = ValID::t_MDNode;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002036 return false;
2037 }
2038
Devang Patel923078c2009-07-01 19:21:12 +00002039 // Standalone metadata reference
2040 // !{ ..., !42, ... }
Chris Lattner860775c2009-12-30 04:13:37 +00002041 if (Lex.getKind() == lltok::APSInt) {
Chris Lattner4a72efc2009-12-30 04:15:23 +00002042 if (ParseMDNodeID(ID.MDNodeVal)) return true;
Chris Lattner287881d2009-12-30 02:11:14 +00002043 ID.Kind = ValID::t_MDNode;
Devang Patel923078c2009-07-01 19:21:12 +00002044 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00002045 }
2046
Nick Lewycky21cc4462009-04-04 07:22:01 +00002047 // MDString:
2048 // ::= '!' STRINGCONSTANT
Chris Lattner287881d2009-12-30 02:11:14 +00002049 if (ParseMDString(ID.MDStringVal)) return true;
2050 ID.Kind = ValID::t_MDString;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002051 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002053 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002054 ID.Kind = ValID::t_APSInt;
2055 break;
2056 case lltok::APFloat:
2057 ID.APFloatVal = Lex.getAPFloatVal();
2058 ID.Kind = ValID::t_APFloat;
2059 break;
2060 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002061 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002062 ID.Kind = ValID::t_Constant;
2063 break;
2064 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002065 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 ID.Kind = ValID::t_Constant;
2067 break;
2068 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2069 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2070 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002071
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 case lltok::lbrace: {
2073 // ValID ::= '{' ConstVector '}'
2074 Lex.Lex();
2075 SmallVector<Constant*, 16> Elts;
2076 if (ParseGlobalValueVector(Elts) ||
2077 ParseToken(lltok::rbrace, "expected end of struct constant"))
2078 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002079
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002080 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2081 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 ID.Kind = ValID::t_Constant;
2083 return false;
2084 }
2085 case lltok::less: {
2086 // ValID ::= '<' ConstVector '>' --> Vector.
2087 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2088 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002089 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002090
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 SmallVector<Constant*, 16> Elts;
2092 LocTy FirstEltLoc = Lex.getLoc();
2093 if (ParseGlobalValueVector(Elts) ||
2094 (isPackedStruct &&
2095 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2096 ParseToken(lltok::greater, "expected end of constant"))
2097 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002100 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002101 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 ID.Kind = ValID::t_Constant;
2103 return false;
2104 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002105
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 if (Elts.empty())
2107 return Error(ID.Loc, "constant vector must not be empty");
2108
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002109 if (!Elts[0]->getType()->isIntegerTy() &&
2110 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002111 return Error(FirstEltLoc,
2112 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002113
Chris Lattnerdf986172009-01-02 07:01:27 +00002114 // Verify that all the vector elements have the same type.
2115 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2116 if (Elts[i]->getType() != Elts[0]->getType())
2117 return Error(FirstEltLoc,
2118 "vector element #" + utostr(i) +
2119 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002120
Owen Andersonaf7ec972009-07-28 21:19:26 +00002121 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002122 ID.Kind = ValID::t_Constant;
2123 return false;
2124 }
2125 case lltok::lsquare: { // Array Constant
2126 Lex.Lex();
2127 SmallVector<Constant*, 16> Elts;
2128 LocTy FirstEltLoc = Lex.getLoc();
2129 if (ParseGlobalValueVector(Elts) ||
2130 ParseToken(lltok::rsquare, "expected end of array constant"))
2131 return true;
2132
2133 // Handle empty element.
2134 if (Elts.empty()) {
2135 // Use undef instead of an array because it's inconvenient to determine
2136 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002137 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 return false;
2139 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002142 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002143 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Owen Andersondebcb012009-07-29 22:17:13 +00002145 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002146
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002148 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002149 if (Elts[i]->getType() != Elts[0]->getType())
2150 return Error(FirstEltLoc,
2151 "array element #" + utostr(i) +
2152 " is not of type '" +Elts[0]->getType()->getDescription());
2153 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002154
Owen Anderson1fd70962009-07-28 18:32:17 +00002155 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 ID.Kind = ValID::t_Constant;
2157 return false;
2158 }
2159 case lltok::kw_c: // c "foo"
2160 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002161 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002162 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2163 ID.Kind = ValID::t_Constant;
2164 return false;
2165
2166 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002167 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2168 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 Lex.Lex();
2170 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002171 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002172 ParseStringConstant(ID.StrVal) ||
2173 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 ParseToken(lltok::StringConstant, "expected constraint string"))
2175 return true;
2176 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002177 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 ID.Kind = ValID::t_InlineAsm;
2179 return false;
2180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002181
Chris Lattner09d9ef42009-10-28 03:39:23 +00002182 case lltok::kw_blockaddress: {
2183 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2184 Lex.Lex();
2185
2186 ValID Fn, Label;
2187 LocTy FnLoc, LabelLoc;
2188
2189 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2190 ParseValID(Fn) ||
2191 ParseToken(lltok::comma, "expected comma in block address expression")||
2192 ParseValID(Label) ||
2193 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2194 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002195
Chris Lattner09d9ef42009-10-28 03:39:23 +00002196 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2197 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002198 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002199 return Error(Label.Loc, "expected basic block name in blockaddress");
2200
2201 // Make a global variable as a placeholder for this reference.
2202 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2203 false, GlobalValue::InternalLinkage,
2204 0, "");
2205 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2206 ID.ConstantVal = FwdRef;
2207 ID.Kind = ValID::t_Constant;
2208 return false;
2209 }
2210
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 case lltok::kw_trunc:
2212 case lltok::kw_zext:
2213 case lltok::kw_sext:
2214 case lltok::kw_fptrunc:
2215 case lltok::kw_fpext:
2216 case lltok::kw_bitcast:
2217 case lltok::kw_uitofp:
2218 case lltok::kw_sitofp:
2219 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002220 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002221 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002222 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002223 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002224 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 Constant *SrcVal;
2226 Lex.Lex();
2227 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2228 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002229 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 ParseType(DestTy) ||
2231 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2232 return true;
2233 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2234 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2235 SrcVal->getType()->getDescription() + "' to '" +
2236 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002237 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002238 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002239 ID.Kind = ValID::t_Constant;
2240 return false;
2241 }
2242 case lltok::kw_extractvalue: {
2243 Lex.Lex();
2244 Constant *Val;
2245 SmallVector<unsigned, 4> Indices;
2246 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2247 ParseGlobalTypeAndValue(Val) ||
2248 ParseIndexList(Indices) ||
2249 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2250 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002251
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002252 if (!Val->getType()->isAggregateType())
2253 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2255 Indices.end()))
2256 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002257 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002258 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002259 ID.Kind = ValID::t_Constant;
2260 return false;
2261 }
2262 case lltok::kw_insertvalue: {
2263 Lex.Lex();
2264 Constant *Val0, *Val1;
2265 SmallVector<unsigned, 4> Indices;
2266 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2267 ParseGlobalTypeAndValue(Val0) ||
2268 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2269 ParseGlobalTypeAndValue(Val1) ||
2270 ParseIndexList(Indices) ||
2271 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2272 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002273 if (!Val0->getType()->isAggregateType())
2274 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2276 Indices.end()))
2277 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002278 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002279 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 ID.Kind = ValID::t_Constant;
2281 return false;
2282 }
2283 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002284 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002285 unsigned PredVal, Opc = Lex.getUIntVal();
2286 Constant *Val0, *Val1;
2287 Lex.Lex();
2288 if (ParseCmpPredicate(PredVal, Opc) ||
2289 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2290 ParseGlobalTypeAndValue(Val0) ||
2291 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2292 ParseGlobalTypeAndValue(Val1) ||
2293 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2294 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002295
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 if (Val0->getType() != Val1->getType())
2297 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002298
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002300
Chris Lattnerdf986172009-01-02 07:01:27 +00002301 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002302 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002303 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002304 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002305 } else {
2306 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002307 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002308 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002310 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002311 }
2312 ID.Kind = ValID::t_Constant;
2313 return false;
2314 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002315
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 // Binary Operators.
2317 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002318 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002320 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002321 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002322 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 case lltok::kw_udiv:
2324 case lltok::kw_sdiv:
2325 case lltok::kw_fdiv:
2326 case lltok::kw_urem:
2327 case lltok::kw_srem:
2328 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002329 bool NUW = false;
2330 bool NSW = false;
2331 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002332 unsigned Opc = Lex.getUIntVal();
2333 Constant *Val0, *Val1;
2334 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002335 LocTy ModifierLoc = Lex.getLoc();
2336 if (Opc == Instruction::Add ||
2337 Opc == Instruction::Sub ||
2338 Opc == Instruction::Mul) {
2339 if (EatIfPresent(lltok::kw_nuw))
2340 NUW = true;
2341 if (EatIfPresent(lltok::kw_nsw)) {
2342 NSW = true;
2343 if (EatIfPresent(lltok::kw_nuw))
2344 NUW = true;
2345 }
2346 } else if (Opc == Instruction::SDiv) {
2347 if (EatIfPresent(lltok::kw_exact))
2348 Exact = true;
2349 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2351 ParseGlobalTypeAndValue(Val0) ||
2352 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2353 ParseGlobalTypeAndValue(Val1) ||
2354 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2355 return true;
2356 if (Val0->getType() != Val1->getType())
2357 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002358 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002359 if (NUW)
2360 return Error(ModifierLoc, "nuw only applies to integer operations");
2361 if (NSW)
2362 return Error(ModifierLoc, "nsw only applies to integer operations");
2363 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002364 // Check that the type is valid for the operator.
2365 switch (Opc) {
2366 case Instruction::Add:
2367 case Instruction::Sub:
2368 case Instruction::Mul:
2369 case Instruction::UDiv:
2370 case Instruction::SDiv:
2371 case Instruction::URem:
2372 case Instruction::SRem:
2373 if (!Val0->getType()->isIntOrIntVectorTy())
2374 return Error(ID.Loc, "constexpr requires integer operands");
2375 break;
2376 case Instruction::FAdd:
2377 case Instruction::FSub:
2378 case Instruction::FMul:
2379 case Instruction::FDiv:
2380 case Instruction::FRem:
2381 if (!Val0->getType()->isFPOrFPVectorTy())
2382 return Error(ID.Loc, "constexpr requires fp operands");
2383 break;
2384 default: llvm_unreachable("Unknown binary operator!");
2385 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002386 unsigned Flags = 0;
2387 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2388 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2389 if (Exact) Flags |= SDivOperator::IsExact;
2390 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002391 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 ID.Kind = ValID::t_Constant;
2393 return false;
2394 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002395
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 // Logical Operations
2397 case lltok::kw_shl:
2398 case lltok::kw_lshr:
2399 case lltok::kw_ashr:
2400 case lltok::kw_and:
2401 case lltok::kw_or:
2402 case lltok::kw_xor: {
2403 unsigned Opc = Lex.getUIntVal();
2404 Constant *Val0, *Val1;
2405 Lex.Lex();
2406 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2407 ParseGlobalTypeAndValue(Val0) ||
2408 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2409 ParseGlobalTypeAndValue(Val1) ||
2410 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2411 return true;
2412 if (Val0->getType() != Val1->getType())
2413 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002414 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 return Error(ID.Loc,
2416 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002417 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 ID.Kind = ValID::t_Constant;
2419 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002420 }
2421
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 case lltok::kw_getelementptr:
2423 case lltok::kw_shufflevector:
2424 case lltok::kw_insertelement:
2425 case lltok::kw_extractelement:
2426 case lltok::kw_select: {
2427 unsigned Opc = Lex.getUIntVal();
2428 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002429 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002431 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002432 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002433 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2434 ParseGlobalValueVector(Elts) ||
2435 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2436 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002437
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002439 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002441
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002443 (Value**)(Elts.data() + 1),
2444 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002446 ID.ConstantVal = InBounds ?
2447 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2448 Elts.data() + 1,
2449 Elts.size() - 1) :
2450 ConstantExpr::getGetElementPtr(Elts[0],
2451 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002452 } else if (Opc == Instruction::Select) {
2453 if (Elts.size() != 3)
2454 return Error(ID.Loc, "expected three operands to select");
2455 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2456 Elts[2]))
2457 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002458 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002459 } else if (Opc == Instruction::ShuffleVector) {
2460 if (Elts.size() != 3)
2461 return Error(ID.Loc, "expected three operands to shufflevector");
2462 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2463 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002464 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002465 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002466 } else if (Opc == Instruction::ExtractElement) {
2467 if (Elts.size() != 2)
2468 return Error(ID.Loc, "expected two operands to extractelement");
2469 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2470 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002471 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002472 } else {
2473 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2474 if (Elts.size() != 3)
2475 return Error(ID.Loc, "expected three operands to insertelement");
2476 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2477 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002478 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002479 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002480 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002481
Chris Lattnerdf986172009-01-02 07:01:27 +00002482 ID.Kind = ValID::t_Constant;
2483 return false;
2484 }
2485 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002486
Chris Lattnerdf986172009-01-02 07:01:27 +00002487 Lex.Lex();
2488 return false;
2489}
2490
2491/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002492bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2493 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002494 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002495 Value *V = NULL;
2496 bool Parsed = ParseValID(ID) ||
2497 ConvertValIDToValue(Ty, ID, V, NULL);
2498 if (V && !(C = dyn_cast<Constant>(V)))
2499 return Error(ID.Loc, "global values must be constants");
2500 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002501}
2502
Victor Hernandez92f238d2010-01-11 22:31:58 +00002503bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2504 PATypeHolder Type(Type::getVoidTy(Context));
2505 return ParseType(Type) ||
2506 ParseGlobalValue(Type, V);
2507}
2508
2509/// ParseGlobalValueVector
2510/// ::= /*empty*/
2511/// ::= TypeAndValue (',' TypeAndValue)*
2512bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2513 // Empty list.
2514 if (Lex.getKind() == lltok::rbrace ||
2515 Lex.getKind() == lltok::rsquare ||
2516 Lex.getKind() == lltok::greater ||
2517 Lex.getKind() == lltok::rparen)
2518 return false;
2519
2520 Constant *C;
2521 if (ParseGlobalTypeAndValue(C)) return true;
2522 Elts.push_back(C);
2523
2524 while (EatIfPresent(lltok::comma)) {
2525 if (ParseGlobalTypeAndValue(C)) return true;
2526 Elts.push_back(C);
2527 }
2528
2529 return false;
2530}
2531
2532
2533//===----------------------------------------------------------------------===//
2534// Function Parsing.
2535//===----------------------------------------------------------------------===//
2536
2537bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2538 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002539 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002540 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002541
Chris Lattnerdf986172009-01-02 07:01:27 +00002542 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002543 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002545 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2546 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2547 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002549 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2550 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2551 return (V == 0);
2552 case ValID::t_InlineAsm: {
2553 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2554 const FunctionType *FTy =
2555 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2556 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2557 return Error(ID.Loc, "invalid type for inline asm constraint string");
2558 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2559 return false;
2560 }
2561 case ValID::t_MDNode:
2562 if (!Ty->isMetadataTy())
2563 return Error(ID.Loc, "metadata value must have metadata type");
2564 V = ID.MDNodeVal;
2565 return false;
2566 case ValID::t_MDString:
2567 if (!Ty->isMetadataTy())
2568 return Error(ID.Loc, "metadata value must have metadata type");
2569 V = ID.MDStringVal;
2570 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 case ValID::t_GlobalName:
2572 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2573 return V == 0;
2574 case ValID::t_GlobalID:
2575 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2576 return V == 0;
2577 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002578 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002579 return Error(ID.Loc, "integer constant must have integer type");
2580 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002581 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002582 return false;
2583 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002584 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2586 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002587
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 // The lexer has no type info, so builds all float and double FP constants
2589 // as double. Fix this here. Long double does not need this.
2590 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002591 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 bool Ignored;
2593 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2594 &Ignored);
2595 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002596 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002597
Chris Lattner959873d2009-01-05 18:24:23 +00002598 if (V->getType() != Ty)
2599 return Error(ID.Loc, "floating point constant does not have type '" +
2600 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002601
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 return false;
2603 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002604 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002605 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002606 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002607 return false;
2608 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002609 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002610 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002611 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002612 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002613 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002614 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002615 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002616 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002617 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002618 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002619 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002621 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002622 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002623 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002624 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 return false;
2626 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002627 if (ID.ConstantVal->getType() != Ty) {
2628 // Allow a constant struct with a single member to be converted
2629 // to a union, if the union has a member which is the same type
2630 // as the struct member.
2631 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2632 return ParseUnionValue(utype, ID, V);
2633 }
2634
Chris Lattnerdf986172009-01-02 07:01:27 +00002635 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002636 }
2637
Chris Lattnerdf986172009-01-02 07:01:27 +00002638 V = ID.ConstantVal;
2639 return false;
2640 }
2641}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002642
Chris Lattnerdf986172009-01-02 07:01:27 +00002643bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2644 V = 0;
2645 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002646 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002647 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002648}
2649
2650bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002651 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002652 return ParseType(T) ||
2653 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002654}
2655
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002656bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2657 PerFunctionState &PFS) {
2658 Value *V;
2659 Loc = Lex.getLoc();
2660 if (ParseTypeAndValue(V, PFS)) return true;
2661 if (!isa<BasicBlock>(V))
2662 return Error(Loc, "expected a basic block");
2663 BB = cast<BasicBlock>(V);
2664 return false;
2665}
2666
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002667bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2668 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2669 if (stype->getNumContainedTypes() != 1)
2670 return Error(ID.Loc, "constant expression type mismatch");
2671 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2672 if (index < 0)
2673 return Error(ID.Loc, "initializer type is not a member of the union");
2674
2675 V = ConstantUnion::get(
2676 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2677 return false;
2678 }
2679
2680 return Error(ID.Loc, "constant expression type mismatch");
2681}
2682
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002683
Chris Lattnerdf986172009-01-02 07:01:27 +00002684/// FunctionHeader
2685/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2686/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2687/// OptionalAlign OptGC
2688bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2689 // Parse the linkage.
2690 LocTy LinkageLoc = Lex.getLoc();
2691 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002692
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002693 unsigned Visibility, RetAttrs;
2694 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002695 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 LocTy RetTypeLoc = Lex.getLoc();
2697 if (ParseOptionalLinkage(Linkage) ||
2698 ParseOptionalVisibility(Visibility) ||
2699 ParseOptionalCallingConv(CC) ||
2700 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002701 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 return true;
2703
2704 // Verify that the linkage is ok.
2705 switch ((GlobalValue::LinkageTypes)Linkage) {
2706 case GlobalValue::ExternalLinkage:
2707 break; // always ok.
2708 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002709 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002710 if (isDefine)
2711 return Error(LinkageLoc, "invalid linkage for function definition");
2712 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002713 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002714 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002715 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002716 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002717 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002718 case GlobalValue::LinkOnceAnyLinkage:
2719 case GlobalValue::LinkOnceODRLinkage:
2720 case GlobalValue::WeakAnyLinkage:
2721 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002722 case GlobalValue::DLLExportLinkage:
2723 if (!isDefine)
2724 return Error(LinkageLoc, "invalid linkage for function declaration");
2725 break;
2726 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002727 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 return Error(LinkageLoc, "invalid function linkage type");
2729 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002730
Chris Lattner99bb3152009-01-05 08:00:30 +00002731 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002732 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002734
Chris Lattnerdf986172009-01-02 07:01:27 +00002735 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002736
2737 std::string FunctionName;
2738 if (Lex.getKind() == lltok::GlobalVar) {
2739 FunctionName = Lex.getStrVal();
2740 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2741 unsigned NameID = Lex.getUIntVal();
2742
2743 if (NameID != NumberedVals.size())
2744 return TokError("function expected to be numbered '%" +
2745 utostr(NumberedVals.size()) + "'");
2746 } else {
2747 return TokError("expected function name");
2748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002749
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002750 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002751
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002752 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002753 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002754
Chris Lattnerdf986172009-01-02 07:01:27 +00002755 std::vector<ArgInfo> ArgList;
2756 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002759 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002760 std::string GC;
2761
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002762 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002763 ParseOptionalAttrs(FuncAttrs, 2) ||
2764 (EatIfPresent(lltok::kw_section) &&
2765 ParseStringConstant(Section)) ||
2766 ParseOptionalAlignment(Alignment) ||
2767 (EatIfPresent(lltok::kw_gc) &&
2768 ParseStringConstant(GC)))
2769 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002770
2771 // If the alignment was parsed as an attribute, move to the alignment field.
2772 if (FuncAttrs & Attribute::Alignment) {
2773 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2774 FuncAttrs &= ~Attribute::Alignment;
2775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Chris Lattnerdf986172009-01-02 07:01:27 +00002777 // Okay, if we got here, the function is syntactically valid. Convert types
2778 // and do semantic checks.
2779 std::vector<const Type*> ParamTypeList;
2780 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 // attributes.
2783 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2784 if (FuncAttrs & ObsoleteFuncAttrs) {
2785 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2786 FuncAttrs &= ~ObsoleteFuncAttrs;
2787 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 if (RetAttrs != Attribute::None)
2790 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerdf986172009-01-02 07:01:27 +00002792 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2793 ParamTypeList.push_back(ArgList[i].Type);
2794 if (ArgList[i].Attrs != Attribute::None)
2795 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2796 }
2797
2798 if (FuncAttrs != Attribute::None)
2799 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2800
2801 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002802
Benjamin Kramerf0127052010-01-05 13:12:22 +00002803 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002804 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2805
Owen Andersonfba933c2009-07-01 23:57:11 +00002806 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002807 FunctionType::get(RetType, ParamTypeList, isVarArg);
2808 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002809
2810 Fn = 0;
2811 if (!FunctionName.empty()) {
2812 // If this was a definition of a forward reference, remove the definition
2813 // from the forward reference table and fill in the forward ref.
2814 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2815 ForwardRefVals.find(FunctionName);
2816 if (FRVI != ForwardRefVals.end()) {
2817 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002818 if (Fn->getType() != PFT)
2819 return Error(FRVI->second.second, "invalid forward reference to "
2820 "function '" + FunctionName + "' with wrong type!");
2821
Chris Lattnerdf986172009-01-02 07:01:27 +00002822 ForwardRefVals.erase(FRVI);
2823 } else if ((Fn = M->getFunction(FunctionName))) {
2824 // If this function already exists in the symbol table, then it is
2825 // multiply defined. We accept a few cases for old backwards compat.
2826 // FIXME: Remove this stuff for LLVM 3.0.
2827 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2828 (!Fn->isDeclaration() && isDefine)) {
2829 // If the redefinition has different type or different attributes,
2830 // reject it. If both have bodies, reject it.
2831 return Error(NameLoc, "invalid redefinition of function '" +
2832 FunctionName + "'");
2833 } else if (Fn->isDeclaration()) {
2834 // Make sure to strip off any argument names so we can't get conflicts.
2835 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2836 AI != AE; ++AI)
2837 AI->setName("");
2838 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002839 } else if (M->getNamedValue(FunctionName)) {
2840 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002842
Dan Gohman41905542009-08-29 23:37:49 +00002843 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002844 // If this is a definition of a forward referenced function, make sure the
2845 // types agree.
2846 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2847 = ForwardRefValIDs.find(NumberedVals.size());
2848 if (I != ForwardRefValIDs.end()) {
2849 Fn = cast<Function>(I->second.first);
2850 if (Fn->getType() != PFT)
2851 return Error(NameLoc, "type of definition and forward reference of '@" +
2852 utostr(NumberedVals.size()) +"' disagree");
2853 ForwardRefValIDs.erase(I);
2854 }
2855 }
2856
2857 if (Fn == 0)
2858 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2859 else // Move the forward-reference to the correct spot in the module.
2860 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2861
2862 if (FunctionName.empty())
2863 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002864
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2866 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2867 Fn->setCallingConv(CC);
2868 Fn->setAttributes(PAL);
2869 Fn->setAlignment(Alignment);
2870 Fn->setSection(Section);
2871 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002872
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 // Add all of the arguments we parsed to the function.
2874 Function::arg_iterator ArgIt = Fn->arg_begin();
2875 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002876 // If we run out of arguments in the Function prototype, exit early.
2877 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2878 if (ArgIt == Fn->arg_end()) break;
2879
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 // If the argument has a name, insert it into the argument symbol table.
2881 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002882
Chris Lattnerdf986172009-01-02 07:01:27 +00002883 // Set the name, if it conflicted, it will be auto-renamed.
2884 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002885
Chris Lattnerdf986172009-01-02 07:01:27 +00002886 if (ArgIt->getNameStr() != ArgList[i].Name)
2887 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2888 ArgList[i].Name + "'");
2889 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnerdf986172009-01-02 07:01:27 +00002891 return false;
2892}
2893
2894
2895/// ParseFunctionBody
2896/// ::= '{' BasicBlock+ '}'
2897/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2898///
2899bool LLParser::ParseFunctionBody(Function &Fn) {
2900 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2901 return TokError("expected '{' in function body");
2902 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002903
Chris Lattner09d9ef42009-10-28 03:39:23 +00002904 int FunctionNumber = -1;
2905 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2906
2907 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002908
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002909 // We need at least one basic block.
2910 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2911 return TokError("function body requires at least one basic block");
2912
Chris Lattnerdf986172009-01-02 07:01:27 +00002913 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2914 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002915
Chris Lattnerdf986172009-01-02 07:01:27 +00002916 // Eat the }.
2917 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002918
Chris Lattnerdf986172009-01-02 07:01:27 +00002919 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002920 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002921}
2922
2923/// ParseBasicBlock
2924/// ::= LabelStr? Instruction*
2925bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2926 // If this basic block starts out with a name, remember it.
2927 std::string Name;
2928 LocTy NameLoc = Lex.getLoc();
2929 if (Lex.getKind() == lltok::LabelStr) {
2930 Name = Lex.getStrVal();
2931 Lex.Lex();
2932 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002933
Chris Lattnerdf986172009-01-02 07:01:27 +00002934 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2935 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002936
Chris Lattnerdf986172009-01-02 07:01:27 +00002937 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002938
Chris Lattnerdf986172009-01-02 07:01:27 +00002939 // Parse the instructions in this block until we get a terminator.
2940 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002941 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 do {
2943 // This instruction may have three possibilities for a name: a) none
2944 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2945 LocTy NameLoc = Lex.getLoc();
2946 int NameID = -1;
2947 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002948
Chris Lattnerdf986172009-01-02 07:01:27 +00002949 if (Lex.getKind() == lltok::LocalVarID) {
2950 NameID = Lex.getUIntVal();
2951 Lex.Lex();
2952 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2953 return true;
2954 } else if (Lex.getKind() == lltok::LocalVar ||
2955 // FIXME: REMOVE IN LLVM 3.0
2956 Lex.getKind() == lltok::StringConstant) {
2957 NameStr = Lex.getStrVal();
2958 Lex.Lex();
2959 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2960 return true;
2961 }
Devang Patelf633a062009-09-17 23:04:48 +00002962
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002963 switch (ParseInstruction(Inst, BB, PFS)) {
2964 default: assert(0 && "Unknown ParseInstruction result!");
2965 case InstError: return true;
2966 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002967 BB->getInstList().push_back(Inst);
2968
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002969 // With a normal result, we check to see if the instruction is followed by
2970 // a comma and metadata.
2971 if (EatIfPresent(lltok::comma))
Chris Lattnerfe805242010-04-01 04:51:13 +00002972 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002973 return true;
2974 break;
2975 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002976 BB->getInstList().push_back(Inst);
2977
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002978 // If the instruction parser ate an extra comma at the end of it, it
2979 // *must* be followed by metadata.
Chris Lattnerfe805242010-04-01 04:51:13 +00002980 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002981 return true;
2982 break;
2983 }
Devang Patelf633a062009-09-17 23:04:48 +00002984
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 // Set the name on the instruction.
2986 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2987 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002988
Chris Lattnerdf986172009-01-02 07:01:27 +00002989 return false;
2990}
2991
2992//===----------------------------------------------------------------------===//
2993// Instruction Parsing.
2994//===----------------------------------------------------------------------===//
2995
2996/// ParseInstruction - Parse one of the many different instructions.
2997///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002998int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2999 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003000 lltok::Kind Token = Lex.getKind();
3001 if (Token == lltok::Eof)
3002 return TokError("found end of file when expecting more instructions");
3003 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003004 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003005 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003006
Chris Lattnerdf986172009-01-02 07:01:27 +00003007 switch (Token) {
3008 default: return Error(Loc, "expected instruction opcode");
3009 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003010 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3011 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003012 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3013 case lltok::kw_br: return ParseBr(Inst, PFS);
3014 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003015 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3017 // Binary Operators.
3018 case lltok::kw_add:
3019 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00003020 case lltok::kw_mul: {
3021 bool NUW = false;
3022 bool NSW = false;
3023 LocTy ModifierLoc = Lex.getLoc();
3024 if (EatIfPresent(lltok::kw_nuw))
3025 NUW = true;
3026 if (EatIfPresent(lltok::kw_nsw)) {
3027 NSW = true;
3028 if (EatIfPresent(lltok::kw_nuw))
3029 NUW = true;
3030 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003031 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003032 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003033 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003034 if (NUW)
3035 return Error(ModifierLoc, "nuw only applies to integer operations");
3036 if (NSW)
3037 return Error(ModifierLoc, "nsw only applies to integer operations");
3038 }
3039 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003040 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003041 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003042 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003043 }
3044 return Result;
3045 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003046 case lltok::kw_fadd:
3047 case lltok::kw_fsub:
3048 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3049
Dan Gohman59858cf2009-07-27 16:11:46 +00003050 case lltok::kw_sdiv: {
3051 bool Exact = false;
3052 if (EatIfPresent(lltok::kw_exact))
3053 Exact = true;
3054 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3055 if (!Result)
3056 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003057 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003058 return Result;
3059 }
3060
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003063 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003064 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003065 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003066 case lltok::kw_shl:
3067 case lltok::kw_lshr:
3068 case lltok::kw_ashr:
3069 case lltok::kw_and:
3070 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003071 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003073 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003074 // Casts.
3075 case lltok::kw_trunc:
3076 case lltok::kw_zext:
3077 case lltok::kw_sext:
3078 case lltok::kw_fptrunc:
3079 case lltok::kw_fpext:
3080 case lltok::kw_bitcast:
3081 case lltok::kw_uitofp:
3082 case lltok::kw_sitofp:
3083 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003084 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003085 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003086 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003087 // Other.
3088 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003089 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3091 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3092 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3093 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3094 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3095 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3096 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003097 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3098 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003099 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003100 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3101 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3102 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003103 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003105 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003106 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003107 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003108 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3110 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3111 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3112 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3113 }
3114}
3115
3116/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3117bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003118 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003119 switch (Lex.getKind()) {
3120 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3121 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3122 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3123 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3124 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3125 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3126 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3127 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3128 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3129 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3130 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3131 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3132 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3133 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3134 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3135 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3136 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3137 }
3138 } else {
3139 switch (Lex.getKind()) {
3140 default: TokError("expected icmp predicate (e.g. 'eq')");
3141 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3142 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3143 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3144 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3145 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3146 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3147 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3148 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3149 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3150 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3151 }
3152 }
3153 Lex.Lex();
3154 return false;
3155}
3156
3157//===----------------------------------------------------------------------===//
3158// Terminator Instructions.
3159//===----------------------------------------------------------------------===//
3160
3161/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003162/// ::= 'ret' void (',' !dbg, !1)*
3163/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3164/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003165/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003166int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3167 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003168 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003169 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003170
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003171 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003172 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003173 return false;
3174 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003175
Chris Lattnerdf986172009-01-02 07:01:27 +00003176 Value *RV;
3177 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003178
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003179 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003180 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003181 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003182 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003183 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003184 } else {
3185 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003186 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3187 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003188 SmallVector<Value*, 8> RVs;
3189 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003190
Devang Patelf633a062009-09-17 23:04:48 +00003191 do {
Devang Patel0475c912009-09-29 00:01:14 +00003192 // If optional custom metadata, e.g. !dbg is seen then this is the
3193 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003194 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003195 break;
3196 if (ParseTypeAndValue(RV, PFS)) return true;
3197 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003198 } while (EatIfPresent(lltok::comma));
3199
3200 RV = UndefValue::get(PFS.getFunction().getReturnType());
3201 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003202 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3203 BB->getInstList().push_back(I);
3204 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003205 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 }
3207 }
Devang Patelf633a062009-09-17 23:04:48 +00003208
Owen Anderson1d0be152009-08-13 21:58:54 +00003209 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003210 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003211}
3212
3213
3214/// ParseBr
3215/// ::= 'br' TypeAndValue
3216/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3217bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3218 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003219 Value *Op0;
3220 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003222
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3224 Inst = BranchInst::Create(BB);
3225 return false;
3226 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003227
Owen Anderson1d0be152009-08-13 21:58:54 +00003228 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003230
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003232 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003233 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003234 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003236
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003237 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 return false;
3239}
3240
3241/// ParseSwitch
3242/// Instruction
3243/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3244/// JumpTable
3245/// ::= (TypeAndValue ',' TypeAndValue)*
3246bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3247 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003248 Value *Cond;
3249 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3251 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003252 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003253 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3254 return true;
3255
Duncan Sands1df98592010-02-16 11:11:14 +00003256 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003258
Chris Lattnerdf986172009-01-02 07:01:27 +00003259 // Parse the jump table pairs.
3260 SmallPtrSet<Value*, 32> SeenCases;
3261 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3262 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003263 Value *Constant;
3264 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003265
Chris Lattnerdf986172009-01-02 07:01:27 +00003266 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3267 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003268 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003270
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 if (!SeenCases.insert(Constant))
3272 return Error(CondLoc, "duplicate case value in switch");
3273 if (!isa<ConstantInt>(Constant))
3274 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003275
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003276 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003277 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003278
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003280
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003281 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003282 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3283 SI->addCase(Table[i].first, Table[i].second);
3284 Inst = SI;
3285 return false;
3286}
3287
Chris Lattnerab21db72009-10-28 00:19:10 +00003288/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003289/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003290/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3291bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003292 LocTy AddrLoc;
3293 Value *Address;
3294 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003295 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3296 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003297 return true;
3298
Duncan Sands1df98592010-02-16 11:11:14 +00003299 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003300 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003301
3302 // Parse the destination list.
3303 SmallVector<BasicBlock*, 16> DestList;
3304
3305 if (Lex.getKind() != lltok::rsquare) {
3306 BasicBlock *DestBB;
3307 if (ParseTypeAndBasicBlock(DestBB, PFS))
3308 return true;
3309 DestList.push_back(DestBB);
3310
3311 while (EatIfPresent(lltok::comma)) {
3312 if (ParseTypeAndBasicBlock(DestBB, PFS))
3313 return true;
3314 DestList.push_back(DestBB);
3315 }
3316 }
3317
3318 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3319 return true;
3320
Chris Lattnerab21db72009-10-28 00:19:10 +00003321 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003322 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3323 IBI->addDestination(DestList[i]);
3324 Inst = IBI;
3325 return false;
3326}
3327
3328
Chris Lattnerdf986172009-01-02 07:01:27 +00003329/// ParseInvoke
3330/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3331/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3332bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3333 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003334 unsigned RetAttrs, FnAttrs;
3335 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003336 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003337 LocTy RetTypeLoc;
3338 ValID CalleeID;
3339 SmallVector<ParamInfo, 16> ArgList;
3340
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003341 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003342 if (ParseOptionalCallingConv(CC) ||
3343 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003344 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003345 ParseValID(CalleeID) ||
3346 ParseParameterList(ArgList, PFS) ||
3347 ParseOptionalAttrs(FnAttrs, 2) ||
3348 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003349 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003350 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003351 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003353
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 // If RetType is a non-function pointer type, then this is the short syntax
3355 // for the call, which means that RetType is just the return type. Infer the
3356 // rest of the function argument types from the arguments that are present.
3357 const PointerType *PFTy = 0;
3358 const FunctionType *Ty = 0;
3359 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3360 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3361 // Pull out the types of all of the arguments...
3362 std::vector<const Type*> ParamTypes;
3363 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3364 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003365
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 if (!FunctionType::isValidReturnType(RetType))
3367 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003368
Owen Andersondebcb012009-07-29 22:17:13 +00003369 Ty = FunctionType::get(RetType, ParamTypes, false);
3370 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003371 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003372
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 // Look up the callee.
3374 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003375 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003376
Chris Lattnerdf986172009-01-02 07:01:27 +00003377 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3378 // function attributes.
3379 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3380 if (FnAttrs & ObsoleteFuncAttrs) {
3381 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3382 FnAttrs &= ~ObsoleteFuncAttrs;
3383 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003384
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 // Set up the Attributes for the function.
3386 SmallVector<AttributeWithIndex, 8> Attrs;
3387 if (RetAttrs != Attribute::None)
3388 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003391
Chris Lattnerdf986172009-01-02 07:01:27 +00003392 // Loop through FunctionType's arguments and ensure they are specified
3393 // correctly. Also, gather any parameter attributes.
3394 FunctionType::param_iterator I = Ty->param_begin();
3395 FunctionType::param_iterator E = Ty->param_end();
3396 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3397 const Type *ExpectedTy = 0;
3398 if (I != E) {
3399 ExpectedTy = *I++;
3400 } else if (!Ty->isVarArg()) {
3401 return Error(ArgList[i].Loc, "too many arguments specified");
3402 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003403
Chris Lattnerdf986172009-01-02 07:01:27 +00003404 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3405 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3406 ExpectedTy->getDescription() + "'");
3407 Args.push_back(ArgList[i].V);
3408 if (ArgList[i].Attrs != Attribute::None)
3409 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3410 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003411
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 if (I != E)
3413 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003414
Chris Lattnerdf986172009-01-02 07:01:27 +00003415 if (FnAttrs != Attribute::None)
3416 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003417
Chris Lattnerdf986172009-01-02 07:01:27 +00003418 // Finish off the Attributes and check them
3419 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003420
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003421 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003422 Args.begin(), Args.end());
3423 II->setCallingConv(CC);
3424 II->setAttributes(PAL);
3425 Inst = II;
3426 return false;
3427}
3428
3429
3430
3431//===----------------------------------------------------------------------===//
3432// Binary Operators.
3433//===----------------------------------------------------------------------===//
3434
3435/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003436/// ::= ArithmeticOps TypeAndValue ',' Value
3437///
3438/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3439/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003440bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003441 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 LocTy Loc; Value *LHS, *RHS;
3443 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3444 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3445 ParseValue(LHS->getType(), RHS, PFS))
3446 return true;
3447
Chris Lattnere914b592009-01-05 08:24:46 +00003448 bool Valid;
3449 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003450 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003451 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003452 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3453 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003454 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003455 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3456 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003457 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003458
Chris Lattnere914b592009-01-05 08:24:46 +00003459 if (!Valid)
3460 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003461
Chris Lattnerdf986172009-01-02 07:01:27 +00003462 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3463 return false;
3464}
3465
3466/// ParseLogical
3467/// ::= ArithmeticOps TypeAndValue ',' Value {
3468bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3469 unsigned Opc) {
3470 LocTy Loc; Value *LHS, *RHS;
3471 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3472 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3473 ParseValue(LHS->getType(), RHS, PFS))
3474 return true;
3475
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003476 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 return Error(Loc,"instruction requires integer or integer vector operands");
3478
3479 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3480 return false;
3481}
3482
3483
3484/// ParseCompare
3485/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3486/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003487bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3488 unsigned Opc) {
3489 // Parse the integer/fp comparison predicate.
3490 LocTy Loc;
3491 unsigned Pred;
3492 Value *LHS, *RHS;
3493 if (ParseCmpPredicate(Pred, Opc) ||
3494 ParseTypeAndValue(LHS, Loc, PFS) ||
3495 ParseToken(lltok::comma, "expected ',' after compare value") ||
3496 ParseValue(LHS->getType(), RHS, PFS))
3497 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003498
Chris Lattnerdf986172009-01-02 07:01:27 +00003499 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003500 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003501 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003502 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003503 } else {
3504 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003505 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003506 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003507 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003508 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003509 }
3510 return false;
3511}
3512
3513//===----------------------------------------------------------------------===//
3514// Other Instructions.
3515//===----------------------------------------------------------------------===//
3516
3517
3518/// ParseCast
3519/// ::= CastOpc TypeAndValue 'to' Type
3520bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3521 unsigned Opc) {
3522 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003523 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 if (ParseTypeAndValue(Op, Loc, PFS) ||
3525 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3526 ParseType(DestTy))
3527 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003528
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003529 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3530 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003531 return Error(Loc, "invalid cast opcode for cast from '" +
3532 Op->getType()->getDescription() + "' to '" +
3533 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003534 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3536 return false;
3537}
3538
3539/// ParseSelect
3540/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3541bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3542 LocTy Loc;
3543 Value *Op0, *Op1, *Op2;
3544 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3545 ParseToken(lltok::comma, "expected ',' after select condition") ||
3546 ParseTypeAndValue(Op1, PFS) ||
3547 ParseToken(lltok::comma, "expected ',' after select value") ||
3548 ParseTypeAndValue(Op2, PFS))
3549 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003550
Chris Lattnerdf986172009-01-02 07:01:27 +00003551 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3552 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003553
Chris Lattnerdf986172009-01-02 07:01:27 +00003554 Inst = SelectInst::Create(Op0, Op1, Op2);
3555 return false;
3556}
3557
Chris Lattner0088a5c2009-01-05 08:18:44 +00003558/// ParseVA_Arg
3559/// ::= 'va_arg' TypeAndValue ',' Type
3560bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003561 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003562 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003563 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003564 if (ParseTypeAndValue(Op, PFS) ||
3565 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003566 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003568
Chris Lattner0088a5c2009-01-05 08:18:44 +00003569 if (!EltTy->isFirstClassType())
3570 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003571
3572 Inst = new VAArgInst(Op, EltTy);
3573 return false;
3574}
3575
3576/// ParseExtractElement
3577/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3578bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3579 LocTy Loc;
3580 Value *Op0, *Op1;
3581 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3582 ParseToken(lltok::comma, "expected ',' after extract value") ||
3583 ParseTypeAndValue(Op1, PFS))
3584 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003585
Chris Lattnerdf986172009-01-02 07:01:27 +00003586 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3587 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003588
Eric Christophera3500da2009-07-25 02:28:41 +00003589 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003590 return false;
3591}
3592
3593/// ParseInsertElement
3594/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3595bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3596 LocTy Loc;
3597 Value *Op0, *Op1, *Op2;
3598 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3599 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3600 ParseTypeAndValue(Op1, PFS) ||
3601 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3602 ParseTypeAndValue(Op2, PFS))
3603 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003604
Chris Lattnerdf986172009-01-02 07:01:27 +00003605 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003606 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003607
Chris Lattnerdf986172009-01-02 07:01:27 +00003608 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3609 return false;
3610}
3611
3612/// ParseShuffleVector
3613/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3614bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3615 LocTy Loc;
3616 Value *Op0, *Op1, *Op2;
3617 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3618 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3619 ParseTypeAndValue(Op1, PFS) ||
3620 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3621 ParseTypeAndValue(Op2, PFS))
3622 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003623
Chris Lattnerdf986172009-01-02 07:01:27 +00003624 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3625 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003626
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3628 return false;
3629}
3630
3631/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003632/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003633int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003634 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 Value *Op0, *Op1;
3636 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003637
Chris Lattnerdf986172009-01-02 07:01:27 +00003638 if (ParseType(Ty) ||
3639 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3640 ParseValue(Ty, Op0, PFS) ||
3641 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003642 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003643 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3644 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003645
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003646 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003647 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3648 while (1) {
3649 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003650
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003651 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003652 break;
3653
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003654 if (Lex.getKind() == lltok::MetadataVar) {
3655 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003656 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003657 }
Devang Patela43d46f2009-10-16 18:45:49 +00003658
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003659 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003660 ParseValue(Ty, Op0, PFS) ||
3661 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003662 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003663 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3664 return true;
3665 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003666
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 if (!Ty->isFirstClassType())
3668 return Error(TypeLoc, "phi node must have first class type");
3669
3670 PHINode *PN = PHINode::Create(Ty);
3671 PN->reserveOperandSpace(PHIVals.size());
3672 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3673 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3674 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003675 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003676}
3677
3678/// ParseCall
3679/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3680/// ParameterList OptionalAttrs
3681bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3682 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003683 unsigned RetAttrs, FnAttrs;
3684 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003685 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003686 LocTy RetTypeLoc;
3687 ValID CalleeID;
3688 SmallVector<ParamInfo, 16> ArgList;
3689 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003690
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3692 ParseOptionalCallingConv(CC) ||
3693 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003694 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 ParseValID(CalleeID) ||
3696 ParseParameterList(ArgList, PFS) ||
3697 ParseOptionalAttrs(FnAttrs, 2))
3698 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003699
Chris Lattnerdf986172009-01-02 07:01:27 +00003700 // If RetType is a non-function pointer type, then this is the short syntax
3701 // for the call, which means that RetType is just the return type. Infer the
3702 // rest of the function argument types from the arguments that are present.
3703 const PointerType *PFTy = 0;
3704 const FunctionType *Ty = 0;
3705 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3706 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3707 // Pull out the types of all of the arguments...
3708 std::vector<const Type*> ParamTypes;
3709 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3710 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003711
Chris Lattnerdf986172009-01-02 07:01:27 +00003712 if (!FunctionType::isValidReturnType(RetType))
3713 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003714
Owen Andersondebcb012009-07-29 22:17:13 +00003715 Ty = FunctionType::get(RetType, ParamTypes, false);
3716 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003717 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003718
Chris Lattnerdf986172009-01-02 07:01:27 +00003719 // Look up the callee.
3720 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003721 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003722
Chris Lattnerdf986172009-01-02 07:01:27 +00003723 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3724 // function attributes.
3725 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3726 if (FnAttrs & ObsoleteFuncAttrs) {
3727 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3728 FnAttrs &= ~ObsoleteFuncAttrs;
3729 }
3730
3731 // Set up the Attributes for the function.
3732 SmallVector<AttributeWithIndex, 8> Attrs;
3733 if (RetAttrs != Attribute::None)
3734 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003735
Chris Lattnerdf986172009-01-02 07:01:27 +00003736 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003737
Chris Lattnerdf986172009-01-02 07:01:27 +00003738 // Loop through FunctionType's arguments and ensure they are specified
3739 // correctly. Also, gather any parameter attributes.
3740 FunctionType::param_iterator I = Ty->param_begin();
3741 FunctionType::param_iterator E = Ty->param_end();
3742 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3743 const Type *ExpectedTy = 0;
3744 if (I != E) {
3745 ExpectedTy = *I++;
3746 } else if (!Ty->isVarArg()) {
3747 return Error(ArgList[i].Loc, "too many arguments specified");
3748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003749
Chris Lattnerdf986172009-01-02 07:01:27 +00003750 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3751 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3752 ExpectedTy->getDescription() + "'");
3753 Args.push_back(ArgList[i].V);
3754 if (ArgList[i].Attrs != Attribute::None)
3755 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003757
Chris Lattnerdf986172009-01-02 07:01:27 +00003758 if (I != E)
3759 return Error(CallLoc, "not enough parameters specified for call");
3760
3761 if (FnAttrs != Attribute::None)
3762 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3763
3764 // Finish off the Attributes and check them
3765 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003766
Chris Lattnerdf986172009-01-02 07:01:27 +00003767 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3768 CI->setTailCall(isTail);
3769 CI->setCallingConv(CC);
3770 CI->setAttributes(PAL);
3771 Inst = CI;
3772 return false;
3773}
3774
3775//===----------------------------------------------------------------------===//
3776// Memory Instructions.
3777//===----------------------------------------------------------------------===//
3778
3779/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003780/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3781/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003782int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3783 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003784 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003785 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003786 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003787 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003788 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003789
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003790 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003791 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003792 if (Lex.getKind() == lltok::kw_align) {
3793 if (ParseOptionalAlignment(Alignment)) return true;
3794 } else if (Lex.getKind() == lltok::MetadataVar) {
3795 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003796 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003797 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3798 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3799 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003800 }
3801 }
3802
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003803 if (Size && !Size->getType()->isIntegerTy())
3804 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003805
Victor Hernandez68afa542009-10-21 19:11:40 +00003806 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003807 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003808 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003809 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003810
3811 // Autoupgrade old malloc instruction to malloc call.
3812 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003813 if (Size && !Size->getType()->isIntegerTy(32))
3814 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003815 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003816 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3817 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003818 if (!MallocF)
3819 // Prototype malloc as "void *(int32)".
3820 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003821 MallocF = cast<Function>(
3822 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003823 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003824return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003825}
3826
3827/// ParseFree
3828/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003829bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3830 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003831 Value *Val; LocTy Loc;
3832 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003833 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003834 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003835 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003836 return false;
3837}
3838
3839/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003840/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003841int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3842 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003843 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003844 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003845 bool AteExtraComma = false;
3846 if (ParseTypeAndValue(Val, Loc, PFS) ||
3847 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3848 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003849
Duncan Sands1df98592010-02-16 11:11:14 +00003850 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003851 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3852 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003853
Chris Lattnerdf986172009-01-02 07:01:27 +00003854 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003855 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003856}
3857
3858/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003859/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003860int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3861 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003862 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003863 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003864 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003865 if (ParseTypeAndValue(Val, Loc, PFS) ||
3866 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003867 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3868 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003869 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003870
Duncan Sands1df98592010-02-16 11:11:14 +00003871 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003872 return Error(PtrLoc, "store operand must be a pointer");
3873 if (!Val->getType()->isFirstClassType())
3874 return Error(Loc, "store operand must be a first class value");
3875 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3876 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003877
Chris Lattnerdf986172009-01-02 07:01:27 +00003878 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003879 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003880}
3881
3882/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003883/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003884/// FIXME: Remove support for getresult in LLVM 3.0
3885bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3886 Value *Val; LocTy ValLoc, EltLoc;
3887 unsigned Element;
3888 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3889 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003890 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003891 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003892
Duncan Sands1df98592010-02-16 11:11:14 +00003893 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003894 return Error(ValLoc, "getresult inst requires an aggregate operand");
3895 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3896 return Error(EltLoc, "invalid getresult index for value");
3897 Inst = ExtractValueInst::Create(Val, Element);
3898 return false;
3899}
3900
3901/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003902/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003903int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003904 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003905
Dan Gohmandcb40a32009-07-29 15:58:36 +00003906 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003907
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003908 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003909
Duncan Sands1df98592010-02-16 11:11:14 +00003910 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003911 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003912
Chris Lattnerdf986172009-01-02 07:01:27 +00003913 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003914 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003915 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003916 if (Lex.getKind() == lltok::MetadataVar) {
3917 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003918 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003919 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003920 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003921 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003922 return Error(EltLoc, "getelementptr index must be an integer");
3923 Indices.push_back(Val);
3924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003925
Chris Lattnerdf986172009-01-02 07:01:27 +00003926 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3927 Indices.begin(), Indices.end()))
3928 return Error(Loc, "invalid getelementptr indices");
3929 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003930 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003931 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003932 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003933}
3934
3935/// ParseExtractValue
3936/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003937int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003938 Value *Val; LocTy Loc;
3939 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003940 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003941 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003942 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003943 return true;
3944
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003945 if (!Val->getType()->isAggregateType())
3946 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003947
3948 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3949 Indices.end()))
3950 return Error(Loc, "invalid indices for extractvalue");
3951 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003952 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003953}
3954
3955/// ParseInsertValue
3956/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003957int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003958 Value *Val0, *Val1; LocTy Loc0, Loc1;
3959 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003960 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003961 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3962 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3963 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003964 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003965 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003966
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003967 if (!Val0->getType()->isAggregateType())
3968 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003969
Chris Lattnerdf986172009-01-02 07:01:27 +00003970 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3971 Indices.end()))
3972 return Error(Loc0, "invalid indices for insertvalue");
3973 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003974 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003975}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003976
3977//===----------------------------------------------------------------------===//
3978// Embedded metadata.
3979//===----------------------------------------------------------------------===//
3980
3981/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003982/// ::= Element (',' Element)*
3983/// Element
3984/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003985bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003986 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003987 // Check for an empty list.
3988 if (Lex.getKind() == lltok::rbrace)
3989 return false;
3990
Nick Lewycky21cc4462009-04-04 07:22:01 +00003991 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003992 // Null is a special case since it is typeless.
3993 if (EatIfPresent(lltok::kw_null)) {
3994 Elts.push_back(0);
3995 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003996 }
Chris Lattnera7352392009-12-30 04:42:57 +00003997
3998 Value *V = 0;
3999 PATypeHolder Ty(Type::getVoidTy(Context));
4000 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00004001 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00004002 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00004003 return true;
4004
Nick Lewyckycb337992009-05-10 20:57:05 +00004005 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004006 } while (EatIfPresent(lltok::comma));
4007
4008 return false;
4009}