blob: a3d77aea620fb9b580cbac4a8d042049b0ed71ba [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000026#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattner3ed88ef2009-01-02 08:05:26 +000029/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000030bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000031 // Prime the lexer.
32 Lex.Lex();
33
Chris Lattnerad7d1e22009-01-04 20:44:11 +000034 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000036}
37
38/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
39/// module.
40bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000041 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata.empty()) {
43 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
44 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
45 I != E; ++I) {
46 Instruction *Inst = I->first;
47 const std::vector<MDRef> &MDList = I->second;
48
49 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
50 unsigned SlotNo = MDList[i].MDSlot;
51
52 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
53 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000054 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000055 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
56 }
57 }
58 ForwardRefInstMetadata.clear();
59 }
60
61
Chris Lattner09d9ef42009-10-28 03:39:23 +000062 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
66 Function *TheFn = 0;
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
72
73 if (TheFn == 0)
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
75
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
79 0))
80 return true;
81
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
83 }
84
85
Chris Lattnerdf986172009-01-02 07:01:27 +000086 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000093 Twine(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000094
Chris Lattnerdf986172009-01-02 07:01:27 +000095 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
98 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000099
Chris Lattnerdf986172009-01-02 07:01:27 +0000100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000103 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000104
Devang Patel1c7eea62009-07-08 19:23:54 +0000105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000108 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000109
Devang Patel1c7eea62009-07-08 19:23:54 +0000110
Chris Lattnerdf986172009-01-02 07:01:27 +0000111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000114
Devang Patele4b27562009-08-28 23:24:31 +0000115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000117 return false;
118}
119
Chris Lattner09d9ef42009-10-28 03:39:23 +0000120bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
125 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000126 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127 if (Refs[i].first.Kind == ValID::t_LocalName)
128 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000129 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000130 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
131 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
132 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000133 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000134 } else {
135 Res = dyn_cast_or_null<BasicBlock>(
136 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
137 }
138
Chris Lattnercdfc9402009-11-01 01:27:45 +0000139 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000140 return Error(Refs[i].first.Loc,
141 "referenced value is not a basic block");
142
143 // Get the BlockAddress for this and update references to use it.
144 BlockAddress *BA = BlockAddress::get(TheFn, Res);
145 Refs[i].second->replaceAllUsesWith(BA);
146 Refs[i].second->eraseFromParent();
147 }
148 return false;
149}
150
151
Chris Lattnerdf986172009-01-02 07:01:27 +0000152//===----------------------------------------------------------------------===//
153// Top-Level Entities
154//===----------------------------------------------------------------------===//
155
156bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000157 while (1) {
158 switch (Lex.getKind()) {
159 default: return TokError("expected top-level entity");
160 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000161 case lltok::kw_declare: if (ParseDeclare()) return true; break;
162 case lltok::kw_define: if (ParseDefine()) return true; break;
163 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
164 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
165 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
166 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000167 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000169 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000170 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000171 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000172 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173
174 // The Global variable production with no name can have many different
175 // optional leading prefixes, the production is:
176 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000177 // OptionalAddrSpace OptionalUnNammedAddr
178 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000179 case lltok::kw_private: // OptionalLinkage
180 case lltok::kw_linker_private: // OptionalLinkage
181 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000182 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000183 case lltok::kw_internal: // OptionalLinkage
184 case lltok::kw_weak: // OptionalLinkage
185 case lltok::kw_weak_odr: // OptionalLinkage
186 case lltok::kw_linkonce: // OptionalLinkage
187 case lltok::kw_linkonce_odr: // OptionalLinkage
188 case lltok::kw_appending: // OptionalLinkage
189 case lltok::kw_dllexport: // OptionalLinkage
190 case lltok::kw_common: // OptionalLinkage
191 case lltok::kw_dllimport: // OptionalLinkage
192 case lltok::kw_extern_weak: // OptionalLinkage
193 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000194 unsigned Linkage, Visibility;
195 if (ParseOptionalLinkage(Linkage) ||
196 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000197 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 return true;
199 break;
200 }
201 case lltok::kw_default: // OptionalVisibility
202 case lltok::kw_hidden: // OptionalVisibility
203 case lltok::kw_protected: { // OptionalVisibility
204 unsigned Visibility;
205 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000206 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return true;
208 break;
209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000210
Chris Lattnerdf986172009-01-02 07:01:27 +0000211 case lltok::kw_thread_local: // OptionalThreadLocal
212 case lltok::kw_addrspace: // OptionalAddrSpace
213 case lltok::kw_constant: // GlobalType
214 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000215 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 break;
217 }
218 }
219}
220
221
222/// toplevelentity
223/// ::= 'module' 'asm' STRINGCONSTANT
224bool LLParser::ParseModuleAsm() {
225 assert(Lex.getKind() == lltok::kw_module);
226 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000227
228 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000229 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
230 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000231
Rafael Espindola38c4e532011-03-02 04:14:42 +0000232 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000233 return false;
234}
235
236/// toplevelentity
237/// ::= 'target' 'triple' '=' STRINGCONSTANT
238/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
239bool LLParser::ParseTargetDefinition() {
240 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000241 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000242 switch (Lex.Lex()) {
243 default: return TokError("unknown target property");
244 case lltok::kw_triple:
245 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000246 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
247 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000248 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000249 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000250 return false;
251 case lltok::kw_datalayout:
252 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
254 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000256 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 return false;
258 }
259}
260
261/// toplevelentity
262/// ::= 'deplibs' '=' '[' ']'
263/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
264bool LLParser::ParseDepLibs() {
265 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000266 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000267 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
268 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
269 return true;
270
271 if (EatIfPresent(lltok::rsquare))
272 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000273
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000274 std::string Str;
275 if (ParseStringConstant(Str)) return true;
276 M->addLibrary(Str);
277
278 while (EatIfPresent(lltok::comma)) {
279 if (ParseStringConstant(Str)) return true;
280 M->addLibrary(Str);
281 }
282
283 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000284}
285
Dan Gohman3845e502009-08-12 23:32:33 +0000286/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000287/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000288/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000289bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000290 unsigned TypeID = NumberedTypes.size();
291
292 // Handle the LocalVarID form.
293 if (Lex.getKind() == lltok::LocalVarID) {
294 if (Lex.getUIntVal() != TypeID)
295 return Error(Lex.getLoc(), "type expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000296 Twine(TypeID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000297 Lex.Lex(); // eat LocalVarID;
298
299 if (ParseToken(lltok::equal, "expected '=' after name"))
300 return true;
301 }
302
Chris Lattnerdf986172009-01-02 07:01:27 +0000303 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000304 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000305
Owen Anderson1d0be152009-08-13 21:58:54 +0000306 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000307 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000308
Chris Lattnerdf986172009-01-02 07:01:27 +0000309 // See if this type was previously referenced.
310 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
311 FI = ForwardRefTypeIDs.find(TypeID);
312 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000313 if (FI->second.first.get() == Ty)
314 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000315
Chris Lattnerdf986172009-01-02 07:01:27 +0000316 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
317 Ty = FI->second.first.get();
318 ForwardRefTypeIDs.erase(FI);
319 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000320
Chris Lattnerdf986172009-01-02 07:01:27 +0000321 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerdf986172009-01-02 07:01:27 +0000323 return false;
324}
325
326/// toplevelentity
327/// ::= LocalVar '=' 'type' type
328bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000331 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000332
Owen Anderson1d0be152009-08-13 21:58:54 +0000333 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000334
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000335 if (ParseToken(lltok::equal, "expected '=' after name") ||
336 ParseToken(lltok::kw_type, "expected 'type' after name") ||
337 ParseType(Ty))
338 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 // Set the type name, checking for conflicts as we do so.
341 bool AlreadyExists = M->addTypeName(Name, Ty);
342 if (!AlreadyExists) return false;
343
344 // See if this type is a forward reference. We need to eagerly resolve
345 // types to allow recursive type redefinitions below.
346 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
347 FI = ForwardRefTypes.find(Name);
348 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000349 if (FI->second.first.get() == Ty)
350 return Error(NameLoc, "self referential type is invalid");
351
Chris Lattnerdf986172009-01-02 07:01:27 +0000352 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
353 Ty = FI->second.first.get();
354 ForwardRefTypes.erase(FI);
355 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000356
Chris Lattnerdf986172009-01-02 07:01:27 +0000357 // Inserting a name that is already defined, get the existing name.
358 const Type *Existing = M->getTypeByName(Name);
359 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000360
Chris Lattnerdf986172009-01-02 07:01:27 +0000361 // Otherwise, this is an attempt to redefine a type. That's okay if
362 // the redefinition is identical to the original.
363 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
364 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000365
Chris Lattnerdf986172009-01-02 07:01:27 +0000366 // Any other kind of (non-equivalent) redefinition is an error.
367 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
368 Ty->getDescription() + "'");
369}
370
371
372/// toplevelentity
373/// ::= 'declare' FunctionHeader
374bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
376 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000377
Chris Lattnerdf986172009-01-02 07:01:27 +0000378 Function *F;
379 return ParseFunctionHeader(F, false);
380}
381
382/// toplevelentity
383/// ::= 'define' FunctionHeader '{' ...
384bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
386 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000387
Chris Lattnerdf986172009-01-02 07:01:27 +0000388 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000389 return ParseFunctionHeader(F, true) ||
390 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000391}
392
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000393/// ParseGlobalType
394/// ::= 'constant'
395/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000396bool LLParser::ParseGlobalType(bool &IsConstant) {
397 if (Lex.getKind() == lltok::kw_constant)
398 IsConstant = true;
399 else if (Lex.getKind() == lltok::kw_global)
400 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000401 else {
402 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000403 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000404 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000405 Lex.Lex();
406 return false;
407}
408
Dan Gohman3845e502009-08-12 23:32:33 +0000409/// ParseUnnamedGlobal:
410/// OptionalVisibility ALIAS ...
411/// OptionalLinkage OptionalVisibility ... -> global variable
412/// GlobalID '=' OptionalVisibility ALIAS ...
413/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
414bool LLParser::ParseUnnamedGlobal() {
415 unsigned VarID = NumberedVals.size();
416 std::string Name;
417 LocTy NameLoc = Lex.getLoc();
418
419 // Handle the GlobalID form.
420 if (Lex.getKind() == lltok::GlobalID) {
421 if (Lex.getUIntVal() != VarID)
422 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000423 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000424 Lex.Lex(); // eat GlobalID;
425
426 if (ParseToken(lltok::equal, "expected '=' after name"))
427 return true;
428 }
429
430 bool HasLinkage;
431 unsigned Linkage, Visibility;
432 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
433 ParseOptionalVisibility(Visibility))
434 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000435
Dan Gohman3845e502009-08-12 23:32:33 +0000436 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
437 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
438 return ParseAlias(Name, NameLoc, Visibility);
439}
440
Chris Lattnerdf986172009-01-02 07:01:27 +0000441/// ParseNamedGlobal:
442/// GlobalVar '=' OptionalVisibility ALIAS ...
443/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
444bool LLParser::ParseNamedGlobal() {
445 assert(Lex.getKind() == lltok::GlobalVar);
446 LocTy NameLoc = Lex.getLoc();
447 std::string Name = Lex.getStrVal();
448 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000449
Chris Lattnerdf986172009-01-02 07:01:27 +0000450 bool HasLinkage;
451 unsigned Linkage, Visibility;
452 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
453 ParseOptionalLinkage(Linkage, HasLinkage) ||
454 ParseOptionalVisibility(Visibility))
455 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000456
Chris Lattnerdf986172009-01-02 07:01:27 +0000457 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
458 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
459 return ParseAlias(Name, NameLoc, Visibility);
460}
461
Devang Patel256be962009-07-20 19:00:08 +0000462// MDString:
463// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000464bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000465 std::string Str;
466 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000467 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000468 return false;
469}
470
471// MDNode:
472// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000473//
474/// This version of ParseMDNodeID returns the slot number and null in the case
475/// of a forward reference.
476bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
477 // !{ ..., !42, ... }
478 if (ParseUInt32(SlotNo)) return true;
479
480 // Check existing MDNode.
481 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
482 Result = NumberedMetadata[SlotNo];
483 else
484 Result = 0;
485 return false;
486}
487
Chris Lattner4a72efc2009-12-30 04:15:23 +0000488bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000489 // !{ ..., !42, ... }
490 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000491 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000492
Chris Lattner449c3102010-04-01 05:14:45 +0000493 // If not a forward reference, just return it now.
494 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000495
Chris Lattner449c3102010-04-01 05:14:45 +0000496 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000497 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000498 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000499
500 if (NumberedMetadata.size() <= MID)
501 NumberedMetadata.resize(MID+1);
502 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000503 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000504 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000505}
Devang Patel256be962009-07-20 19:00:08 +0000506
Chris Lattner84d03b12009-12-29 22:35:39 +0000507/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000508/// !foo = !{ !1, !2 }
509bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000510 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000511 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000512 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000513
Chris Lattner84d03b12009-12-29 22:35:39 +0000514 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000515 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000516 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000517 return true;
518
Dan Gohman17aa92c2010-07-21 23:38:33 +0000519 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000520 if (Lex.getKind() != lltok::rbrace)
521 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000522 if (ParseToken(lltok::exclaim, "Expected '!' here"))
523 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000524
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000525 MDNode *N = 0;
526 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000527 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000528 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000529
530 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
531 return true;
532
Devang Pateleff2ab62009-07-29 00:34:02 +0000533 return false;
534}
535
Devang Patel923078c2009-07-01 19:21:12 +0000536/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000537/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000538bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000539 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000540 Lex.Lex();
541 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000542
543 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000544 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000545 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000546 if (ParseUInt32(MetadataID) ||
547 ParseToken(lltok::equal, "expected '=' here") ||
548 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000549 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000550 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000551 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000552 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000553 return true;
554
Jay Foadec9186b2011-04-21 19:59:31 +0000555 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000556
557 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000558 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000559 FI = ForwardRefMDNodes.find(MetadataID);
560 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000561 MDNode *Temp = FI->second.first;
562 Temp->replaceAllUsesWith(Init);
563 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000564 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000565
566 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
567 } else {
568 if (MetadataID >= NumberedMetadata.size())
569 NumberedMetadata.resize(MetadataID+1);
570
571 if (NumberedMetadata[MetadataID] != 0)
572 return TokError("Metadata id is already used");
573 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000574 }
575
Devang Patel923078c2009-07-01 19:21:12 +0000576 return false;
577}
578
Chris Lattnerdf986172009-01-02 07:01:27 +0000579/// ParseAlias:
580/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
581/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000582/// ::= TypeAndValue
583/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000584/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000585///
586/// Everything through visibility has already been parsed.
587///
588bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
589 unsigned Visibility) {
590 assert(Lex.getKind() == lltok::kw_alias);
591 Lex.Lex();
592 unsigned Linkage;
593 LocTy LinkageLoc = Lex.getLoc();
594 if (ParseOptionalLinkage(Linkage))
595 return true;
596
597 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000598 Linkage != GlobalValue::WeakAnyLinkage &&
599 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000600 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000601 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000602 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000603 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
604 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000605 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000606
Chris Lattnerdf986172009-01-02 07:01:27 +0000607 Constant *Aliasee;
608 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000609 if (Lex.getKind() != lltok::kw_bitcast &&
610 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000611 if (ParseGlobalTypeAndValue(Aliasee)) return true;
612 } else {
613 // The bitcast dest type is not present, it is implied by the dest type.
614 ValID ID;
615 if (ParseValID(ID)) return true;
616 if (ID.Kind != ValID::t_Constant)
617 return Error(AliaseeLoc, "invalid aliasee");
618 Aliasee = ID.ConstantVal;
619 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000620
Duncan Sands1df98592010-02-16 11:11:14 +0000621 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000622 return Error(AliaseeLoc, "alias must have pointer type");
623
624 // Okay, create the alias but do not insert it into the module yet.
625 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
626 (GlobalValue::LinkageTypes)Linkage, Name,
627 Aliasee);
628 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000629
Chris Lattnerdf986172009-01-02 07:01:27 +0000630 // See if this value already exists in the symbol table. If so, it is either
631 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000632 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 // See if this was a redefinition. If so, there is no entry in
634 // ForwardRefVals.
635 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
636 I = ForwardRefVals.find(Name);
637 if (I == ForwardRefVals.end())
638 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
639
640 // Otherwise, this was a definition of forward ref. Verify that types
641 // agree.
642 if (Val->getType() != GA->getType())
643 return Error(NameLoc,
644 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000645
Chris Lattnerdf986172009-01-02 07:01:27 +0000646 // If they agree, just RAUW the old value with the alias and remove the
647 // forward ref info.
648 Val->replaceAllUsesWith(GA);
649 Val->eraseFromParent();
650 ForwardRefVals.erase(I);
651 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattnerdf986172009-01-02 07:01:27 +0000653 // Insert into the module, we know its name won't collide now.
654 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000655 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000656
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 return false;
658}
659
660/// ParseGlobal
661/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000662/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000663/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000664/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000665///
666/// Everything through visibility has been parsed already.
667///
668bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
669 unsigned Linkage, bool HasLinkage,
670 unsigned Visibility) {
671 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000672 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000673 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000674 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000675
Owen Anderson1d0be152009-08-13 21:58:54 +0000676 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
678 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000679 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
680 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 ParseGlobalType(IsConstant) ||
682 ParseType(Ty, TyLoc))
683 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 // If the linkage is specified and is external, then no initializer is
686 // present.
687 Constant *Init = 0;
688 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000689 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000690 Linkage != GlobalValue::ExternalLinkage)) {
691 if (ParseGlobalValue(Ty, Init))
692 return true;
693 }
694
Duncan Sands1df98592010-02-16 11:11:14 +0000695 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000696 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000697
Chris Lattnerdf986172009-01-02 07:01:27 +0000698 GlobalVariable *GV = 0;
699
700 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000701 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000702 if (GlobalValue *GVal = M->getNamedValue(Name)) {
703 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
704 return Error(NameLoc, "redefinition of global '@" + Name + "'");
705 GV = cast<GlobalVariable>(GVal);
706 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000707 } else {
708 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
709 I = ForwardRefValIDs.find(NumberedVals.size());
710 if (I != ForwardRefValIDs.end()) {
711 GV = cast<GlobalVariable>(I->second.first);
712 ForwardRefValIDs.erase(I);
713 }
714 }
715
716 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000718 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 } else {
720 if (GV->getType()->getElementType() != Ty)
721 return Error(TyLoc,
722 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000723
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 // Move the forward-reference to the correct spot in the module.
725 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
726 }
727
728 if (Name.empty())
729 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000730
Chris Lattnerdf986172009-01-02 07:01:27 +0000731 // Set the parsed properties on the global.
732 if (Init)
733 GV->setInitializer(Init);
734 GV->setConstant(IsConstant);
735 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
736 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
737 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000738 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000739
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 // Parse attributes on the global.
741 while (Lex.getKind() == lltok::comma) {
742 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743
Chris Lattnerdf986172009-01-02 07:01:27 +0000744 if (Lex.getKind() == lltok::kw_section) {
745 Lex.Lex();
746 GV->setSection(Lex.getStrVal());
747 if (ParseToken(lltok::StringConstant, "expected global section string"))
748 return true;
749 } else if (Lex.getKind() == lltok::kw_align) {
750 unsigned Alignment;
751 if (ParseOptionalAlignment(Alignment)) return true;
752 GV->setAlignment(Alignment);
753 } else {
754 TokError("unknown global variable property!");
755 }
756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattnerdf986172009-01-02 07:01:27 +0000758 return false;
759}
760
761
762//===----------------------------------------------------------------------===//
763// GlobalValue Reference/Resolution Routines.
764//===----------------------------------------------------------------------===//
765
766/// GetGlobalVal - Get a value with the specified name or ID, creating a
767/// forward reference record if needed. This can return null if the value
768/// exists but does not have the right type.
769GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
770 LocTy Loc) {
771 const PointerType *PTy = dyn_cast<PointerType>(Ty);
772 if (PTy == 0) {
773 Error(Loc, "global variable reference must have pointer type");
774 return 0;
775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 // Look this name up in the normal function symbol table.
778 GlobalValue *Val =
779 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000780
Chris Lattnerdf986172009-01-02 07:01:27 +0000781 // If this is a forward reference for the value, see if we already created a
782 // forward ref record.
783 if (Val == 0) {
784 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
785 I = ForwardRefVals.find(Name);
786 if (I != ForwardRefVals.end())
787 Val = I->second.first;
788 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000789
Chris Lattnerdf986172009-01-02 07:01:27 +0000790 // If we have the value in the symbol table or fwd-ref table, return it.
791 if (Val) {
792 if (Val->getType() == Ty) return Val;
793 Error(Loc, "'@" + Name + "' defined with type '" +
794 Val->getType()->getDescription() + "'");
795 return 0;
796 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797
Chris Lattnerdf986172009-01-02 07:01:27 +0000798 // Otherwise, create a new forward reference for this value and remember it.
799 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000800 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
801 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000802 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000803 Error(Loc, "function may not return opaque type");
804 return 0;
805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000807 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000808 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000809 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
810 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000812
Chris Lattnerdf986172009-01-02 07:01:27 +0000813 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
814 return FwdVal;
815}
816
817GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
818 const PointerType *PTy = dyn_cast<PointerType>(Ty);
819 if (PTy == 0) {
820 Error(Loc, "global variable reference must have pointer type");
821 return 0;
822 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000823
Chris Lattnerdf986172009-01-02 07:01:27 +0000824 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000825
Chris Lattnerdf986172009-01-02 07:01:27 +0000826 // If this is a forward reference for the value, see if we already created a
827 // forward ref record.
828 if (Val == 0) {
829 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
830 I = ForwardRefValIDs.find(ID);
831 if (I != ForwardRefValIDs.end())
832 Val = I->second.first;
833 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000834
Chris Lattnerdf986172009-01-02 07:01:27 +0000835 // If we have the value in the symbol table or fwd-ref table, return it.
836 if (Val) {
837 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000838 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +0000839 Val->getType()->getDescription() + "'");
840 return 0;
841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000842
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 // Otherwise, create a new forward reference for this value and remember it.
844 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000845 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
846 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000847 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000848 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000849 return 0;
850 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000851 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000852 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000853 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
854 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000855 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000856
Chris Lattnerdf986172009-01-02 07:01:27 +0000857 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
858 return FwdVal;
859}
860
861
862//===----------------------------------------------------------------------===//
863// Helper Routines.
864//===----------------------------------------------------------------------===//
865
866/// ParseToken - If the current token has the specified kind, eat it and return
867/// success. Otherwise, emit the specified error and return failure.
868bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
869 if (Lex.getKind() != T)
870 return TokError(ErrMsg);
871 Lex.Lex();
872 return false;
873}
874
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000875/// ParseStringConstant
876/// ::= StringConstant
877bool LLParser::ParseStringConstant(std::string &Result) {
878 if (Lex.getKind() != lltok::StringConstant)
879 return TokError("expected string constant");
880 Result = Lex.getStrVal();
881 Lex.Lex();
882 return false;
883}
884
885/// ParseUInt32
886/// ::= uint32
887bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000888 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
889 return TokError("expected integer");
890 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
891 if (Val64 != unsigned(Val64))
892 return TokError("expected 32-bit integer (too large)");
893 Val = Val64;
894 Lex.Lex();
895 return false;
896}
897
898
899/// ParseOptionalAddrSpace
900/// := /*empty*/
901/// := 'addrspace' '(' uint32 ')'
902bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
903 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000904 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000905 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000906 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000907 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000908 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000909}
Chris Lattnerdf986172009-01-02 07:01:27 +0000910
911/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
912/// indicates what kind of attribute list this is: 0: function arg, 1: result,
913/// 2: function attr.
914bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
915 Attrs = Attribute::None;
916 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000917
Chris Lattnerdf986172009-01-02 07:01:27 +0000918 while (1) {
919 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000920 default: // End of attributes.
921 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
922 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000923
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000924 // As a hack, we allow "align 2" on functions as a synonym for
925 // "alignstack 2".
926 if (AttrKind == 2 &&
927 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
928 return Error(AttrLoc, "invalid use of attribute on a function");
929
930 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000931 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000932
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000934 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
935 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
936 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
937 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
938 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
939 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
940 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
941 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000942
Devang Patel578efa92009-06-05 21:57:13 +0000943 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
944 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000945 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Devang Patel578efa92009-06-05 21:57:13 +0000946 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
947 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
948 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000949 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000950 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
951 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
952 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
953 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
954 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
955 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000956 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000957 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
John McCall3a3465b2011-06-15 20:36:13 +0000958 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Charles Davis1e063d12010-02-12 00:31:15 +0000960 case lltok::kw_alignstack: {
961 unsigned Alignment;
962 if (ParseOptionalStackAlignment(Alignment))
963 return true;
964 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
965 continue;
966 }
967
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 case lltok::kw_align: {
969 unsigned Alignment;
970 if (ParseOptionalAlignment(Alignment))
971 return true;
972 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
973 continue;
974 }
Charles Davis1e063d12010-02-12 00:31:15 +0000975
Chris Lattnerdf986172009-01-02 07:01:27 +0000976 }
977 Lex.Lex();
978 }
979}
980
981/// ParseOptionalLinkage
982/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000983/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000984/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000985/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000986/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000987/// ::= 'internal'
988/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000989/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000990/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000991/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000992/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000993/// ::= 'appending'
994/// ::= 'dllexport'
995/// ::= 'common'
996/// ::= 'dllimport'
997/// ::= 'extern_weak'
998/// ::= 'external'
999bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1000 HasLinkage = false;
1001 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001002 default: Res=GlobalValue::ExternalLinkage; return false;
1003 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1004 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001005 case lltok::kw_linker_private_weak:
1006 Res = GlobalValue::LinkerPrivateWeakLinkage;
1007 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001008 case lltok::kw_linker_private_weak_def_auto:
1009 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1010 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001011 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1012 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1013 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1014 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1015 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001016 case lltok::kw_available_externally:
1017 Res = GlobalValue::AvailableExternallyLinkage;
1018 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001019 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1020 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1021 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1022 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1023 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1024 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001025 }
1026 Lex.Lex();
1027 HasLinkage = true;
1028 return false;
1029}
1030
1031/// ParseOptionalVisibility
1032/// ::= /*empty*/
1033/// ::= 'default'
1034/// ::= 'hidden'
1035/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001036///
Chris Lattnerdf986172009-01-02 07:01:27 +00001037bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1038 switch (Lex.getKind()) {
1039 default: Res = GlobalValue::DefaultVisibility; return false;
1040 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1041 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1042 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1043 }
1044 Lex.Lex();
1045 return false;
1046}
1047
1048/// ParseOptionalCallingConv
1049/// ::= /*empty*/
1050/// ::= 'ccc'
1051/// ::= 'fastcc'
1052/// ::= 'coldcc'
1053/// ::= 'x86_stdcallcc'
1054/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001055/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001056/// ::= 'arm_apcscc'
1057/// ::= 'arm_aapcscc'
1058/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001059/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001060/// ::= 'ptx_kernel'
1061/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001062/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001063///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001064bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001065 switch (Lex.getKind()) {
1066 default: CC = CallingConv::C; return false;
1067 case lltok::kw_ccc: CC = CallingConv::C; break;
1068 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1069 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1070 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1071 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001072 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001073 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1074 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1075 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001076 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001077 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1078 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001079 case lltok::kw_cc: {
1080 unsigned ArbitraryCC;
1081 Lex.Lex();
1082 if (ParseUInt32(ArbitraryCC)) {
1083 return true;
1084 } else
1085 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1086 return false;
1087 }
1088 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001089 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001090
Chris Lattnerdf986172009-01-02 07:01:27 +00001091 Lex.Lex();
1092 return false;
1093}
1094
Chris Lattnerb8c46862009-12-30 05:31:19 +00001095/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001096/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001097bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1098 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001099 do {
1100 if (Lex.getKind() != lltok::MetadataVar)
1101 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001102
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001103 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001104 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001105 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001106
Chris Lattner442ffa12009-12-29 21:53:55 +00001107 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001108 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001109
1110 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001111 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001112
Dan Gohman68261142010-08-24 14:35:45 +00001113 // This code is similar to that of ParseMetadataValue, however it needs to
1114 // have special-case code for a forward reference; see the comments on
1115 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1116 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001117 if (Lex.getKind() == lltok::lbrace) {
1118 ValID ID;
1119 if (ParseMetadataListValue(ID, PFS))
1120 return true;
1121 assert(ID.Kind == ValID::t_MDNode);
1122 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001123 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001124 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001125 if (ParseMDNodeID(Node, NodeID))
1126 return true;
1127 if (Node) {
1128 // If we got the node, add it to the instruction.
1129 Inst->setMetadata(MDK, Node);
1130 } else {
1131 MDRef R = { Loc, MDK, NodeID };
1132 // Otherwise, remember that this should be resolved later.
1133 ForwardRefInstMetadata[Inst].push_back(R);
1134 }
Chris Lattner449c3102010-04-01 05:14:45 +00001135 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001136
1137 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001138 } while (EatIfPresent(lltok::comma));
1139 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001140}
1141
Chris Lattnerdf986172009-01-02 07:01:27 +00001142/// ParseOptionalAlignment
1143/// ::= /* empty */
1144/// ::= 'align' 4
1145bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1146 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001147 if (!EatIfPresent(lltok::kw_align))
1148 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001149 LocTy AlignLoc = Lex.getLoc();
1150 if (ParseUInt32(Alignment)) return true;
1151 if (!isPowerOf2_32(Alignment))
1152 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001153 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001154 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001155 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001156}
1157
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001158/// ParseOptionalCommaAlign
1159/// ::=
1160/// ::= ',' align 4
1161///
1162/// This returns with AteExtraComma set to true if it ate an excess comma at the
1163/// end.
1164bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1165 bool &AteExtraComma) {
1166 AteExtraComma = false;
1167 while (EatIfPresent(lltok::comma)) {
1168 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001169 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001170 AteExtraComma = true;
1171 return false;
1172 }
1173
Chris Lattner093eed12010-04-23 00:50:50 +00001174 if (Lex.getKind() != lltok::kw_align)
1175 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001176
Chris Lattner093eed12010-04-23 00:50:50 +00001177 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001178 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001179
Devang Patelf633a062009-09-17 23:04:48 +00001180 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001181}
1182
Charles Davis1e063d12010-02-12 00:31:15 +00001183/// ParseOptionalStackAlignment
1184/// ::= /* empty */
1185/// ::= 'alignstack' '(' 4 ')'
1186bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1187 Alignment = 0;
1188 if (!EatIfPresent(lltok::kw_alignstack))
1189 return false;
1190 LocTy ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::lparen))
1192 return Error(ParenLoc, "expected '('");
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::rparen))
1197 return Error(ParenLoc, "expected ')'");
1198 if (!isPowerOf2_32(Alignment))
1199 return Error(AlignLoc, "stack alignment is not a power of two");
1200 return false;
1201}
Devang Patelf633a062009-09-17 23:04:48 +00001202
Chris Lattner628c13a2009-12-30 05:14:00 +00001203/// ParseIndexList - This parses the index list for an insert/extractvalue
1204/// instruction. This sets AteExtraComma in the case where we eat an extra
1205/// comma at the end of the line and find that it is followed by metadata.
1206/// Clients that don't allow metadata can call the version of this function that
1207/// only takes one argument.
1208///
Chris Lattnerdf986172009-01-02 07:01:27 +00001209/// ParseIndexList
1210/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001211///
1212bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1213 bool &AteExtraComma) {
1214 AteExtraComma = false;
1215
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 if (Lex.getKind() != lltok::comma)
1217 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001218
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001219 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1222 return false;
1223 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001224 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001225 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001226 Indices.push_back(Idx);
1227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001228
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 return false;
1230}
1231
1232//===----------------------------------------------------------------------===//
1233// Type Parsing.
1234//===----------------------------------------------------------------------===//
1235
1236/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001237bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1238 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001240
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 // Verify no unresolved uprefs.
1242 if (!UpRefs.empty())
1243 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001244
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001245 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001246 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001247
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 return false;
1249}
1250
1251/// HandleUpRefs - Every time we finish a new layer of types, this function is
1252/// called. It loops through the UpRefs vector, which is a list of the
1253/// currently active types. For each type, if the up-reference is contained in
1254/// the newly completed type, we decrement the level count. When the level
1255/// count reaches zero, the up-referenced type is the type that is passed in:
1256/// thus we can complete the cycle.
1257///
1258PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1259 // If Ty isn't abstract, or if there are no up-references in it, then there is
1260 // nothing to resolve here.
1261 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001262
Chris Lattnerdf986172009-01-02 07:01:27 +00001263 PATypeHolder Ty(ty);
1264#if 0
David Greene0e28d762009-12-23 23:38:28 +00001265 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001266 << "' newly formed. Resolving upreferences.\n"
1267 << UpRefs.size() << " upreferences active!\n";
1268#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001269
Chris Lattnerdf986172009-01-02 07:01:27 +00001270 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1271 // to zero), we resolve them all together before we resolve them to Ty. At
1272 // the end of the loop, if there is anything to resolve to Ty, it will be in
1273 // this variable.
1274 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1277 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1278 bool ContainsType =
1279 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1280 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001281
Chris Lattnerdf986172009-01-02 07:01:27 +00001282#if 0
David Greene0e28d762009-12-23 23:38:28 +00001283 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1285 << (ContainsType ? "true" : "false")
1286 << " level=" << UpRefs[i].NestingLevel << "\n";
1287#endif
1288 if (!ContainsType)
1289 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 // Decrement level of upreference
1292 unsigned Level = --UpRefs[i].NestingLevel;
1293 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001294
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1296 if (Level != 0)
1297 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001298
Chris Lattnerdf986172009-01-02 07:01:27 +00001299#if 0
David Greene0e28d762009-12-23 23:38:28 +00001300 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001301#endif
1302 if (!TypeToResolve)
1303 TypeToResolve = UpRefs[i].UpRefTy;
1304 else
1305 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1306 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1307 --i; // Do not skip the next element.
1308 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001309
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 if (TypeToResolve)
1311 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001312
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 return Ty;
1314}
1315
1316
1317/// ParseTypeRec - The recursive function used to process the internal
1318/// implementation details of types.
1319bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1320 switch (Lex.getKind()) {
1321 default:
1322 return TokError("expected type");
1323 case lltok::Type:
1324 // TypeRec ::= 'float' | 'void' (etc)
1325 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001326 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 break;
1328 case lltok::kw_opaque:
1329 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001330 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001331 Lex.Lex();
1332 break;
1333 case lltok::lbrace:
1334 // TypeRec ::= '{' ... '}'
1335 if (ParseStructType(Result, false))
1336 return true;
1337 break;
1338 case lltok::lsquare:
1339 // TypeRec ::= '[' ... ']'
1340 Lex.Lex(); // eat the lsquare.
1341 if (ParseArrayVectorType(Result, false))
1342 return true;
1343 break;
1344 case lltok::less: // Either vector or packed struct.
1345 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001346 Lex.Lex();
1347 if (Lex.getKind() == lltok::lbrace) {
1348 if (ParseStructType(Result, true) ||
1349 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 } else if (ParseArrayVectorType(Result, true))
1352 return true;
1353 break;
1354 case lltok::LocalVar:
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 // TypeRec ::= %foo
1356 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1357 Result = T;
1358 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001359 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001360 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1361 std::make_pair(Result,
1362 Lex.getLoc())));
1363 M->addTypeName(Lex.getStrVal(), Result.get());
1364 }
1365 Lex.Lex();
1366 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001367
Chris Lattnerdf986172009-01-02 07:01:27 +00001368 case lltok::LocalVarID:
1369 // TypeRec ::= %4
1370 if (Lex.getUIntVal() < NumberedTypes.size())
1371 Result = NumberedTypes[Lex.getUIntVal()];
1372 else {
1373 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1374 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1375 if (I != ForwardRefTypeIDs.end())
1376 Result = I->second.first;
1377 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001378 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001379 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1380 std::make_pair(Result,
1381 Lex.getLoc())));
1382 }
1383 }
1384 Lex.Lex();
1385 break;
1386 case lltok::backslash: {
1387 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001389 unsigned Val;
1390 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001391 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001392 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1393 Result = OT;
1394 break;
1395 }
1396 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001397
1398 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001399 while (1) {
1400 switch (Lex.getKind()) {
1401 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001402 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001403
1404 // TypeRec ::= TypeRec '*'
1405 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001406 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001408 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001409 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001410 if (!PointerType::isValidElementType(Result.get()))
1411 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001412 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 Lex.Lex();
1414 break;
1415
1416 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1417 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001418 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001420 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001421 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001422 if (!PointerType::isValidElementType(Result.get()))
1423 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 unsigned AddrSpace;
1425 if (ParseOptionalAddrSpace(AddrSpace) ||
1426 ParseToken(lltok::star, "expected '*' in address space"))
1427 return true;
1428
Owen Andersondebcb012009-07-29 22:17:13 +00001429 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001430 break;
1431 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001432
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1434 case lltok::lparen:
1435 if (ParseFunctionType(Result))
1436 return true;
1437 break;
1438 }
1439 }
1440}
1441
1442/// ParseParameterList
1443/// ::= '(' ')'
1444/// ::= '(' Arg (',' Arg)* ')'
1445/// Arg
1446/// ::= Type OptionalAttributes Value OptionalAttributes
1447bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1448 PerFunctionState &PFS) {
1449 if (ParseToken(lltok::lparen, "expected '(' in call"))
1450 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001451
Chris Lattnerdf986172009-01-02 07:01:27 +00001452 while (Lex.getKind() != lltok::rparen) {
1453 // If this isn't the first argument, we need a comma.
1454 if (!ArgList.empty() &&
1455 ParseToken(lltok::comma, "expected ',' in argument list"))
1456 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001457
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 // Parse the argument.
1459 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001460 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001461 unsigned ArgAttrs1 = Attribute::None;
1462 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001463 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001464 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001465 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001466
Chris Lattner287881d2009-12-30 02:11:14 +00001467 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001468 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001469 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001470 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1471 }
1472
1473 Lex.Lex(); // Lex the ')'.
1474 return false;
1475}
1476
1477
1478
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001479/// ParseArgumentList - Parse the argument list for a function type or function
1480/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001481/// ::= '(' ArgTypeListI ')'
1482/// ArgTypeListI
1483/// ::= /*empty*/
1484/// ::= '...'
1485/// ::= ArgTypeList ',' '...'
1486/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001487///
Chris Lattnerdf986172009-01-02 07:01:27 +00001488bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001489 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001490 isVarArg = false;
1491 assert(Lex.getKind() == lltok::lparen);
1492 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001493
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 if (Lex.getKind() == lltok::rparen) {
1495 // empty
1496 } else if (Lex.getKind() == lltok::dotdotdot) {
1497 isVarArg = true;
1498 Lex.Lex();
1499 } else {
1500 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001501 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001502 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001504
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001505 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1506 // types (such as a function returning a pointer to itself). If parsing a
1507 // function prototype, we require fully resolved types.
1508 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001509 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001510
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001511 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001512 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001513
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001514 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001515 Name = Lex.getStrVal();
1516 Lex.Lex();
1517 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001518
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001519 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001520 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001521
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001524 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001525 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001528 break;
1529 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001530
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 // Otherwise must be an argument type.
1532 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001533 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001534 ParseOptionalAttrs(Attrs, 0)) return true;
1535
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001536 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001537 return Error(TypeLoc, "argument can not have void type");
1538
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001539 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 Name = Lex.getStrVal();
1541 Lex.Lex();
1542 } else {
1543 Name = "";
1544 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001545
Duncan Sands47c51882010-02-16 14:50:09 +00001546 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001547 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001548
Chris Lattnerdf986172009-01-02 07:01:27 +00001549 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1550 }
1551 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001552
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001553 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001554}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001555
Chris Lattnerdf986172009-01-02 07:01:27 +00001556/// ParseFunctionType
1557/// ::= Type ArgumentList OptionalAttrs
1558bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1559 assert(Lex.getKind() == lltok::lparen);
1560
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001561 if (!FunctionType::isValidReturnType(Result))
1562 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 std::vector<ArgInfo> ArgList;
1565 bool isVarArg;
1566 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001567 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001568 // FIXME: Allow, but ignore attributes on function types!
1569 // FIXME: Remove in LLVM 3.0
1570 ParseOptionalAttrs(Attrs, 2))
1571 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattnerdf986172009-01-02 07:01:27 +00001573 // Reject names on the arguments lists.
1574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1575 if (!ArgList[i].Name.empty())
1576 return Error(ArgList[i].Loc, "argument name invalid in function type");
1577 if (!ArgList[i].Attrs != 0) {
1578 // Allow but ignore attributes on function types; this permits
1579 // auto-upgrade.
1580 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1581 }
1582 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Chris Lattnerdf986172009-01-02 07:01:27 +00001584 std::vector<const Type*> ArgListTy;
1585 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1586 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001587
Owen Andersondebcb012009-07-29 22:17:13 +00001588 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001589 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 return false;
1591}
1592
1593/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1594/// TypeRec
1595/// ::= '{' '}'
1596/// ::= '{' TypeRec (',' TypeRec)* '}'
1597/// ::= '<' '{' '}' '>'
1598/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1599bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1600 assert(Lex.getKind() == lltok::lbrace);
1601 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001603 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001604 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001605 return false;
1606 }
1607
1608 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001609 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 if (ParseTypeRec(Result)) return true;
1611 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001612
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001613 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001614 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001615 if (!StructType::isValidElementType(Result))
1616 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001618 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001619 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001620 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001621
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001622 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001623 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001624 if (!StructType::isValidElementType(Result))
1625 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001626
Chris Lattnerdf986172009-01-02 07:01:27 +00001627 ParamsList.push_back(Result);
1628 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001630 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1631 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001632
Chris Lattnerdf986172009-01-02 07:01:27 +00001633 std::vector<const Type*> ParamsListTy;
1634 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1635 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001636 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001637 return false;
1638}
1639
1640/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1641/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001643/// ::= '[' APSINTVAL 'x' Types ']'
1644/// ::= '<' APSINTVAL 'x' Types '>'
1645bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1646 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1647 Lex.getAPSIntVal().getBitWidth() > 64)
1648 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattnerdf986172009-01-02 07:01:27 +00001650 LocTy SizeLoc = Lex.getLoc();
1651 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001652 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001653
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001654 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1655 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001656
1657 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001658 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001659 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001660
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001661 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001662 return Error(TypeLoc, "array and vector element type cannot be void");
1663
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001664 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1665 "expected end of sequential type"))
1666 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattnerdf986172009-01-02 07:01:27 +00001668 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001669 if (Size == 0)
1670 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001671 if ((unsigned)Size != Size)
1672 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001673 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001674 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001675 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001676 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001677 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001678 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001679 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001680 }
1681 return false;
1682}
1683
1684//===----------------------------------------------------------------------===//
1685// Function Semantic Analysis.
1686//===----------------------------------------------------------------------===//
1687
Chris Lattner09d9ef42009-10-28 03:39:23 +00001688LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1689 int functionNumber)
1690 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001691
1692 // Insert unnamed arguments into the NumberedVals list.
1693 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1694 AI != E; ++AI)
1695 if (!AI->hasName())
1696 NumberedVals.push_back(AI);
1697}
1698
1699LLParser::PerFunctionState::~PerFunctionState() {
1700 // If there were any forward referenced non-basicblock values, delete them.
1701 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1702 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1703 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001704 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001705 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 delete I->second.first;
1707 I->second.first = 0;
1708 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1711 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1712 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001713 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001714 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001715 delete I->second.first;
1716 I->second.first = 0;
1717 }
1718}
1719
Chris Lattner09d9ef42009-10-28 03:39:23 +00001720bool LLParser::PerFunctionState::FinishFunction() {
1721 // Check to see if someone took the address of labels in this block.
1722 if (!P.ForwardRefBlockAddresses.empty()) {
1723 ValID FunctionID;
1724 if (!F.getName().empty()) {
1725 FunctionID.Kind = ValID::t_GlobalName;
1726 FunctionID.StrVal = F.getName();
1727 } else {
1728 FunctionID.Kind = ValID::t_GlobalID;
1729 FunctionID.UIntVal = FunctionNumber;
1730 }
1731
1732 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1733 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1734 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1735 // Resolve all these references.
1736 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1737 return true;
1738
1739 P.ForwardRefBlockAddresses.erase(FRBAI);
1740 }
1741 }
1742
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 if (!ForwardRefVals.empty())
1744 return P.Error(ForwardRefVals.begin()->second.second,
1745 "use of undefined value '%" + ForwardRefVals.begin()->first +
1746 "'");
1747 if (!ForwardRefValIDs.empty())
1748 return P.Error(ForwardRefValIDs.begin()->second.second,
1749 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001750 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001751 return false;
1752}
1753
1754
1755/// GetVal - Get a value with the specified name or ID, creating a
1756/// forward reference record if needed. This can return null if the value
1757/// exists but does not have the right type.
1758Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1759 const Type *Ty, LocTy Loc) {
1760 // Look this name up in the normal function symbol table.
1761 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattnerdf986172009-01-02 07:01:27 +00001763 // If this is a forward reference for the value, see if we already created a
1764 // forward ref record.
1765 if (Val == 0) {
1766 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1767 I = ForwardRefVals.find(Name);
1768 if (I != ForwardRefVals.end())
1769 Val = I->second.first;
1770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001771
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 // If we have the value in the symbol table or fwd-ref table, return it.
1773 if (Val) {
1774 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001775 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001776 P.Error(Loc, "'%" + Name + "' is not a basic block");
1777 else
1778 P.Error(Loc, "'%" + Name + "' defined with type '" +
1779 Val->getType()->getDescription() + "'");
1780 return 0;
1781 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001782
Chris Lattnerdf986172009-01-02 07:01:27 +00001783 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001784 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 P.Error(Loc, "invalid use of a non-first-class type");
1786 return 0;
1787 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001788
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 // Otherwise, create a new forward reference for this value and remember it.
1790 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001791 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001792 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 else
1794 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001795
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1797 return FwdVal;
1798}
1799
1800Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1801 LocTy Loc) {
1802 // Look this name up in the normal function symbol table.
1803 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001804
Chris Lattnerdf986172009-01-02 07:01:27 +00001805 // If this is a forward reference for the value, see if we already created a
1806 // forward ref record.
1807 if (Val == 0) {
1808 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1809 I = ForwardRefValIDs.find(ID);
1810 if (I != ForwardRefValIDs.end())
1811 Val = I->second.first;
1812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001813
Chris Lattnerdf986172009-01-02 07:01:27 +00001814 // If we have the value in the symbol table or fwd-ref table, return it.
1815 if (Val) {
1816 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001817 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001818 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001820 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001821 Val->getType()->getDescription() + "'");
1822 return 0;
1823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001824
Duncan Sands47c51882010-02-16 14:50:09 +00001825 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 P.Error(Loc, "invalid use of a non-first-class type");
1827 return 0;
1828 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001829
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 // Otherwise, create a new forward reference for this value and remember it.
1831 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001832 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001833 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001834 else
1835 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001836
Chris Lattnerdf986172009-01-02 07:01:27 +00001837 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1838 return FwdVal;
1839}
1840
1841/// SetInstName - After an instruction is parsed and inserted into its
1842/// basic block, this installs its name.
1843bool LLParser::PerFunctionState::SetInstName(int NameID,
1844 const std::string &NameStr,
1845 LocTy NameLoc, Instruction *Inst) {
1846 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001847 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 if (NameID != -1 || !NameStr.empty())
1849 return P.Error(NameLoc, "instructions returning void cannot have a name");
1850 return false;
1851 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852
Chris Lattnerdf986172009-01-02 07:01:27 +00001853 // If this was a numbered instruction, verify that the instruction is the
1854 // expected value and resolve any forward references.
1855 if (NameStr.empty()) {
1856 // If neither a name nor an ID was specified, just use the next ID.
1857 if (NameID == -1)
1858 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 if (unsigned(NameID) != NumberedVals.size())
1861 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001862 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1865 ForwardRefValIDs.find(NameID);
1866 if (FI != ForwardRefValIDs.end()) {
1867 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001868 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 FI->second.first->getType()->getDescription() + "'");
1870 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001871 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 ForwardRefValIDs.erase(FI);
1873 }
1874
1875 NumberedVals.push_back(Inst);
1876 return false;
1877 }
1878
1879 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1880 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1881 FI = ForwardRefVals.find(NameStr);
1882 if (FI != ForwardRefVals.end()) {
1883 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001884 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001885 FI->second.first->getType()->getDescription() + "'");
1886 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001887 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001888 ForwardRefVals.erase(FI);
1889 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001890
Chris Lattnerdf986172009-01-02 07:01:27 +00001891 // Set the name on the instruction.
1892 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001893
Benjamin Krameraf812352010-10-16 11:28:23 +00001894 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001895 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001896 NameStr + "'");
1897 return false;
1898}
1899
1900/// GetBB - Get a basic block with the specified name or ID, creating a
1901/// forward reference record if needed.
1902BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1903 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001904 return cast_or_null<BasicBlock>(GetVal(Name,
1905 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001906}
1907
1908BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001909 return cast_or_null<BasicBlock>(GetVal(ID,
1910 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001911}
1912
1913/// DefineBB - Define the specified basic block, which is either named or
1914/// unnamed. If there is an error, this returns null otherwise it returns
1915/// the block being defined.
1916BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1917 LocTy Loc) {
1918 BasicBlock *BB;
1919 if (Name.empty())
1920 BB = GetBB(NumberedVals.size(), Loc);
1921 else
1922 BB = GetBB(Name, Loc);
1923 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 // Move the block to the end of the function. Forward ref'd blocks are
1926 // inserted wherever they happen to be referenced.
1927 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 // Remove the block from forward ref sets.
1930 if (Name.empty()) {
1931 ForwardRefValIDs.erase(NumberedVals.size());
1932 NumberedVals.push_back(BB);
1933 } else {
1934 // BB forward references are already in the function symbol table.
1935 ForwardRefVals.erase(Name);
1936 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 return BB;
1939}
1940
1941//===----------------------------------------------------------------------===//
1942// Constants.
1943//===----------------------------------------------------------------------===//
1944
1945/// ParseValID - Parse an abstract value that doesn't necessarily have a
1946/// type implied. For example, if we parse "4" we don't know what integer type
1947/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001948/// sanity. PFS is used to convert function-local operands of metadata (since
1949/// metadata operands are not just parsed here but also converted to values).
1950/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001951bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 ID.Loc = Lex.getLoc();
1953 switch (Lex.getKind()) {
1954 default: return TokError("expected value token");
1955 case lltok::GlobalID: // @42
1956 ID.UIntVal = Lex.getUIntVal();
1957 ID.Kind = ValID::t_GlobalID;
1958 break;
1959 case lltok::GlobalVar: // @foo
1960 ID.StrVal = Lex.getStrVal();
1961 ID.Kind = ValID::t_GlobalName;
1962 break;
1963 case lltok::LocalVarID: // %42
1964 ID.UIntVal = Lex.getUIntVal();
1965 ID.Kind = ValID::t_LocalID;
1966 break;
1967 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001968 ID.StrVal = Lex.getStrVal();
1969 ID.Kind = ValID::t_LocalName;
1970 break;
Dan Gohman83448032010-07-14 18:26:50 +00001971 case lltok::exclaim: // !42, !{...}, or !"foo"
1972 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 ID.Kind = ValID::t_APSInt;
1976 break;
1977 case lltok::APFloat:
1978 ID.APFloatVal = Lex.getAPFloatVal();
1979 ID.Kind = ValID::t_APFloat;
1980 break;
1981 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001982 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 ID.Kind = ValID::t_Constant;
1984 break;
1985 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001986 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001987 ID.Kind = ValID::t_Constant;
1988 break;
1989 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1990 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1991 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001992
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 case lltok::lbrace: {
1994 // ValID ::= '{' ConstVector '}'
1995 Lex.Lex();
1996 SmallVector<Constant*, 16> Elts;
1997 if (ParseGlobalValueVector(Elts) ||
1998 ParseToken(lltok::rbrace, "expected end of struct constant"))
1999 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002000
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002001 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2002 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002003 ID.Kind = ValID::t_Constant;
2004 return false;
2005 }
2006 case lltok::less: {
2007 // ValID ::= '<' ConstVector '>' --> Vector.
2008 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2009 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002010 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002011
Chris Lattnerdf986172009-01-02 07:01:27 +00002012 SmallVector<Constant*, 16> Elts;
2013 LocTy FirstEltLoc = Lex.getLoc();
2014 if (ParseGlobalValueVector(Elts) ||
2015 (isPackedStruct &&
2016 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2017 ParseToken(lltok::greater, "expected end of constant"))
2018 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002019
Chris Lattnerdf986172009-01-02 07:01:27 +00002020 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002021 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002022 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 ID.Kind = ValID::t_Constant;
2024 return false;
2025 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002026
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 if (Elts.empty())
2028 return Error(ID.Loc, "constant vector must not be empty");
2029
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002030 if (!Elts[0]->getType()->isIntegerTy() &&
2031 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 return Error(FirstEltLoc,
2033 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002034
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 // Verify that all the vector elements have the same type.
2036 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2037 if (Elts[i]->getType() != Elts[0]->getType())
2038 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002039 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002041
Chris Lattner2ca5c862011-02-15 00:14:00 +00002042 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002043 ID.Kind = ValID::t_Constant;
2044 return false;
2045 }
2046 case lltok::lsquare: { // Array Constant
2047 Lex.Lex();
2048 SmallVector<Constant*, 16> Elts;
2049 LocTy FirstEltLoc = Lex.getLoc();
2050 if (ParseGlobalValueVector(Elts) ||
2051 ParseToken(lltok::rsquare, "expected end of array constant"))
2052 return true;
2053
2054 // Handle empty element.
2055 if (Elts.empty()) {
2056 // Use undef instead of an array because it's inconvenient to determine
2057 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002058 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002059 return false;
2060 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Chris Lattnerdf986172009-01-02 07:01:27 +00002062 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002063 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Owen Andersondebcb012009-07-29 22:17:13 +00002066 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002067
Chris Lattnerdf986172009-01-02 07:01:27 +00002068 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002069 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002070 if (Elts[i]->getType() != Elts[0]->getType())
2071 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002072 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 " is not of type '" +Elts[0]->getType()->getDescription());
2074 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002075
Owen Anderson1fd70962009-07-28 18:32:17 +00002076 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002077 ID.Kind = ValID::t_Constant;
2078 return false;
2079 }
2080 case lltok::kw_c: // c "foo"
2081 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002082 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002083 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2084 ID.Kind = ValID::t_Constant;
2085 return false;
2086
2087 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002088 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2089 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 Lex.Lex();
2091 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002092 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002093 ParseStringConstant(ID.StrVal) ||
2094 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 ParseToken(lltok::StringConstant, "expected constraint string"))
2096 return true;
2097 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002098 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 ID.Kind = ValID::t_InlineAsm;
2100 return false;
2101 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002102
Chris Lattner09d9ef42009-10-28 03:39:23 +00002103 case lltok::kw_blockaddress: {
2104 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2105 Lex.Lex();
2106
2107 ValID Fn, Label;
2108 LocTy FnLoc, LabelLoc;
2109
2110 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2111 ParseValID(Fn) ||
2112 ParseToken(lltok::comma, "expected comma in block address expression")||
2113 ParseValID(Label) ||
2114 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2115 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002116
Chris Lattner09d9ef42009-10-28 03:39:23 +00002117 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2118 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002119 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002120 return Error(Label.Loc, "expected basic block name in blockaddress");
2121
2122 // Make a global variable as a placeholder for this reference.
2123 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2124 false, GlobalValue::InternalLinkage,
2125 0, "");
2126 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2127 ID.ConstantVal = FwdRef;
2128 ID.Kind = ValID::t_Constant;
2129 return false;
2130 }
2131
Chris Lattnerdf986172009-01-02 07:01:27 +00002132 case lltok::kw_trunc:
2133 case lltok::kw_zext:
2134 case lltok::kw_sext:
2135 case lltok::kw_fptrunc:
2136 case lltok::kw_fpext:
2137 case lltok::kw_bitcast:
2138 case lltok::kw_uitofp:
2139 case lltok::kw_sitofp:
2140 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002141 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002145 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 Constant *SrcVal;
2147 Lex.Lex();
2148 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2149 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002150 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 ParseType(DestTy) ||
2152 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2153 return true;
2154 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2155 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2156 SrcVal->getType()->getDescription() + "' to '" +
2157 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002158 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002159 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 ID.Kind = ValID::t_Constant;
2161 return false;
2162 }
2163 case lltok::kw_extractvalue: {
2164 Lex.Lex();
2165 Constant *Val;
2166 SmallVector<unsigned, 4> Indices;
2167 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2168 ParseGlobalTypeAndValue(Val) ||
2169 ParseIndexList(Indices) ||
2170 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2171 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002172
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002173 if (!Val->getType()->isAggregateType())
2174 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2176 Indices.end()))
2177 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002178 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002179 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 ID.Kind = ValID::t_Constant;
2181 return false;
2182 }
2183 case lltok::kw_insertvalue: {
2184 Lex.Lex();
2185 Constant *Val0, *Val1;
2186 SmallVector<unsigned, 4> Indices;
2187 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2188 ParseGlobalTypeAndValue(Val0) ||
2189 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2190 ParseGlobalTypeAndValue(Val1) ||
2191 ParseIndexList(Indices) ||
2192 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2193 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002194 if (!Val0->getType()->isAggregateType())
2195 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002196 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2197 Indices.end()))
2198 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002199 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002200 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 ID.Kind = ValID::t_Constant;
2202 return false;
2203 }
2204 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002205 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 unsigned PredVal, Opc = Lex.getUIntVal();
2207 Constant *Val0, *Val1;
2208 Lex.Lex();
2209 if (ParseCmpPredicate(PredVal, Opc) ||
2210 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2211 ParseGlobalTypeAndValue(Val0) ||
2212 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2213 ParseGlobalTypeAndValue(Val1) ||
2214 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2215 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002216
Chris Lattnerdf986172009-01-02 07:01:27 +00002217 if (Val0->getType() != Val1->getType())
2218 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002219
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002221
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002223 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002225 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002226 } else {
2227 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002228 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002229 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002231 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002232 }
2233 ID.Kind = ValID::t_Constant;
2234 return false;
2235 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236
Chris Lattnerdf986172009-01-02 07:01:27 +00002237 // Binary Operators.
2238 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002239 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002241 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002242 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002243 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 case lltok::kw_udiv:
2245 case lltok::kw_sdiv:
2246 case lltok::kw_fdiv:
2247 case lltok::kw_urem:
2248 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002249 case lltok::kw_frem:
2250 case lltok::kw_shl:
2251 case lltok::kw_lshr:
2252 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002253 bool NUW = false;
2254 bool NSW = false;
2255 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 unsigned Opc = Lex.getUIntVal();
2257 Constant *Val0, *Val1;
2258 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002259 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002260 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2261 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002262 if (EatIfPresent(lltok::kw_nuw))
2263 NUW = true;
2264 if (EatIfPresent(lltok::kw_nsw)) {
2265 NSW = true;
2266 if (EatIfPresent(lltok::kw_nuw))
2267 NUW = true;
2268 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002269 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2270 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002271 if (EatIfPresent(lltok::kw_exact))
2272 Exact = true;
2273 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2275 ParseGlobalTypeAndValue(Val0) ||
2276 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2277 ParseGlobalTypeAndValue(Val1) ||
2278 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2279 return true;
2280 if (Val0->getType() != Val1->getType())
2281 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002282 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002283 if (NUW)
2284 return Error(ModifierLoc, "nuw only applies to integer operations");
2285 if (NSW)
2286 return Error(ModifierLoc, "nsw only applies to integer operations");
2287 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002288 // Check that the type is valid for the operator.
2289 switch (Opc) {
2290 case Instruction::Add:
2291 case Instruction::Sub:
2292 case Instruction::Mul:
2293 case Instruction::UDiv:
2294 case Instruction::SDiv:
2295 case Instruction::URem:
2296 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002297 case Instruction::Shl:
2298 case Instruction::AShr:
2299 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002300 if (!Val0->getType()->isIntOrIntVectorTy())
2301 return Error(ID.Loc, "constexpr requires integer operands");
2302 break;
2303 case Instruction::FAdd:
2304 case Instruction::FSub:
2305 case Instruction::FMul:
2306 case Instruction::FDiv:
2307 case Instruction::FRem:
2308 if (!Val0->getType()->isFPOrFPVectorTy())
2309 return Error(ID.Loc, "constexpr requires fp operands");
2310 break;
2311 default: llvm_unreachable("Unknown binary operator!");
2312 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002313 unsigned Flags = 0;
2314 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2315 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002316 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002317 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002318 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 ID.Kind = ValID::t_Constant;
2320 return false;
2321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002322
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002324 case lltok::kw_and:
2325 case lltok::kw_or:
2326 case lltok::kw_xor: {
2327 unsigned Opc = Lex.getUIntVal();
2328 Constant *Val0, *Val1;
2329 Lex.Lex();
2330 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2331 ParseGlobalTypeAndValue(Val0) ||
2332 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2333 ParseGlobalTypeAndValue(Val1) ||
2334 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2335 return true;
2336 if (Val0->getType() != Val1->getType())
2337 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002338 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 return Error(ID.Loc,
2340 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002341 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 ID.Kind = ValID::t_Constant;
2343 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002344 }
2345
Chris Lattnerdf986172009-01-02 07:01:27 +00002346 case lltok::kw_getelementptr:
2347 case lltok::kw_shufflevector:
2348 case lltok::kw_insertelement:
2349 case lltok::kw_extractelement:
2350 case lltok::kw_select: {
2351 unsigned Opc = Lex.getUIntVal();
2352 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002353 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002354 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002355 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002356 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002357 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2358 ParseGlobalValueVector(Elts) ||
2359 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2360 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361
Chris Lattnerdf986172009-01-02 07:01:27 +00002362 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002363 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002364 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002365
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002367 (Value**)(Elts.data() + 1),
2368 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002369 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002370 ID.ConstantVal = InBounds ?
2371 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2372 Elts.data() + 1,
2373 Elts.size() - 1) :
2374 ConstantExpr::getGetElementPtr(Elts[0],
2375 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002376 } else if (Opc == Instruction::Select) {
2377 if (Elts.size() != 3)
2378 return Error(ID.Loc, "expected three operands to select");
2379 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2380 Elts[2]))
2381 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002382 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002383 } else if (Opc == Instruction::ShuffleVector) {
2384 if (Elts.size() != 3)
2385 return Error(ID.Loc, "expected three operands to shufflevector");
2386 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2387 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002388 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002389 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 } else if (Opc == Instruction::ExtractElement) {
2391 if (Elts.size() != 2)
2392 return Error(ID.Loc, "expected two operands to extractelement");
2393 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2394 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002395 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 } else {
2397 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2398 if (Elts.size() != 3)
2399 return Error(ID.Loc, "expected three operands to insertelement");
2400 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2401 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002402 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002403 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Chris Lattnerdf986172009-01-02 07:01:27 +00002406 ID.Kind = ValID::t_Constant;
2407 return false;
2408 }
2409 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002410
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 Lex.Lex();
2412 return false;
2413}
2414
2415/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002416bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2417 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002419 Value *V = NULL;
2420 bool Parsed = ParseValID(ID) ||
2421 ConvertValIDToValue(Ty, ID, V, NULL);
2422 if (V && !(C = dyn_cast<Constant>(V)))
2423 return Error(ID.Loc, "global values must be constants");
2424 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002425}
2426
Victor Hernandez92f238d2010-01-11 22:31:58 +00002427bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2428 PATypeHolder Type(Type::getVoidTy(Context));
2429 return ParseType(Type) ||
2430 ParseGlobalValue(Type, V);
2431}
2432
2433/// ParseGlobalValueVector
2434/// ::= /*empty*/
2435/// ::= TypeAndValue (',' TypeAndValue)*
2436bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2437 // Empty list.
2438 if (Lex.getKind() == lltok::rbrace ||
2439 Lex.getKind() == lltok::rsquare ||
2440 Lex.getKind() == lltok::greater ||
2441 Lex.getKind() == lltok::rparen)
2442 return false;
2443
2444 Constant *C;
2445 if (ParseGlobalTypeAndValue(C)) return true;
2446 Elts.push_back(C);
2447
2448 while (EatIfPresent(lltok::comma)) {
2449 if (ParseGlobalTypeAndValue(C)) return true;
2450 Elts.push_back(C);
2451 }
2452
2453 return false;
2454}
2455
Dan Gohman309b3af2010-08-24 02:24:03 +00002456bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2457 assert(Lex.getKind() == lltok::lbrace);
2458 Lex.Lex();
2459
2460 SmallVector<Value*, 16> Elts;
2461 if (ParseMDNodeVector(Elts, PFS) ||
2462 ParseToken(lltok::rbrace, "expected end of metadata node"))
2463 return true;
2464
Jay Foadec9186b2011-04-21 19:59:31 +00002465 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002466 ID.Kind = ValID::t_MDNode;
2467 return false;
2468}
2469
Dan Gohman83448032010-07-14 18:26:50 +00002470/// ParseMetadataValue
2471/// ::= !42
2472/// ::= !{...}
2473/// ::= !"string"
2474bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2475 assert(Lex.getKind() == lltok::exclaim);
2476 Lex.Lex();
2477
2478 // MDNode:
2479 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002480 if (Lex.getKind() == lltok::lbrace)
2481 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002482
2483 // Standalone metadata reference
2484 // !42
2485 if (Lex.getKind() == lltok::APSInt) {
2486 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2487 ID.Kind = ValID::t_MDNode;
2488 return false;
2489 }
2490
2491 // MDString:
2492 // ::= '!' STRINGCONSTANT
2493 if (ParseMDString(ID.MDStringVal)) return true;
2494 ID.Kind = ValID::t_MDString;
2495 return false;
2496}
2497
Victor Hernandez92f238d2010-01-11 22:31:58 +00002498
2499//===----------------------------------------------------------------------===//
2500// Function Parsing.
2501//===----------------------------------------------------------------------===//
2502
2503bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2504 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002505 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002506 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002507
Chris Lattnerdf986172009-01-02 07:01:27 +00002508 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002509 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002511 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2512 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2513 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002514 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002515 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2516 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2517 return (V == 0);
2518 case ValID::t_InlineAsm: {
2519 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2520 const FunctionType *FTy =
2521 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2522 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2523 return Error(ID.Loc, "invalid type for inline asm constraint string");
2524 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2525 return false;
2526 }
2527 case ValID::t_MDNode:
2528 if (!Ty->isMetadataTy())
2529 return Error(ID.Loc, "metadata value must have metadata type");
2530 V = ID.MDNodeVal;
2531 return false;
2532 case ValID::t_MDString:
2533 if (!Ty->isMetadataTy())
2534 return Error(ID.Loc, "metadata value must have metadata type");
2535 V = ID.MDStringVal;
2536 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 case ValID::t_GlobalName:
2538 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2539 return V == 0;
2540 case ValID::t_GlobalID:
2541 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2542 return V == 0;
2543 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002544 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002546 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002547 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 return false;
2549 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002550 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002551 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2552 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002553
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 // The lexer has no type info, so builds all float and double FP constants
2555 // as double. Fix this here. Long double does not need this.
2556 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002557 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002558 bool Ignored;
2559 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2560 &Ignored);
2561 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002562 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002563
Chris Lattner959873d2009-01-05 18:24:23 +00002564 if (V->getType() != Ty)
2565 return Error(ID.Loc, "floating point constant does not have type '" +
2566 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002567
Chris Lattnerdf986172009-01-02 07:01:27 +00002568 return false;
2569 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002570 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002572 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002573 return false;
2574 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002575 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002576 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002577 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002578 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002579 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002580 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002581 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002582 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002583 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002584 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002585 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002587 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002588 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002589 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002590 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 return false;
2592 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002593 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002595
Chris Lattnerdf986172009-01-02 07:01:27 +00002596 V = ID.ConstantVal;
2597 return false;
2598 }
2599}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002600
Chris Lattnerdf986172009-01-02 07:01:27 +00002601bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2602 V = 0;
2603 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002604 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002605 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002606}
2607
2608bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002609 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002610 return ParseType(T) ||
2611 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002612}
2613
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002614bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2615 PerFunctionState &PFS) {
2616 Value *V;
2617 Loc = Lex.getLoc();
2618 if (ParseTypeAndValue(V, PFS)) return true;
2619 if (!isa<BasicBlock>(V))
2620 return Error(Loc, "expected a basic block");
2621 BB = cast<BasicBlock>(V);
2622 return false;
2623}
2624
2625
Chris Lattnerdf986172009-01-02 07:01:27 +00002626/// FunctionHeader
2627/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002628/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002629/// OptionalAlign OptGC
2630bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2631 // Parse the linkage.
2632 LocTy LinkageLoc = Lex.getLoc();
2633 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002634
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002635 unsigned Visibility, RetAttrs;
2636 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002637 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002638 LocTy RetTypeLoc = Lex.getLoc();
2639 if (ParseOptionalLinkage(Linkage) ||
2640 ParseOptionalVisibility(Visibility) ||
2641 ParseOptionalCallingConv(CC) ||
2642 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002643 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002644 return true;
2645
2646 // Verify that the linkage is ok.
2647 switch ((GlobalValue::LinkageTypes)Linkage) {
2648 case GlobalValue::ExternalLinkage:
2649 break; // always ok.
2650 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002651 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002652 if (isDefine)
2653 return Error(LinkageLoc, "invalid linkage for function definition");
2654 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002655 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002656 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002657 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002658 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002659 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002660 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002661 case GlobalValue::LinkOnceAnyLinkage:
2662 case GlobalValue::LinkOnceODRLinkage:
2663 case GlobalValue::WeakAnyLinkage:
2664 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002665 case GlobalValue::DLLExportLinkage:
2666 if (!isDefine)
2667 return Error(LinkageLoc, "invalid linkage for function declaration");
2668 break;
2669 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002670 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002671 return Error(LinkageLoc, "invalid function linkage type");
2672 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Chris Lattner99bb3152009-01-05 08:00:30 +00002674 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002675 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002677
Chris Lattnerdf986172009-01-02 07:01:27 +00002678 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002679
2680 std::string FunctionName;
2681 if (Lex.getKind() == lltok::GlobalVar) {
2682 FunctionName = Lex.getStrVal();
2683 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2684 unsigned NameID = Lex.getUIntVal();
2685
2686 if (NameID != NumberedVals.size())
2687 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002688 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002689 } else {
2690 return TokError("expected function name");
2691 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002692
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002693 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002694
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002695 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 std::vector<ArgInfo> ArgList;
2699 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002703 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002704 bool UnnamedAddr;
2705 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002706
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002707 if (ParseArgumentList(ArgList, isVarArg, false) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002708 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2709 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002710 ParseOptionalAttrs(FuncAttrs, 2) ||
2711 (EatIfPresent(lltok::kw_section) &&
2712 ParseStringConstant(Section)) ||
2713 ParseOptionalAlignment(Alignment) ||
2714 (EatIfPresent(lltok::kw_gc) &&
2715 ParseStringConstant(GC)))
2716 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002717
2718 // If the alignment was parsed as an attribute, move to the alignment field.
2719 if (FuncAttrs & Attribute::Alignment) {
2720 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2721 FuncAttrs &= ~Attribute::Alignment;
2722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 // Okay, if we got here, the function is syntactically valid. Convert types
2725 // and do semantic checks.
2726 std::vector<const Type*> ParamTypeList;
2727 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002728
Chris Lattnerdf986172009-01-02 07:01:27 +00002729 if (RetAttrs != Attribute::None)
2730 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002731
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2733 ParamTypeList.push_back(ArgList[i].Type);
2734 if (ArgList[i].Attrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2736 }
2737
2738 if (FuncAttrs != Attribute::None)
2739 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2740
2741 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002742
Benjamin Kramerf0127052010-01-05 13:12:22 +00002743 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002744 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2745
Owen Andersonfba933c2009-07-01 23:57:11 +00002746 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002747 FunctionType::get(RetType, ParamTypeList, isVarArg);
2748 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002749
2750 Fn = 0;
2751 if (!FunctionName.empty()) {
2752 // If this was a definition of a forward reference, remove the definition
2753 // from the forward reference table and fill in the forward ref.
2754 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2755 ForwardRefVals.find(FunctionName);
2756 if (FRVI != ForwardRefVals.end()) {
2757 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002758 if (Fn->getType() != PFT)
2759 return Error(FRVI->second.second, "invalid forward reference to "
2760 "function '" + FunctionName + "' with wrong type!");
2761
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 ForwardRefVals.erase(FRVI);
2763 } else if ((Fn = M->getFunction(FunctionName))) {
2764 // If this function already exists in the symbol table, then it is
2765 // multiply defined. We accept a few cases for old backwards compat.
2766 // FIXME: Remove this stuff for LLVM 3.0.
2767 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2768 (!Fn->isDeclaration() && isDefine)) {
2769 // If the redefinition has different type or different attributes,
2770 // reject it. If both have bodies, reject it.
2771 return Error(NameLoc, "invalid redefinition of function '" +
2772 FunctionName + "'");
2773 } else if (Fn->isDeclaration()) {
2774 // Make sure to strip off any argument names so we can't get conflicts.
2775 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2776 AI != AE; ++AI)
2777 AI->setName("");
2778 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002779 } else if (M->getNamedValue(FunctionName)) {
2780 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782
Dan Gohman41905542009-08-29 23:37:49 +00002783 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002784 // If this is a definition of a forward referenced function, make sure the
2785 // types agree.
2786 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2787 = ForwardRefValIDs.find(NumberedVals.size());
2788 if (I != ForwardRefValIDs.end()) {
2789 Fn = cast<Function>(I->second.first);
2790 if (Fn->getType() != PFT)
2791 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002792 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002793 ForwardRefValIDs.erase(I);
2794 }
2795 }
2796
2797 if (Fn == 0)
2798 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2799 else // Move the forward-reference to the correct spot in the module.
2800 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2801
2802 if (FunctionName.empty())
2803 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002804
Chris Lattnerdf986172009-01-02 07:01:27 +00002805 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2806 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2807 Fn->setCallingConv(CC);
2808 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002809 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 Fn->setAlignment(Alignment);
2811 Fn->setSection(Section);
2812 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002813
Chris Lattnerdf986172009-01-02 07:01:27 +00002814 // Add all of the arguments we parsed to the function.
2815 Function::arg_iterator ArgIt = Fn->arg_begin();
2816 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002817 // If we run out of arguments in the Function prototype, exit early.
2818 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2819 if (ArgIt == Fn->arg_end()) break;
2820
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 // If the argument has a name, insert it into the argument symbol table.
2822 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 // Set the name, if it conflicted, it will be auto-renamed.
2825 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002826
Benjamin Krameraf812352010-10-16 11:28:23 +00002827 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2829 ArgList[i].Name + "'");
2830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002831
Chris Lattnerdf986172009-01-02 07:01:27 +00002832 return false;
2833}
2834
2835
2836/// ParseFunctionBody
2837/// ::= '{' BasicBlock+ '}'
2838/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2839///
2840bool LLParser::ParseFunctionBody(Function &Fn) {
2841 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2842 return TokError("expected '{' in function body");
2843 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002844
Chris Lattner09d9ef42009-10-28 03:39:23 +00002845 int FunctionNumber = -1;
2846 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2847
2848 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002849
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002850 // We need at least one basic block.
2851 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2852 return TokError("function body requires at least one basic block");
2853
Chris Lattnerdf986172009-01-02 07:01:27 +00002854 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2855 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002856
Chris Lattnerdf986172009-01-02 07:01:27 +00002857 // Eat the }.
2858 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002861 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002862}
2863
2864/// ParseBasicBlock
2865/// ::= LabelStr? Instruction*
2866bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2867 // If this basic block starts out with a name, remember it.
2868 std::string Name;
2869 LocTy NameLoc = Lex.getLoc();
2870 if (Lex.getKind() == lltok::LabelStr) {
2871 Name = Lex.getStrVal();
2872 Lex.Lex();
2873 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002874
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2876 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002879
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 // Parse the instructions in this block until we get a terminator.
2881 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002882 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002883 do {
2884 // This instruction may have three possibilities for a name: a) none
2885 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2886 LocTy NameLoc = Lex.getLoc();
2887 int NameID = -1;
2888 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002889
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 if (Lex.getKind() == lltok::LocalVarID) {
2891 NameID = Lex.getUIntVal();
2892 Lex.Lex();
2893 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2894 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002895 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 NameStr = Lex.getStrVal();
2897 Lex.Lex();
2898 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2899 return true;
2900 }
Devang Patelf633a062009-09-17 23:04:48 +00002901
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002902 switch (ParseInstruction(Inst, BB, PFS)) {
2903 default: assert(0 && "Unknown ParseInstruction result!");
2904 case InstError: return true;
2905 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002906 BB->getInstList().push_back(Inst);
2907
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002908 // With a normal result, we check to see if the instruction is followed by
2909 // a comma and metadata.
2910 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002911 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002912 return true;
2913 break;
2914 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002915 BB->getInstList().push_back(Inst);
2916
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002917 // If the instruction parser ate an extra comma at the end of it, it
2918 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002919 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002920 return true;
2921 break;
2922 }
Devang Patelf633a062009-09-17 23:04:48 +00002923
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 // Set the name on the instruction.
2925 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2926 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002927
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 return false;
2929}
2930
2931//===----------------------------------------------------------------------===//
2932// Instruction Parsing.
2933//===----------------------------------------------------------------------===//
2934
2935/// ParseInstruction - Parse one of the many different instructions.
2936///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002937int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2938 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002939 lltok::Kind Token = Lex.getKind();
2940 if (Token == lltok::Eof)
2941 return TokError("found end of file when expecting more instructions");
2942 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002943 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002945
Chris Lattnerdf986172009-01-02 07:01:27 +00002946 switch (Token) {
2947 default: return Error(Loc, "expected instruction opcode");
2948 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002949 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2950 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002951 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2952 case lltok::kw_br: return ParseBr(Inst, PFS);
2953 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002954 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002955 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2956 // Binary Operators.
2957 case lltok::kw_add:
2958 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002959 case lltok::kw_mul:
2960 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002961 bool NUW = EatIfPresent(lltok::kw_nuw);
2962 bool NSW = EatIfPresent(lltok::kw_nsw);
2963 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2964
2965 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2966
2967 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2968 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2969 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002970 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002971 case lltok::kw_fadd:
2972 case lltok::kw_fsub:
2973 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2974
Chris Lattner35bda892011-02-06 21:44:57 +00002975 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002976 case lltok::kw_udiv:
2977 case lltok::kw_lshr:
2978 case lltok::kw_ashr: {
2979 bool Exact = EatIfPresent(lltok::kw_exact);
2980
2981 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2982 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2983 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002984 }
2985
Chris Lattnerdf986172009-01-02 07:01:27 +00002986 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002987 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002988 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002989 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 case lltok::kw_and:
2991 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002992 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002993 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002994 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002995 // Casts.
2996 case lltok::kw_trunc:
2997 case lltok::kw_zext:
2998 case lltok::kw_sext:
2999 case lltok::kw_fptrunc:
3000 case lltok::kw_fpext:
3001 case lltok::kw_bitcast:
3002 case lltok::kw_uitofp:
3003 case lltok::kw_sitofp:
3004 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003005 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003006 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003007 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003008 // Other.
3009 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003010 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003011 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3012 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3013 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3014 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3015 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3016 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3017 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003018 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003019 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3020 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3021 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003022 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003023 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003024 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003025 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003026 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003027 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003028 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3029 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3030 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3031 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3032 }
3033}
3034
3035/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3036bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003037 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 switch (Lex.getKind()) {
3039 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3040 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3041 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3042 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3043 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3044 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3045 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3046 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3047 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3048 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3049 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3050 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3051 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3052 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3053 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3054 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3055 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3056 }
3057 } else {
3058 switch (Lex.getKind()) {
3059 default: TokError("expected icmp predicate (e.g. 'eq')");
3060 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3061 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3062 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3063 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3064 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3065 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3066 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3067 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3068 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3069 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3070 }
3071 }
3072 Lex.Lex();
3073 return false;
3074}
3075
3076//===----------------------------------------------------------------------===//
3077// Terminator Instructions.
3078//===----------------------------------------------------------------------===//
3079
3080/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003081/// ::= 'ret' void (',' !dbg, !1)*
3082/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3083/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003084/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003085int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3086 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003087 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003088 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003089
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003090 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003091 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 return false;
3093 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003094
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 Value *RV;
3096 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003097
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003098 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003099 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003100 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003101 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003102 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003103 } else {
3104 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003105 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3106 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003107 SmallVector<Value*, 8> RVs;
3108 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003109
Devang Patelf633a062009-09-17 23:04:48 +00003110 do {
Devang Patel0475c912009-09-29 00:01:14 +00003111 // If optional custom metadata, e.g. !dbg is seen then this is the
3112 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003113 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003114 break;
3115 if (ParseTypeAndValue(RV, PFS)) return true;
3116 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003117 } while (EatIfPresent(lltok::comma));
3118
3119 RV = UndefValue::get(PFS.getFunction().getReturnType());
3120 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003121 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3122 BB->getInstList().push_back(I);
3123 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003124 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003125 }
3126 }
Devang Patelf633a062009-09-17 23:04:48 +00003127
Owen Anderson1d0be152009-08-13 21:58:54 +00003128 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003129 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003130}
3131
3132
3133/// ParseBr
3134/// ::= 'br' TypeAndValue
3135/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3136bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3137 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003138 Value *Op0;
3139 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003140 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003141
Chris Lattnerdf986172009-01-02 07:01:27 +00003142 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3143 Inst = BranchInst::Create(BB);
3144 return false;
3145 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003146
Owen Anderson1d0be152009-08-13 21:58:54 +00003147 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003148 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003149
Chris Lattnerdf986172009-01-02 07:01:27 +00003150 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003151 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003152 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003153 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003154 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003155
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003156 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 return false;
3158}
3159
3160/// ParseSwitch
3161/// Instruction
3162/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3163/// JumpTable
3164/// ::= (TypeAndValue ',' TypeAndValue)*
3165bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3166 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003167 Value *Cond;
3168 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003169 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3170 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003171 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003172 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3173 return true;
3174
Duncan Sands1df98592010-02-16 11:11:14 +00003175 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003176 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003177
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 // Parse the jump table pairs.
3179 SmallPtrSet<Value*, 32> SeenCases;
3180 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3181 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003182 Value *Constant;
3183 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003184
Chris Lattnerdf986172009-01-02 07:01:27 +00003185 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3186 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003187 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003188 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003189
Chris Lattnerdf986172009-01-02 07:01:27 +00003190 if (!SeenCases.insert(Constant))
3191 return Error(CondLoc, "duplicate case value in switch");
3192 if (!isa<ConstantInt>(Constant))
3193 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003194
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003195 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003197
Chris Lattnerdf986172009-01-02 07:01:27 +00003198 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003199
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003200 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3202 SI->addCase(Table[i].first, Table[i].second);
3203 Inst = SI;
3204 return false;
3205}
3206
Chris Lattnerab21db72009-10-28 00:19:10 +00003207/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003208/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003209/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3210bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003211 LocTy AddrLoc;
3212 Value *Address;
3213 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003214 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3215 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003216 return true;
3217
Duncan Sands1df98592010-02-16 11:11:14 +00003218 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003219 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003220
3221 // Parse the destination list.
3222 SmallVector<BasicBlock*, 16> DestList;
3223
3224 if (Lex.getKind() != lltok::rsquare) {
3225 BasicBlock *DestBB;
3226 if (ParseTypeAndBasicBlock(DestBB, PFS))
3227 return true;
3228 DestList.push_back(DestBB);
3229
3230 while (EatIfPresent(lltok::comma)) {
3231 if (ParseTypeAndBasicBlock(DestBB, PFS))
3232 return true;
3233 DestList.push_back(DestBB);
3234 }
3235 }
3236
3237 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3238 return true;
3239
Chris Lattnerab21db72009-10-28 00:19:10 +00003240 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003241 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3242 IBI->addDestination(DestList[i]);
3243 Inst = IBI;
3244 return false;
3245}
3246
3247
Chris Lattnerdf986172009-01-02 07:01:27 +00003248/// ParseInvoke
3249/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3250/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3251bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3252 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003253 unsigned RetAttrs, FnAttrs;
3254 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003255 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003256 LocTy RetTypeLoc;
3257 ValID CalleeID;
3258 SmallVector<ParamInfo, 16> ArgList;
3259
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003260 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003261 if (ParseOptionalCallingConv(CC) ||
3262 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003263 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003264 ParseValID(CalleeID) ||
3265 ParseParameterList(ArgList, PFS) ||
3266 ParseOptionalAttrs(FnAttrs, 2) ||
3267 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003268 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003270 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003272
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 // If RetType is a non-function pointer type, then this is the short syntax
3274 // for the call, which means that RetType is just the return type. Infer the
3275 // rest of the function argument types from the arguments that are present.
3276 const PointerType *PFTy = 0;
3277 const FunctionType *Ty = 0;
3278 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3279 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3280 // Pull out the types of all of the arguments...
3281 std::vector<const Type*> ParamTypes;
3282 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3283 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003284
Chris Lattnerdf986172009-01-02 07:01:27 +00003285 if (!FunctionType::isValidReturnType(RetType))
3286 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003287
Owen Andersondebcb012009-07-29 22:17:13 +00003288 Ty = FunctionType::get(RetType, ParamTypes, false);
3289 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003290 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003291
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 // Look up the callee.
3293 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003294 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003295
Chris Lattnerdf986172009-01-02 07:01:27 +00003296 // Set up the Attributes for the function.
3297 SmallVector<AttributeWithIndex, 8> Attrs;
3298 if (RetAttrs != Attribute::None)
3299 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003300
Chris Lattnerdf986172009-01-02 07:01:27 +00003301 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003302
Chris Lattnerdf986172009-01-02 07:01:27 +00003303 // Loop through FunctionType's arguments and ensure they are specified
3304 // correctly. Also, gather any parameter attributes.
3305 FunctionType::param_iterator I = Ty->param_begin();
3306 FunctionType::param_iterator E = Ty->param_end();
3307 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3308 const Type *ExpectedTy = 0;
3309 if (I != E) {
3310 ExpectedTy = *I++;
3311 } else if (!Ty->isVarArg()) {
3312 return Error(ArgList[i].Loc, "too many arguments specified");
3313 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003314
Chris Lattnerdf986172009-01-02 07:01:27 +00003315 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3316 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3317 ExpectedTy->getDescription() + "'");
3318 Args.push_back(ArgList[i].V);
3319 if (ArgList[i].Attrs != Attribute::None)
3320 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003322
Chris Lattnerdf986172009-01-02 07:01:27 +00003323 if (I != E)
3324 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003325
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 if (FnAttrs != Attribute::None)
3327 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003328
Chris Lattnerdf986172009-01-02 07:01:27 +00003329 // Finish off the Attributes and check them
3330 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003331
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003332 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 Args.begin(), Args.end());
3334 II->setCallingConv(CC);
3335 II->setAttributes(PAL);
3336 Inst = II;
3337 return false;
3338}
3339
3340
3341
3342//===----------------------------------------------------------------------===//
3343// Binary Operators.
3344//===----------------------------------------------------------------------===//
3345
3346/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003347/// ::= ArithmeticOps TypeAndValue ',' Value
3348///
3349/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3350/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003351bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003352 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003353 LocTy Loc; Value *LHS, *RHS;
3354 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3355 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3356 ParseValue(LHS->getType(), RHS, PFS))
3357 return true;
3358
Chris Lattnere914b592009-01-05 08:24:46 +00003359 bool Valid;
3360 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003361 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003362 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003363 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3364 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003365 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003366 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3367 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003368 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003369
Chris Lattnere914b592009-01-05 08:24:46 +00003370 if (!Valid)
3371 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003372
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3374 return false;
3375}
3376
3377/// ParseLogical
3378/// ::= ArithmeticOps TypeAndValue ',' Value {
3379bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3380 unsigned Opc) {
3381 LocTy Loc; Value *LHS, *RHS;
3382 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3383 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3384 ParseValue(LHS->getType(), RHS, PFS))
3385 return true;
3386
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003387 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 return Error(Loc,"instruction requires integer or integer vector operands");
3389
3390 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3391 return false;
3392}
3393
3394
3395/// ParseCompare
3396/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3397/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003398bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3399 unsigned Opc) {
3400 // Parse the integer/fp comparison predicate.
3401 LocTy Loc;
3402 unsigned Pred;
3403 Value *LHS, *RHS;
3404 if (ParseCmpPredicate(Pred, Opc) ||
3405 ParseTypeAndValue(LHS, Loc, PFS) ||
3406 ParseToken(lltok::comma, "expected ',' after compare value") ||
3407 ParseValue(LHS->getType(), RHS, PFS))
3408 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003409
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003411 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003413 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003414 } else {
3415 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003416 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003417 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003418 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003419 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003420 }
3421 return false;
3422}
3423
3424//===----------------------------------------------------------------------===//
3425// Other Instructions.
3426//===----------------------------------------------------------------------===//
3427
3428
3429/// ParseCast
3430/// ::= CastOpc TypeAndValue 'to' Type
3431bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3432 unsigned Opc) {
3433 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003434 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003435 if (ParseTypeAndValue(Op, Loc, PFS) ||
3436 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3437 ParseType(DestTy))
3438 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003439
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003440 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3441 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 return Error(Loc, "invalid cast opcode for cast from '" +
3443 Op->getType()->getDescription() + "' to '" +
3444 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003445 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003446 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3447 return false;
3448}
3449
3450/// ParseSelect
3451/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3452bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3453 LocTy Loc;
3454 Value *Op0, *Op1, *Op2;
3455 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3456 ParseToken(lltok::comma, "expected ',' after select condition") ||
3457 ParseTypeAndValue(Op1, PFS) ||
3458 ParseToken(lltok::comma, "expected ',' after select value") ||
3459 ParseTypeAndValue(Op2, PFS))
3460 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003461
Chris Lattnerdf986172009-01-02 07:01:27 +00003462 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3463 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003464
Chris Lattnerdf986172009-01-02 07:01:27 +00003465 Inst = SelectInst::Create(Op0, Op1, Op2);
3466 return false;
3467}
3468
Chris Lattner0088a5c2009-01-05 08:18:44 +00003469/// ParseVA_Arg
3470/// ::= 'va_arg' TypeAndValue ',' Type
3471bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003472 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003473 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003474 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 if (ParseTypeAndValue(Op, PFS) ||
3476 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003477 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003479
Chris Lattner0088a5c2009-01-05 08:18:44 +00003480 if (!EltTy->isFirstClassType())
3481 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003482
3483 Inst = new VAArgInst(Op, EltTy);
3484 return false;
3485}
3486
3487/// ParseExtractElement
3488/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3489bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3490 LocTy Loc;
3491 Value *Op0, *Op1;
3492 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3493 ParseToken(lltok::comma, "expected ',' after extract value") ||
3494 ParseTypeAndValue(Op1, PFS))
3495 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003496
Chris Lattnerdf986172009-01-02 07:01:27 +00003497 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3498 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003499
Eric Christophera3500da2009-07-25 02:28:41 +00003500 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003501 return false;
3502}
3503
3504/// ParseInsertElement
3505/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3506bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3507 LocTy Loc;
3508 Value *Op0, *Op1, *Op2;
3509 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3510 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3511 ParseTypeAndValue(Op1, PFS) ||
3512 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3513 ParseTypeAndValue(Op2, PFS))
3514 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003515
Chris Lattnerdf986172009-01-02 07:01:27 +00003516 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003517 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003518
Chris Lattnerdf986172009-01-02 07:01:27 +00003519 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3520 return false;
3521}
3522
3523/// ParseShuffleVector
3524/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3525bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3526 LocTy Loc;
3527 Value *Op0, *Op1, *Op2;
3528 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3529 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3530 ParseTypeAndValue(Op1, PFS) ||
3531 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3532 ParseTypeAndValue(Op2, PFS))
3533 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003534
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3536 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003537
Chris Lattnerdf986172009-01-02 07:01:27 +00003538 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3539 return false;
3540}
3541
3542/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003543/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003544int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003545 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003546 Value *Op0, *Op1;
3547 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003548
Chris Lattnerdf986172009-01-02 07:01:27 +00003549 if (ParseType(Ty) ||
3550 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3551 ParseValue(Ty, Op0, PFS) ||
3552 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003553 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003554 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3555 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003556
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003557 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3559 while (1) {
3560 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003561
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003562 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003563 break;
3564
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003565 if (Lex.getKind() == lltok::MetadataVar) {
3566 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003567 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003568 }
Devang Patela43d46f2009-10-16 18:45:49 +00003569
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003570 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003571 ParseValue(Ty, Op0, PFS) ||
3572 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003573 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003574 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3575 return true;
3576 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003577
Chris Lattnerdf986172009-01-02 07:01:27 +00003578 if (!Ty->isFirstClassType())
3579 return Error(TypeLoc, "phi node must have first class type");
3580
Jay Foad3ecfc862011-03-30 11:28:46 +00003581 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003582 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3583 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3584 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003585 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003586}
3587
3588/// ParseCall
3589/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3590/// ParameterList OptionalAttrs
3591bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3592 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003593 unsigned RetAttrs, FnAttrs;
3594 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003595 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 LocTy RetTypeLoc;
3597 ValID CalleeID;
3598 SmallVector<ParamInfo, 16> ArgList;
3599 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003600
Chris Lattnerdf986172009-01-02 07:01:27 +00003601 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3602 ParseOptionalCallingConv(CC) ||
3603 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003604 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003605 ParseValID(CalleeID) ||
3606 ParseParameterList(ArgList, PFS) ||
3607 ParseOptionalAttrs(FnAttrs, 2))
3608 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 // If RetType is a non-function pointer type, then this is the short syntax
3611 // for the call, which means that RetType is just the return type. Infer the
3612 // rest of the function argument types from the arguments that are present.
3613 const PointerType *PFTy = 0;
3614 const FunctionType *Ty = 0;
3615 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3616 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3617 // Pull out the types of all of the arguments...
3618 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003619 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3620 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003621
Chris Lattnerdf986172009-01-02 07:01:27 +00003622 if (!FunctionType::isValidReturnType(RetType))
3623 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003624
Owen Andersondebcb012009-07-29 22:17:13 +00003625 Ty = FunctionType::get(RetType, ParamTypes, false);
3626 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003628
Chris Lattnerdf986172009-01-02 07:01:27 +00003629 // Look up the callee.
3630 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003631 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003632
Chris Lattnerdf986172009-01-02 07:01:27 +00003633 // Set up the Attributes for the function.
3634 SmallVector<AttributeWithIndex, 8> Attrs;
3635 if (RetAttrs != Attribute::None)
3636 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003637
Chris Lattnerdf986172009-01-02 07:01:27 +00003638 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003639
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 // Loop through FunctionType's arguments and ensure they are specified
3641 // correctly. Also, gather any parameter attributes.
3642 FunctionType::param_iterator I = Ty->param_begin();
3643 FunctionType::param_iterator E = Ty->param_end();
3644 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3645 const Type *ExpectedTy = 0;
3646 if (I != E) {
3647 ExpectedTy = *I++;
3648 } else if (!Ty->isVarArg()) {
3649 return Error(ArgList[i].Loc, "too many arguments specified");
3650 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003651
Chris Lattnerdf986172009-01-02 07:01:27 +00003652 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3653 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3654 ExpectedTy->getDescription() + "'");
3655 Args.push_back(ArgList[i].V);
3656 if (ArgList[i].Attrs != Attribute::None)
3657 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3658 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003659
Chris Lattnerdf986172009-01-02 07:01:27 +00003660 if (I != E)
3661 return Error(CallLoc, "not enough parameters specified for call");
3662
3663 if (FnAttrs != Attribute::None)
3664 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3665
3666 // Finish off the Attributes and check them
3667 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003668
Chris Lattnerdf986172009-01-02 07:01:27 +00003669 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3670 CI->setTailCall(isTail);
3671 CI->setCallingConv(CC);
3672 CI->setAttributes(PAL);
3673 Inst = CI;
3674 return false;
3675}
3676
3677//===----------------------------------------------------------------------===//
3678// Memory Instructions.
3679//===----------------------------------------------------------------------===//
3680
3681/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003682/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003683int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003684 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003686 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003687 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003688 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003689
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003690 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003691 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003692 if (Lex.getKind() == lltok::kw_align) {
3693 if (ParseOptionalAlignment(Alignment)) return true;
3694 } else if (Lex.getKind() == lltok::MetadataVar) {
3695 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003696 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003697 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3698 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3699 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003700 }
3701 }
3702
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003703 if (Size && !Size->getType()->isIntegerTy())
3704 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003705
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003706 Inst = new AllocaInst(Ty, Size, Alignment);
3707 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003708}
3709
3710/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003711/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003712int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3713 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003714 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003715 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003716 bool AteExtraComma = false;
3717 if (ParseTypeAndValue(Val, Loc, PFS) ||
3718 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3719 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003720
Duncan Sands1df98592010-02-16 11:11:14 +00003721 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3723 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003724
Chris Lattnerdf986172009-01-02 07:01:27 +00003725 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003726 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003727}
3728
3729/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003730/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003731int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3732 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003733 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003734 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003735 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003736 if (ParseTypeAndValue(Val, Loc, PFS) ||
3737 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003738 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3739 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003741
Duncan Sands1df98592010-02-16 11:11:14 +00003742 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003743 return Error(PtrLoc, "store operand must be a pointer");
3744 if (!Val->getType()->isFirstClassType())
3745 return Error(Loc, "store operand must be a first class value");
3746 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3747 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003748
Chris Lattnerdf986172009-01-02 07:01:27 +00003749 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003750 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003751}
3752
3753/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003754/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003755/// FIXME: Remove support for getresult in LLVM 3.0
3756bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3757 Value *Val; LocTy ValLoc, EltLoc;
3758 unsigned Element;
3759 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3760 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003761 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003762 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003763
Duncan Sands1df98592010-02-16 11:11:14 +00003764 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003765 return Error(ValLoc, "getresult inst requires an aggregate operand");
3766 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3767 return Error(EltLoc, "invalid getresult index for value");
3768 Inst = ExtractValueInst::Create(Val, Element);
3769 return false;
3770}
3771
3772/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003773/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003774int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003775 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003776
Dan Gohmandcb40a32009-07-29 15:58:36 +00003777 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003778
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003779 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003780
Duncan Sands1df98592010-02-16 11:11:14 +00003781 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003782 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003783
Chris Lattnerdf986172009-01-02 07:01:27 +00003784 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003785 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003786 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003787 if (Lex.getKind() == lltok::MetadataVar) {
3788 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003789 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003790 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003791 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003792 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003793 return Error(EltLoc, "getelementptr index must be an integer");
3794 Indices.push_back(Val);
3795 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003796
Chris Lattnerdf986172009-01-02 07:01:27 +00003797 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3798 Indices.begin(), Indices.end()))
3799 return Error(Loc, "invalid getelementptr indices");
3800 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003801 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003802 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003803 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003804}
3805
3806/// ParseExtractValue
3807/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003808int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003809 Value *Val; LocTy Loc;
3810 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003811 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003812 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003813 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003814 return true;
3815
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003816 if (!Val->getType()->isAggregateType())
3817 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003818
3819 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3820 Indices.end()))
3821 return Error(Loc, "invalid indices for extractvalue");
3822 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003823 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003824}
3825
3826/// ParseInsertValue
3827/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003828int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003829 Value *Val0, *Val1; LocTy Loc0, Loc1;
3830 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003831 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003832 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3833 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3834 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003835 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003836 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003837
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003838 if (!Val0->getType()->isAggregateType())
3839 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003840
Chris Lattnerdf986172009-01-02 07:01:27 +00003841 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3842 Indices.end()))
3843 return Error(Loc0, "invalid indices for insertvalue");
3844 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003845 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003846}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003847
3848//===----------------------------------------------------------------------===//
3849// Embedded metadata.
3850//===----------------------------------------------------------------------===//
3851
3852/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003853/// ::= Element (',' Element)*
3854/// Element
3855/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003856bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003857 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003858 // Check for an empty list.
3859 if (Lex.getKind() == lltok::rbrace)
3860 return false;
3861
Nick Lewycky21cc4462009-04-04 07:22:01 +00003862 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003863 // Null is a special case since it is typeless.
3864 if (EatIfPresent(lltok::kw_null)) {
3865 Elts.push_back(0);
3866 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003867 }
Chris Lattnera7352392009-12-30 04:42:57 +00003868
3869 Value *V = 0;
3870 PATypeHolder Ty(Type::getVoidTy(Context));
3871 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003872 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003873 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003874 return true;
3875
Nick Lewyckycb337992009-05-10 20:57:05 +00003876 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003877 } while (EatIfPresent(lltok::comma));
3878
3879 return false;
3880}