blob: 9096120c2d16ca67c0f58c209ab13d25c7217579 [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);
Chris Lattnerd5890992011-06-17 07:06:44 +0000355 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattnerdf986172009-01-02 07:01:27 +0000358 // Inserting a name that is already defined, get the existing name.
359 const Type *Existing = M->getTypeByName(Name);
360 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000361
Chris Lattnerd5890992011-06-17 07:06:44 +0000362 // Otherwise, this is an attempt to redefine a type, report the error.
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
364 Ty->getDescription() + "'");
365}
366
367
368/// toplevelentity
369/// ::= 'declare' FunctionHeader
370bool LLParser::ParseDeclare() {
371 assert(Lex.getKind() == lltok::kw_declare);
372 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000373
Chris Lattnerdf986172009-01-02 07:01:27 +0000374 Function *F;
375 return ParseFunctionHeader(F, false);
376}
377
378/// toplevelentity
379/// ::= 'define' FunctionHeader '{' ...
380bool LLParser::ParseDefine() {
381 assert(Lex.getKind() == lltok::kw_define);
382 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattnerdf986172009-01-02 07:01:27 +0000384 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000385 return ParseFunctionHeader(F, true) ||
386 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000387}
388
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000389/// ParseGlobalType
390/// ::= 'constant'
391/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000392bool LLParser::ParseGlobalType(bool &IsConstant) {
393 if (Lex.getKind() == lltok::kw_constant)
394 IsConstant = true;
395 else if (Lex.getKind() == lltok::kw_global)
396 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000397 else {
398 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000399 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000400 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000401 Lex.Lex();
402 return false;
403}
404
Dan Gohman3845e502009-08-12 23:32:33 +0000405/// ParseUnnamedGlobal:
406/// OptionalVisibility ALIAS ...
407/// OptionalLinkage OptionalVisibility ... -> global variable
408/// GlobalID '=' OptionalVisibility ALIAS ...
409/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
410bool LLParser::ParseUnnamedGlobal() {
411 unsigned VarID = NumberedVals.size();
412 std::string Name;
413 LocTy NameLoc = Lex.getLoc();
414
415 // Handle the GlobalID form.
416 if (Lex.getKind() == lltok::GlobalID) {
417 if (Lex.getUIntVal() != VarID)
418 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000419 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000420 Lex.Lex(); // eat GlobalID;
421
422 if (ParseToken(lltok::equal, "expected '=' after name"))
423 return true;
424 }
425
426 bool HasLinkage;
427 unsigned Linkage, Visibility;
428 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
429 ParseOptionalVisibility(Visibility))
430 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000431
Dan Gohman3845e502009-08-12 23:32:33 +0000432 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434 return ParseAlias(Name, NameLoc, Visibility);
435}
436
Chris Lattnerdf986172009-01-02 07:01:27 +0000437/// ParseNamedGlobal:
438/// GlobalVar '=' OptionalVisibility ALIAS ...
439/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
440bool LLParser::ParseNamedGlobal() {
441 assert(Lex.getKind() == lltok::GlobalVar);
442 LocTy NameLoc = Lex.getLoc();
443 std::string Name = Lex.getStrVal();
444 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000445
Chris Lattnerdf986172009-01-02 07:01:27 +0000446 bool HasLinkage;
447 unsigned Linkage, Visibility;
448 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
449 ParseOptionalLinkage(Linkage, HasLinkage) ||
450 ParseOptionalVisibility(Visibility))
451 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000452
Chris Lattnerdf986172009-01-02 07:01:27 +0000453 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
454 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
455 return ParseAlias(Name, NameLoc, Visibility);
456}
457
Devang Patel256be962009-07-20 19:00:08 +0000458// MDString:
459// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000460bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000461 std::string Str;
462 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000463 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000464 return false;
465}
466
467// MDNode:
468// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000469//
470/// This version of ParseMDNodeID returns the slot number and null in the case
471/// of a forward reference.
472bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
473 // !{ ..., !42, ... }
474 if (ParseUInt32(SlotNo)) return true;
475
476 // Check existing MDNode.
477 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
478 Result = NumberedMetadata[SlotNo];
479 else
480 Result = 0;
481 return false;
482}
483
Chris Lattner4a72efc2009-12-30 04:15:23 +0000484bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000485 // !{ ..., !42, ... }
486 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000487 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000488
Chris Lattner449c3102010-04-01 05:14:45 +0000489 // If not a forward reference, just return it now.
490 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000491
Chris Lattner449c3102010-04-01 05:14:45 +0000492 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000493 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000494 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000495
496 if (NumberedMetadata.size() <= MID)
497 NumberedMetadata.resize(MID+1);
498 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000499 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000500 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000501}
Devang Patel256be962009-07-20 19:00:08 +0000502
Chris Lattner84d03b12009-12-29 22:35:39 +0000503/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000504/// !foo = !{ !1, !2 }
505bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000506 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000507 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000508 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000509
Chris Lattner84d03b12009-12-29 22:35:39 +0000510 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000511 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000512 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000513 return true;
514
Dan Gohman17aa92c2010-07-21 23:38:33 +0000515 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000516 if (Lex.getKind() != lltok::rbrace)
517 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000518 if (ParseToken(lltok::exclaim, "Expected '!' here"))
519 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000520
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000521 MDNode *N = 0;
522 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000523 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000524 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000525
526 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
527 return true;
528
Devang Pateleff2ab62009-07-29 00:34:02 +0000529 return false;
530}
531
Devang Patel923078c2009-07-01 19:21:12 +0000532/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000533/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000534bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000535 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000536 Lex.Lex();
537 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000538
539 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000540 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000541 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000542 if (ParseUInt32(MetadataID) ||
543 ParseToken(lltok::equal, "expected '=' here") ||
544 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000545 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000546 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000547 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000548 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000549 return true;
550
Jay Foadec9186b2011-04-21 19:59:31 +0000551 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000552
553 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000554 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000555 FI = ForwardRefMDNodes.find(MetadataID);
556 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000557 MDNode *Temp = FI->second.first;
558 Temp->replaceAllUsesWith(Init);
559 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000560 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000561
562 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
563 } else {
564 if (MetadataID >= NumberedMetadata.size())
565 NumberedMetadata.resize(MetadataID+1);
566
567 if (NumberedMetadata[MetadataID] != 0)
568 return TokError("Metadata id is already used");
569 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000570 }
571
Devang Patel923078c2009-07-01 19:21:12 +0000572 return false;
573}
574
Chris Lattnerdf986172009-01-02 07:01:27 +0000575/// ParseAlias:
576/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
577/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000578/// ::= TypeAndValue
579/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000580/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000581///
582/// Everything through visibility has already been parsed.
583///
584bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
585 unsigned Visibility) {
586 assert(Lex.getKind() == lltok::kw_alias);
587 Lex.Lex();
588 unsigned Linkage;
589 LocTy LinkageLoc = Lex.getLoc();
590 if (ParseOptionalLinkage(Linkage))
591 return true;
592
593 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000594 Linkage != GlobalValue::WeakAnyLinkage &&
595 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000596 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000597 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000598 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000599 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
600 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000601 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000602
Chris Lattnerdf986172009-01-02 07:01:27 +0000603 Constant *Aliasee;
604 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000605 if (Lex.getKind() != lltok::kw_bitcast &&
606 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000607 if (ParseGlobalTypeAndValue(Aliasee)) return true;
608 } else {
609 // The bitcast dest type is not present, it is implied by the dest type.
610 ValID ID;
611 if (ParseValID(ID)) return true;
612 if (ID.Kind != ValID::t_Constant)
613 return Error(AliaseeLoc, "invalid aliasee");
614 Aliasee = ID.ConstantVal;
615 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000616
Duncan Sands1df98592010-02-16 11:11:14 +0000617 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000618 return Error(AliaseeLoc, "alias must have pointer type");
619
620 // Okay, create the alias but do not insert it into the module yet.
621 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
622 (GlobalValue::LinkageTypes)Linkage, Name,
623 Aliasee);
624 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000625
Chris Lattnerdf986172009-01-02 07:01:27 +0000626 // See if this value already exists in the symbol table. If so, it is either
627 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000628 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 // See if this was a redefinition. If so, there is no entry in
630 // ForwardRefVals.
631 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
632 I = ForwardRefVals.find(Name);
633 if (I == ForwardRefVals.end())
634 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
635
636 // Otherwise, this was a definition of forward ref. Verify that types
637 // agree.
638 if (Val->getType() != GA->getType())
639 return Error(NameLoc,
640 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000641
Chris Lattnerdf986172009-01-02 07:01:27 +0000642 // If they agree, just RAUW the old value with the alias and remove the
643 // forward ref info.
644 Val->replaceAllUsesWith(GA);
645 Val->eraseFromParent();
646 ForwardRefVals.erase(I);
647 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000648
Chris Lattnerdf986172009-01-02 07:01:27 +0000649 // Insert into the module, we know its name won't collide now.
650 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000651 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattnerdf986172009-01-02 07:01:27 +0000653 return false;
654}
655
656/// ParseGlobal
657/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000658/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000659/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000660/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000661///
662/// Everything through visibility has been parsed already.
663///
664bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
665 unsigned Linkage, bool HasLinkage,
666 unsigned Visibility) {
667 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000668 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000669 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000671
Owen Anderson1d0be152009-08-13 21:58:54 +0000672 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000673 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
674 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000675 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
676 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 ParseGlobalType(IsConstant) ||
678 ParseType(Ty, TyLoc))
679 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000680
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 // If the linkage is specified and is external, then no initializer is
682 // present.
683 Constant *Init = 0;
684 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000685 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000686 Linkage != GlobalValue::ExternalLinkage)) {
687 if (ParseGlobalValue(Ty, Init))
688 return true;
689 }
690
Duncan Sands1df98592010-02-16 11:11:14 +0000691 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000692 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000693
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 GlobalVariable *GV = 0;
695
696 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000697 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000698 if (GlobalValue *GVal = M->getNamedValue(Name)) {
699 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
700 return Error(NameLoc, "redefinition of global '@" + Name + "'");
701 GV = cast<GlobalVariable>(GVal);
702 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000703 } else {
704 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
705 I = ForwardRefValIDs.find(NumberedVals.size());
706 if (I != ForwardRefValIDs.end()) {
707 GV = cast<GlobalVariable>(I->second.first);
708 ForwardRefValIDs.erase(I);
709 }
710 }
711
712 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000713 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000714 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000715 } else {
716 if (GV->getType()->getElementType() != Ty)
717 return Error(TyLoc,
718 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000719
Chris Lattnerdf986172009-01-02 07:01:27 +0000720 // Move the forward-reference to the correct spot in the module.
721 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
722 }
723
724 if (Name.empty())
725 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000726
Chris Lattnerdf986172009-01-02 07:01:27 +0000727 // Set the parsed properties on the global.
728 if (Init)
729 GV->setInitializer(Init);
730 GV->setConstant(IsConstant);
731 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
732 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
733 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000734 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattnerdf986172009-01-02 07:01:27 +0000736 // Parse attributes on the global.
737 while (Lex.getKind() == lltok::comma) {
738 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000739
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 if (Lex.getKind() == lltok::kw_section) {
741 Lex.Lex();
742 GV->setSection(Lex.getStrVal());
743 if (ParseToken(lltok::StringConstant, "expected global section string"))
744 return true;
745 } else if (Lex.getKind() == lltok::kw_align) {
746 unsigned Alignment;
747 if (ParseOptionalAlignment(Alignment)) return true;
748 GV->setAlignment(Alignment);
749 } else {
750 TokError("unknown global variable property!");
751 }
752 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000753
Chris Lattnerdf986172009-01-02 07:01:27 +0000754 return false;
755}
756
757
758//===----------------------------------------------------------------------===//
759// GlobalValue Reference/Resolution Routines.
760//===----------------------------------------------------------------------===//
761
762/// GetGlobalVal - Get a value with the specified name or ID, creating a
763/// forward reference record if needed. This can return null if the value
764/// exists but does not have the right type.
765GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
766 LocTy Loc) {
767 const PointerType *PTy = dyn_cast<PointerType>(Ty);
768 if (PTy == 0) {
769 Error(Loc, "global variable reference must have pointer type");
770 return 0;
771 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Chris Lattnerdf986172009-01-02 07:01:27 +0000773 // Look this name up in the normal function symbol table.
774 GlobalValue *Val =
775 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 // If this is a forward reference for the value, see if we already created a
778 // forward ref record.
779 if (Val == 0) {
780 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
781 I = ForwardRefVals.find(Name);
782 if (I != ForwardRefVals.end())
783 Val = I->second.first;
784 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000785
Chris Lattnerdf986172009-01-02 07:01:27 +0000786 // If we have the value in the symbol table or fwd-ref table, return it.
787 if (Val) {
788 if (Val->getType() == Ty) return Val;
789 Error(Loc, "'@" + Name + "' defined with type '" +
790 Val->getType()->getDescription() + "'");
791 return 0;
792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Chris Lattnerdf986172009-01-02 07:01:27 +0000794 // Otherwise, create a new forward reference for this value and remember it.
795 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000796 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
797 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000798 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000799 Error(Loc, "function may not return opaque type");
800 return 0;
801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000802
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000803 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000804 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000805 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
806 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000807 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000808
Chris Lattnerdf986172009-01-02 07:01:27 +0000809 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
810 return FwdVal;
811}
812
813GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
814 const PointerType *PTy = dyn_cast<PointerType>(Ty);
815 if (PTy == 0) {
816 Error(Loc, "global variable reference must have pointer type");
817 return 0;
818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Chris Lattnerdf986172009-01-02 07:01:27 +0000820 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000821
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 // If this is a forward reference for the value, see if we already created a
823 // forward ref record.
824 if (Val == 0) {
825 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
826 I = ForwardRefValIDs.find(ID);
827 if (I != ForwardRefValIDs.end())
828 Val = I->second.first;
829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Chris Lattnerdf986172009-01-02 07:01:27 +0000831 // If we have the value in the symbol table or fwd-ref table, return it.
832 if (Val) {
833 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000834 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +0000835 Val->getType()->getDescription() + "'");
836 return 0;
837 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000838
Chris Lattnerdf986172009-01-02 07:01:27 +0000839 // Otherwise, create a new forward reference for this value and remember it.
840 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000841 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
842 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000843 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000844 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000845 return 0;
846 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000847 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000848 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000849 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
850 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000851 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000852
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
854 return FwdVal;
855}
856
857
858//===----------------------------------------------------------------------===//
859// Helper Routines.
860//===----------------------------------------------------------------------===//
861
862/// ParseToken - If the current token has the specified kind, eat it and return
863/// success. Otherwise, emit the specified error and return failure.
864bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
865 if (Lex.getKind() != T)
866 return TokError(ErrMsg);
867 Lex.Lex();
868 return false;
869}
870
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000871/// ParseStringConstant
872/// ::= StringConstant
873bool LLParser::ParseStringConstant(std::string &Result) {
874 if (Lex.getKind() != lltok::StringConstant)
875 return TokError("expected string constant");
876 Result = Lex.getStrVal();
877 Lex.Lex();
878 return false;
879}
880
881/// ParseUInt32
882/// ::= uint32
883bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000884 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
885 return TokError("expected integer");
886 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
887 if (Val64 != unsigned(Val64))
888 return TokError("expected 32-bit integer (too large)");
889 Val = Val64;
890 Lex.Lex();
891 return false;
892}
893
894
895/// ParseOptionalAddrSpace
896/// := /*empty*/
897/// := 'addrspace' '(' uint32 ')'
898bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
899 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000900 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000901 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000902 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000903 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000904 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000905}
Chris Lattnerdf986172009-01-02 07:01:27 +0000906
907/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
908/// indicates what kind of attribute list this is: 0: function arg, 1: result,
909/// 2: function attr.
910bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
911 Attrs = Attribute::None;
912 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000913
Chris Lattnerdf986172009-01-02 07:01:27 +0000914 while (1) {
915 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000916 default: // End of attributes.
917 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
918 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000919
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000920 // As a hack, we allow "align 2" on functions as a synonym for
921 // "alignstack 2".
922 if (AttrKind == 2 &&
923 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
924 return Error(AttrLoc, "invalid use of attribute on a function");
925
926 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000927 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000928
Chris Lattnerdf986172009-01-02 07:01:27 +0000929 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000930 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
931 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
932 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
933 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
934 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
935 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
936 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
937 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000938
Devang Patel578efa92009-06-05 21:57:13 +0000939 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
940 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000941 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Devang Patel578efa92009-06-05 21:57:13 +0000942 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
943 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
944 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000945 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000946 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
947 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
948 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
949 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
950 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
951 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000952 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000953 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
John McCall3a3465b2011-06-15 20:36:13 +0000954 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000955
Charles Davis1e063d12010-02-12 00:31:15 +0000956 case lltok::kw_alignstack: {
957 unsigned Alignment;
958 if (ParseOptionalStackAlignment(Alignment))
959 return true;
960 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
961 continue;
962 }
963
Chris Lattnerdf986172009-01-02 07:01:27 +0000964 case lltok::kw_align: {
965 unsigned Alignment;
966 if (ParseOptionalAlignment(Alignment))
967 return true;
968 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
969 continue;
970 }
Charles Davis1e063d12010-02-12 00:31:15 +0000971
Chris Lattnerdf986172009-01-02 07:01:27 +0000972 }
973 Lex.Lex();
974 }
975}
976
977/// ParseOptionalLinkage
978/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000979/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000980/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000981/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000982/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000983/// ::= 'internal'
984/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000985/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000986/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000987/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000988/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000989/// ::= 'appending'
990/// ::= 'dllexport'
991/// ::= 'common'
992/// ::= 'dllimport'
993/// ::= 'extern_weak'
994/// ::= 'external'
995bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
996 HasLinkage = false;
997 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000998 default: Res=GlobalValue::ExternalLinkage; return false;
999 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1000 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001001 case lltok::kw_linker_private_weak:
1002 Res = GlobalValue::LinkerPrivateWeakLinkage;
1003 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001004 case lltok::kw_linker_private_weak_def_auto:
1005 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1006 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001007 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1008 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1009 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1010 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1011 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001012 case lltok::kw_available_externally:
1013 Res = GlobalValue::AvailableExternallyLinkage;
1014 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001015 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1016 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1017 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1018 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1019 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1020 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001021 }
1022 Lex.Lex();
1023 HasLinkage = true;
1024 return false;
1025}
1026
1027/// ParseOptionalVisibility
1028/// ::= /*empty*/
1029/// ::= 'default'
1030/// ::= 'hidden'
1031/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001032///
Chris Lattnerdf986172009-01-02 07:01:27 +00001033bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1034 switch (Lex.getKind()) {
1035 default: Res = GlobalValue::DefaultVisibility; return false;
1036 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1037 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1038 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1039 }
1040 Lex.Lex();
1041 return false;
1042}
1043
1044/// ParseOptionalCallingConv
1045/// ::= /*empty*/
1046/// ::= 'ccc'
1047/// ::= 'fastcc'
1048/// ::= 'coldcc'
1049/// ::= 'x86_stdcallcc'
1050/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001051/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001052/// ::= 'arm_apcscc'
1053/// ::= 'arm_aapcscc'
1054/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001055/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001056/// ::= 'ptx_kernel'
1057/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001058/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001059///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001060bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001061 switch (Lex.getKind()) {
1062 default: CC = CallingConv::C; return false;
1063 case lltok::kw_ccc: CC = CallingConv::C; break;
1064 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1065 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1066 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1067 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001068 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001069 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1070 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1071 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001072 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001073 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1074 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001075 case lltok::kw_cc: {
1076 unsigned ArbitraryCC;
1077 Lex.Lex();
1078 if (ParseUInt32(ArbitraryCC)) {
1079 return true;
1080 } else
1081 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1082 return false;
1083 }
1084 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001085 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001086
Chris Lattnerdf986172009-01-02 07:01:27 +00001087 Lex.Lex();
1088 return false;
1089}
1090
Chris Lattnerb8c46862009-12-30 05:31:19 +00001091/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001092/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001093bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1094 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001095 do {
1096 if (Lex.getKind() != lltok::MetadataVar)
1097 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001098
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001099 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001100 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001101 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001102
Chris Lattner442ffa12009-12-29 21:53:55 +00001103 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001104 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001105
1106 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001107 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001108
Dan Gohman68261142010-08-24 14:35:45 +00001109 // This code is similar to that of ParseMetadataValue, however it needs to
1110 // have special-case code for a forward reference; see the comments on
1111 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1112 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001113 if (Lex.getKind() == lltok::lbrace) {
1114 ValID ID;
1115 if (ParseMetadataListValue(ID, PFS))
1116 return true;
1117 assert(ID.Kind == ValID::t_MDNode);
1118 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001119 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001120 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001121 if (ParseMDNodeID(Node, NodeID))
1122 return true;
1123 if (Node) {
1124 // If we got the node, add it to the instruction.
1125 Inst->setMetadata(MDK, Node);
1126 } else {
1127 MDRef R = { Loc, MDK, NodeID };
1128 // Otherwise, remember that this should be resolved later.
1129 ForwardRefInstMetadata[Inst].push_back(R);
1130 }
Chris Lattner449c3102010-04-01 05:14:45 +00001131 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001132
1133 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001134 } while (EatIfPresent(lltok::comma));
1135 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001136}
1137
Chris Lattnerdf986172009-01-02 07:01:27 +00001138/// ParseOptionalAlignment
1139/// ::= /* empty */
1140/// ::= 'align' 4
1141bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1142 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001143 if (!EatIfPresent(lltok::kw_align))
1144 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001145 LocTy AlignLoc = Lex.getLoc();
1146 if (ParseUInt32(Alignment)) return true;
1147 if (!isPowerOf2_32(Alignment))
1148 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001149 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001150 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001151 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001152}
1153
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001154/// ParseOptionalCommaAlign
1155/// ::=
1156/// ::= ',' align 4
1157///
1158/// This returns with AteExtraComma set to true if it ate an excess comma at the
1159/// end.
1160bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1161 bool &AteExtraComma) {
1162 AteExtraComma = false;
1163 while (EatIfPresent(lltok::comma)) {
1164 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001165 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001166 AteExtraComma = true;
1167 return false;
1168 }
1169
Chris Lattner093eed12010-04-23 00:50:50 +00001170 if (Lex.getKind() != lltok::kw_align)
1171 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001172
Chris Lattner093eed12010-04-23 00:50:50 +00001173 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001174 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001175
Devang Patelf633a062009-09-17 23:04:48 +00001176 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001177}
1178
Charles Davis1e063d12010-02-12 00:31:15 +00001179/// ParseOptionalStackAlignment
1180/// ::= /* empty */
1181/// ::= 'alignstack' '(' 4 ')'
1182bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1183 Alignment = 0;
1184 if (!EatIfPresent(lltok::kw_alignstack))
1185 return false;
1186 LocTy ParenLoc = Lex.getLoc();
1187 if (!EatIfPresent(lltok::lparen))
1188 return Error(ParenLoc, "expected '('");
1189 LocTy AlignLoc = Lex.getLoc();
1190 if (ParseUInt32(Alignment)) return true;
1191 ParenLoc = Lex.getLoc();
1192 if (!EatIfPresent(lltok::rparen))
1193 return Error(ParenLoc, "expected ')'");
1194 if (!isPowerOf2_32(Alignment))
1195 return Error(AlignLoc, "stack alignment is not a power of two");
1196 return false;
1197}
Devang Patelf633a062009-09-17 23:04:48 +00001198
Chris Lattner628c13a2009-12-30 05:14:00 +00001199/// ParseIndexList - This parses the index list for an insert/extractvalue
1200/// instruction. This sets AteExtraComma in the case where we eat an extra
1201/// comma at the end of the line and find that it is followed by metadata.
1202/// Clients that don't allow metadata can call the version of this function that
1203/// only takes one argument.
1204///
Chris Lattnerdf986172009-01-02 07:01:27 +00001205/// ParseIndexList
1206/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001207///
1208bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1209 bool &AteExtraComma) {
1210 AteExtraComma = false;
1211
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 if (Lex.getKind() != lltok::comma)
1213 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001214
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001215 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001216 if (Lex.getKind() == lltok::MetadataVar) {
1217 AteExtraComma = true;
1218 return false;
1219 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001220 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001221 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 Indices.push_back(Idx);
1223 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001224
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 return false;
1226}
1227
1228//===----------------------------------------------------------------------===//
1229// Type Parsing.
1230//===----------------------------------------------------------------------===//
1231
1232/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001233bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1234 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001235 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001236
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 // Verify no unresolved uprefs.
1238 if (!UpRefs.empty())
1239 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001240
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001241 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001242 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001243
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 return false;
1245}
1246
1247/// HandleUpRefs - Every time we finish a new layer of types, this function is
1248/// called. It loops through the UpRefs vector, which is a list of the
1249/// currently active types. For each type, if the up-reference is contained in
1250/// the newly completed type, we decrement the level count. When the level
1251/// count reaches zero, the up-referenced type is the type that is passed in:
1252/// thus we can complete the cycle.
1253///
1254PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1255 // If Ty isn't abstract, or if there are no up-references in it, then there is
1256 // nothing to resolve here.
1257 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001258
Chris Lattnerdf986172009-01-02 07:01:27 +00001259 PATypeHolder Ty(ty);
1260#if 0
David Greene0e28d762009-12-23 23:38:28 +00001261 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001262 << "' newly formed. Resolving upreferences.\n"
1263 << UpRefs.size() << " upreferences active!\n";
1264#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001265
Chris Lattnerdf986172009-01-02 07:01:27 +00001266 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1267 // to zero), we resolve them all together before we resolve them to Ty. At
1268 // the end of the loop, if there is anything to resolve to Ty, it will be in
1269 // this variable.
1270 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1273 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1274 bool ContainsType =
1275 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1276 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Chris Lattnerdf986172009-01-02 07:01:27 +00001278#if 0
David Greene0e28d762009-12-23 23:38:28 +00001279 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1281 << (ContainsType ? "true" : "false")
1282 << " level=" << UpRefs[i].NestingLevel << "\n";
1283#endif
1284 if (!ContainsType)
1285 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001286
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 // Decrement level of upreference
1288 unsigned Level = --UpRefs[i].NestingLevel;
1289 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1292 if (Level != 0)
1293 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001294
Chris Lattnerdf986172009-01-02 07:01:27 +00001295#if 0
David Greene0e28d762009-12-23 23:38:28 +00001296 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001297#endif
1298 if (!TypeToResolve)
1299 TypeToResolve = UpRefs[i].UpRefTy;
1300 else
1301 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1302 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1303 --i; // Do not skip the next element.
1304 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001305
Chris Lattnerdf986172009-01-02 07:01:27 +00001306 if (TypeToResolve)
1307 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001308
Chris Lattnerdf986172009-01-02 07:01:27 +00001309 return Ty;
1310}
1311
1312
1313/// ParseTypeRec - The recursive function used to process the internal
1314/// implementation details of types.
1315bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1316 switch (Lex.getKind()) {
1317 default:
1318 return TokError("expected type");
1319 case lltok::Type:
1320 // TypeRec ::= 'float' | 'void' (etc)
1321 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001322 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001323 break;
1324 case lltok::kw_opaque:
1325 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001326 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 Lex.Lex();
1328 break;
1329 case lltok::lbrace:
1330 // TypeRec ::= '{' ... '}'
1331 if (ParseStructType(Result, false))
1332 return true;
1333 break;
1334 case lltok::lsquare:
1335 // TypeRec ::= '[' ... ']'
1336 Lex.Lex(); // eat the lsquare.
1337 if (ParseArrayVectorType(Result, false))
1338 return true;
1339 break;
1340 case lltok::less: // Either vector or packed struct.
1341 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001342 Lex.Lex();
1343 if (Lex.getKind() == lltok::lbrace) {
1344 if (ParseStructType(Result, true) ||
1345 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001347 } else if (ParseArrayVectorType(Result, true))
1348 return true;
1349 break;
1350 case lltok::LocalVar:
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 // TypeRec ::= %foo
1352 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1353 Result = T;
1354 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001355 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001356 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1357 std::make_pair(Result,
1358 Lex.getLoc())));
1359 M->addTypeName(Lex.getStrVal(), Result.get());
1360 }
1361 Lex.Lex();
1362 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001363
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 case lltok::LocalVarID:
1365 // TypeRec ::= %4
1366 if (Lex.getUIntVal() < NumberedTypes.size())
1367 Result = NumberedTypes[Lex.getUIntVal()];
1368 else {
1369 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1370 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1371 if (I != ForwardRefTypeIDs.end())
1372 Result = I->second.first;
1373 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001374 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001375 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1376 std::make_pair(Result,
1377 Lex.getLoc())));
1378 }
1379 }
1380 Lex.Lex();
1381 break;
1382 case lltok::backslash: {
1383 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001384 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001385 unsigned Val;
1386 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001387 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1389 Result = OT;
1390 break;
1391 }
1392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001393
1394 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001395 while (1) {
1396 switch (Lex.getKind()) {
1397 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001398 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001399
1400 // TypeRec ::= TypeRec '*'
1401 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001402 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001403 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001404 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001405 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001406 if (!PointerType::isValidElementType(Result.get()))
1407 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001408 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001409 Lex.Lex();
1410 break;
1411
1412 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1413 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001414 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001416 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001417 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001418 if (!PointerType::isValidElementType(Result.get()))
1419 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 unsigned AddrSpace;
1421 if (ParseOptionalAddrSpace(AddrSpace) ||
1422 ParseToken(lltok::star, "expected '*' in address space"))
1423 return true;
1424
Owen Andersondebcb012009-07-29 22:17:13 +00001425 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 break;
1427 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001428
Chris Lattnerdf986172009-01-02 07:01:27 +00001429 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1430 case lltok::lparen:
1431 if (ParseFunctionType(Result))
1432 return true;
1433 break;
1434 }
1435 }
1436}
1437
1438/// ParseParameterList
1439/// ::= '(' ')'
1440/// ::= '(' Arg (',' Arg)* ')'
1441/// Arg
1442/// ::= Type OptionalAttributes Value OptionalAttributes
1443bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1444 PerFunctionState &PFS) {
1445 if (ParseToken(lltok::lparen, "expected '(' in call"))
1446 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001447
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 while (Lex.getKind() != lltok::rparen) {
1449 // If this isn't the first argument, we need a comma.
1450 if (!ArgList.empty() &&
1451 ParseToken(lltok::comma, "expected ',' in argument list"))
1452 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001453
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 // Parse the argument.
1455 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001456 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001457 unsigned ArgAttrs1 = Attribute::None;
1458 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001459 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001460 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001461 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001462
Chris Lattner287881d2009-12-30 02:11:14 +00001463 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001464 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001465 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001466 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1467 }
1468
1469 Lex.Lex(); // Lex the ')'.
1470 return false;
1471}
1472
1473
1474
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001475/// ParseArgumentList - Parse the argument list for a function type or function
1476/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001477/// ::= '(' ArgTypeListI ')'
1478/// ArgTypeListI
1479/// ::= /*empty*/
1480/// ::= '...'
1481/// ::= ArgTypeList ',' '...'
1482/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001483///
Chris Lattnerdf986172009-01-02 07:01:27 +00001484bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001485 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001486 isVarArg = false;
1487 assert(Lex.getKind() == lltok::lparen);
1488 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001489
Chris Lattnerdf986172009-01-02 07:01:27 +00001490 if (Lex.getKind() == lltok::rparen) {
1491 // empty
1492 } else if (Lex.getKind() == lltok::dotdotdot) {
1493 isVarArg = true;
1494 Lex.Lex();
1495 } else {
1496 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001497 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001498 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001500
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001501 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1502 // types (such as a function returning a pointer to itself). If parsing a
1503 // function prototype, we require fully resolved types.
1504 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001505 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001507 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001508 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001509
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001510 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001511 Name = Lex.getStrVal();
1512 Lex.Lex();
1513 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001514
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001515 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001516 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattnerdf986172009-01-02 07:01:27 +00001518 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001519
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001520 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001521 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001522 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 break;
1525 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 // Otherwise must be an argument type.
1528 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001529 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001530 ParseOptionalAttrs(Attrs, 0)) return true;
1531
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001532 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001533 return Error(TypeLoc, "argument can not have void type");
1534
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001535 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001536 Name = Lex.getStrVal();
1537 Lex.Lex();
1538 } else {
1539 Name = "";
1540 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001541
Duncan Sands47c51882010-02-16 14:50:09 +00001542 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001543 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001544
Chris Lattnerdf986172009-01-02 07:01:27 +00001545 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1546 }
1547 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001548
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001550}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001551
Chris Lattnerdf986172009-01-02 07:01:27 +00001552/// ParseFunctionType
1553/// ::= Type ArgumentList OptionalAttrs
1554bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1555 assert(Lex.getKind() == lltok::lparen);
1556
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001557 if (!FunctionType::isValidReturnType(Result))
1558 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001559
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 std::vector<ArgInfo> ArgList;
1561 bool isVarArg;
Chris Lattnera16546a2011-06-17 17:37:13 +00001562 if (ParseArgumentList(ArgList, isVarArg, true))
Chris Lattnerdf986172009-01-02 07:01:27 +00001563 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattnerdf986172009-01-02 07:01:27 +00001565 // Reject names on the arguments lists.
1566 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1567 if (!ArgList[i].Name.empty())
1568 return Error(ArgList[i].Loc, "argument name invalid in function type");
Chris Lattnera16546a2011-06-17 17:37:13 +00001569 if (ArgList[i].Attrs != 0)
1570 return Error(ArgList[i].Loc,
1571 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001573
Chris Lattnerdf986172009-01-02 07:01:27 +00001574 std::vector<const Type*> ArgListTy;
1575 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1576 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001577
Owen Andersondebcb012009-07-29 22:17:13 +00001578 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001579 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 return false;
1581}
1582
1583/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1584/// TypeRec
1585/// ::= '{' '}'
1586/// ::= '{' TypeRec (',' TypeRec)* '}'
1587/// ::= '<' '{' '}' '>'
1588/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1589bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1590 assert(Lex.getKind() == lltok::lbrace);
1591 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001592
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001593 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001594 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 return false;
1596 }
1597
1598 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001599 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001600 if (ParseTypeRec(Result)) return true;
1601 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001603 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001604 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001605 if (!StructType::isValidElementType(Result))
1606 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001607
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001608 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001609 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001612 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001613 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001614 if (!StructType::isValidElementType(Result))
1615 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001616
Chris Lattnerdf986172009-01-02 07:01:27 +00001617 ParamsList.push_back(Result);
1618 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001619
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001620 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1621 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 std::vector<const Type*> ParamsListTy;
1624 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1625 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001626 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001627 return false;
1628}
1629
1630/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1631/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001632/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001633/// ::= '[' APSINTVAL 'x' Types ']'
1634/// ::= '<' APSINTVAL 'x' Types '>'
1635bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1636 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1637 Lex.getAPSIntVal().getBitWidth() > 64)
1638 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001639
Chris Lattnerdf986172009-01-02 07:01:27 +00001640 LocTy SizeLoc = Lex.getLoc();
1641 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001642 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001643
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001644 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1645 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001646
1647 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001648 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001650
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001651 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001652 return Error(TypeLoc, "array and vector element type cannot be void");
1653
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001654 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1655 "expected end of sequential type"))
1656 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattnerdf986172009-01-02 07:01:27 +00001658 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001659 if (Size == 0)
1660 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001661 if ((unsigned)Size != Size)
1662 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001663 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001665 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001666 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001667 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001668 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001669 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 }
1671 return false;
1672}
1673
1674//===----------------------------------------------------------------------===//
1675// Function Semantic Analysis.
1676//===----------------------------------------------------------------------===//
1677
Chris Lattner09d9ef42009-10-28 03:39:23 +00001678LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1679 int functionNumber)
1680 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001681
1682 // Insert unnamed arguments into the NumberedVals list.
1683 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1684 AI != E; ++AI)
1685 if (!AI->hasName())
1686 NumberedVals.push_back(AI);
1687}
1688
1689LLParser::PerFunctionState::~PerFunctionState() {
1690 // If there were any forward referenced non-basicblock values, delete them.
1691 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1692 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1693 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001694 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001695 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001696 delete I->second.first;
1697 I->second.first = 0;
1698 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001699
Chris Lattnerdf986172009-01-02 07:01:27 +00001700 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1701 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1702 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001703 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001704 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 delete I->second.first;
1706 I->second.first = 0;
1707 }
1708}
1709
Chris Lattner09d9ef42009-10-28 03:39:23 +00001710bool LLParser::PerFunctionState::FinishFunction() {
1711 // Check to see if someone took the address of labels in this block.
1712 if (!P.ForwardRefBlockAddresses.empty()) {
1713 ValID FunctionID;
1714 if (!F.getName().empty()) {
1715 FunctionID.Kind = ValID::t_GlobalName;
1716 FunctionID.StrVal = F.getName();
1717 } else {
1718 FunctionID.Kind = ValID::t_GlobalID;
1719 FunctionID.UIntVal = FunctionNumber;
1720 }
1721
1722 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1723 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1724 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1725 // Resolve all these references.
1726 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1727 return true;
1728
1729 P.ForwardRefBlockAddresses.erase(FRBAI);
1730 }
1731 }
1732
Chris Lattnerdf986172009-01-02 07:01:27 +00001733 if (!ForwardRefVals.empty())
1734 return P.Error(ForwardRefVals.begin()->second.second,
1735 "use of undefined value '%" + ForwardRefVals.begin()->first +
1736 "'");
1737 if (!ForwardRefValIDs.empty())
1738 return P.Error(ForwardRefValIDs.begin()->second.second,
1739 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001740 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 return false;
1742}
1743
1744
1745/// GetVal - Get a value with the specified name or ID, creating a
1746/// forward reference record if needed. This can return null if the value
1747/// exists but does not have the right type.
1748Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1749 const Type *Ty, LocTy Loc) {
1750 // Look this name up in the normal function symbol table.
1751 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001752
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 // If this is a forward reference for the value, see if we already created a
1754 // forward ref record.
1755 if (Val == 0) {
1756 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1757 I = ForwardRefVals.find(Name);
1758 if (I != ForwardRefVals.end())
1759 Val = I->second.first;
1760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001761
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 // If we have the value in the symbol table or fwd-ref table, return it.
1763 if (Val) {
1764 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001765 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001766 P.Error(Loc, "'%" + Name + "' is not a basic block");
1767 else
1768 P.Error(Loc, "'%" + Name + "' defined with type '" +
1769 Val->getType()->getDescription() + "'");
1770 return 0;
1771 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001772
Chris Lattnerdf986172009-01-02 07:01:27 +00001773 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001774 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001775 P.Error(Loc, "invalid use of a non-first-class type");
1776 return 0;
1777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001778
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 // Otherwise, create a new forward reference for this value and remember it.
1780 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001781 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001782 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001783 else
1784 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001785
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1787 return FwdVal;
1788}
1789
1790Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1791 LocTy Loc) {
1792 // Look this name up in the normal function symbol table.
1793 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001794
Chris Lattnerdf986172009-01-02 07:01:27 +00001795 // If this is a forward reference for the value, see if we already created a
1796 // forward ref record.
1797 if (Val == 0) {
1798 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1799 I = ForwardRefValIDs.find(ID);
1800 if (I != ForwardRefValIDs.end())
1801 Val = I->second.first;
1802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001803
Chris Lattnerdf986172009-01-02 07:01:27 +00001804 // If we have the value in the symbol table or fwd-ref table, return it.
1805 if (Val) {
1806 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001807 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001808 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001810 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 Val->getType()->getDescription() + "'");
1812 return 0;
1813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Duncan Sands47c51882010-02-16 14:50:09 +00001815 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001816 P.Error(Loc, "invalid use of a non-first-class type");
1817 return 0;
1818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001819
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 // Otherwise, create a new forward reference for this value and remember it.
1821 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001822 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001823 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 else
1825 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001826
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1828 return FwdVal;
1829}
1830
1831/// SetInstName - After an instruction is parsed and inserted into its
1832/// basic block, this installs its name.
1833bool LLParser::PerFunctionState::SetInstName(int NameID,
1834 const std::string &NameStr,
1835 LocTy NameLoc, Instruction *Inst) {
1836 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001837 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 if (NameID != -1 || !NameStr.empty())
1839 return P.Error(NameLoc, "instructions returning void cannot have a name");
1840 return false;
1841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842
Chris Lattnerdf986172009-01-02 07:01:27 +00001843 // If this was a numbered instruction, verify that the instruction is the
1844 // expected value and resolve any forward references.
1845 if (NameStr.empty()) {
1846 // If neither a name nor an ID was specified, just use the next ID.
1847 if (NameID == -1)
1848 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001849
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 if (unsigned(NameID) != NumberedVals.size())
1851 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001852 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001853
Chris Lattnerdf986172009-01-02 07:01:27 +00001854 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1855 ForwardRefValIDs.find(NameID);
1856 if (FI != ForwardRefValIDs.end()) {
1857 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 FI->second.first->getType()->getDescription() + "'");
1860 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001861 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 ForwardRefValIDs.erase(FI);
1863 }
1864
1865 NumberedVals.push_back(Inst);
1866 return false;
1867 }
1868
1869 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1870 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1871 FI = ForwardRefVals.find(NameStr);
1872 if (FI != ForwardRefVals.end()) {
1873 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001875 FI->second.first->getType()->getDescription() + "'");
1876 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001877 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 ForwardRefVals.erase(FI);
1879 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001880
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 // Set the name on the instruction.
1882 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001883
Benjamin Krameraf812352010-10-16 11:28:23 +00001884 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001885 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 NameStr + "'");
1887 return false;
1888}
1889
1890/// GetBB - Get a basic block with the specified name or ID, creating a
1891/// forward reference record if needed.
1892BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1893 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001894 return cast_or_null<BasicBlock>(GetVal(Name,
1895 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001896}
1897
1898BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001899 return cast_or_null<BasicBlock>(GetVal(ID,
1900 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001901}
1902
1903/// DefineBB - Define the specified basic block, which is either named or
1904/// unnamed. If there is an error, this returns null otherwise it returns
1905/// the block being defined.
1906BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1907 LocTy Loc) {
1908 BasicBlock *BB;
1909 if (Name.empty())
1910 BB = GetBB(NumberedVals.size(), Loc);
1911 else
1912 BB = GetBB(Name, Loc);
1913 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001914
Chris Lattnerdf986172009-01-02 07:01:27 +00001915 // Move the block to the end of the function. Forward ref'd blocks are
1916 // inserted wherever they happen to be referenced.
1917 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001918
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 // Remove the block from forward ref sets.
1920 if (Name.empty()) {
1921 ForwardRefValIDs.erase(NumberedVals.size());
1922 NumberedVals.push_back(BB);
1923 } else {
1924 // BB forward references are already in the function symbol table.
1925 ForwardRefVals.erase(Name);
1926 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927
Chris Lattnerdf986172009-01-02 07:01:27 +00001928 return BB;
1929}
1930
1931//===----------------------------------------------------------------------===//
1932// Constants.
1933//===----------------------------------------------------------------------===//
1934
1935/// ParseValID - Parse an abstract value that doesn't necessarily have a
1936/// type implied. For example, if we parse "4" we don't know what integer type
1937/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001938/// sanity. PFS is used to convert function-local operands of metadata (since
1939/// metadata operands are not just parsed here but also converted to values).
1940/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001941bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 ID.Loc = Lex.getLoc();
1943 switch (Lex.getKind()) {
1944 default: return TokError("expected value token");
1945 case lltok::GlobalID: // @42
1946 ID.UIntVal = Lex.getUIntVal();
1947 ID.Kind = ValID::t_GlobalID;
1948 break;
1949 case lltok::GlobalVar: // @foo
1950 ID.StrVal = Lex.getStrVal();
1951 ID.Kind = ValID::t_GlobalName;
1952 break;
1953 case lltok::LocalVarID: // %42
1954 ID.UIntVal = Lex.getUIntVal();
1955 ID.Kind = ValID::t_LocalID;
1956 break;
1957 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 ID.StrVal = Lex.getStrVal();
1959 ID.Kind = ValID::t_LocalName;
1960 break;
Dan Gohman83448032010-07-14 18:26:50 +00001961 case lltok::exclaim: // !42, !{...}, or !"foo"
1962 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001963 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001964 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001965 ID.Kind = ValID::t_APSInt;
1966 break;
1967 case lltok::APFloat:
1968 ID.APFloatVal = Lex.getAPFloatVal();
1969 ID.Kind = ValID::t_APFloat;
1970 break;
1971 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001972 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 ID.Kind = ValID::t_Constant;
1974 break;
1975 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001976 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001977 ID.Kind = ValID::t_Constant;
1978 break;
1979 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1980 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1981 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001982
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 case lltok::lbrace: {
1984 // ValID ::= '{' ConstVector '}'
1985 Lex.Lex();
1986 SmallVector<Constant*, 16> Elts;
1987 if (ParseGlobalValueVector(Elts) ||
1988 ParseToken(lltok::rbrace, "expected end of struct constant"))
1989 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001991 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1992 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 ID.Kind = ValID::t_Constant;
1994 return false;
1995 }
1996 case lltok::less: {
1997 // ValID ::= '<' ConstVector '>' --> Vector.
1998 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1999 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002000 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002001
Chris Lattnerdf986172009-01-02 07:01:27 +00002002 SmallVector<Constant*, 16> Elts;
2003 LocTy FirstEltLoc = Lex.getLoc();
2004 if (ParseGlobalValueVector(Elts) ||
2005 (isPackedStruct &&
2006 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2007 ParseToken(lltok::greater, "expected end of constant"))
2008 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002009
Chris Lattnerdf986172009-01-02 07:01:27 +00002010 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002011 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002012 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002013 ID.Kind = ValID::t_Constant;
2014 return false;
2015 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 if (Elts.empty())
2018 return Error(ID.Loc, "constant vector must not be empty");
2019
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002020 if (!Elts[0]->getType()->isIntegerTy() &&
2021 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 return Error(FirstEltLoc,
2023 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Chris Lattnerdf986172009-01-02 07:01:27 +00002025 // Verify that all the vector elements have the same type.
2026 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2027 if (Elts[i]->getType() != Elts[0]->getType())
2028 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002029 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002030 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002031
Chris Lattner2ca5c862011-02-15 00:14:00 +00002032 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 ID.Kind = ValID::t_Constant;
2034 return false;
2035 }
2036 case lltok::lsquare: { // Array Constant
2037 Lex.Lex();
2038 SmallVector<Constant*, 16> Elts;
2039 LocTy FirstEltLoc = Lex.getLoc();
2040 if (ParseGlobalValueVector(Elts) ||
2041 ParseToken(lltok::rsquare, "expected end of array constant"))
2042 return true;
2043
2044 // Handle empty element.
2045 if (Elts.empty()) {
2046 // Use undef instead of an array because it's inconvenient to determine
2047 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002048 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002049 return false;
2050 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002053 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002054 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002055
Owen Andersondebcb012009-07-29 22:17:13 +00002056 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002057
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002059 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 if (Elts[i]->getType() != Elts[0]->getType())
2061 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002062 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 " is not of type '" +Elts[0]->getType()->getDescription());
2064 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Owen Anderson1fd70962009-07-28 18:32:17 +00002066 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 ID.Kind = ValID::t_Constant;
2068 return false;
2069 }
2070 case lltok::kw_c: // c "foo"
2071 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002072 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2074 ID.Kind = ValID::t_Constant;
2075 return false;
2076
2077 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002078 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2079 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 Lex.Lex();
2081 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002082 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002083 ParseStringConstant(ID.StrVal) ||
2084 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002085 ParseToken(lltok::StringConstant, "expected constraint string"))
2086 return true;
2087 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002088 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002089 ID.Kind = ValID::t_InlineAsm;
2090 return false;
2091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092
Chris Lattner09d9ef42009-10-28 03:39:23 +00002093 case lltok::kw_blockaddress: {
2094 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2095 Lex.Lex();
2096
2097 ValID Fn, Label;
2098 LocTy FnLoc, LabelLoc;
2099
2100 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2101 ParseValID(Fn) ||
2102 ParseToken(lltok::comma, "expected comma in block address expression")||
2103 ParseValID(Label) ||
2104 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2105 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002106
Chris Lattner09d9ef42009-10-28 03:39:23 +00002107 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2108 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002109 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002110 return Error(Label.Loc, "expected basic block name in blockaddress");
2111
2112 // Make a global variable as a placeholder for this reference.
2113 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2114 false, GlobalValue::InternalLinkage,
2115 0, "");
2116 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2117 ID.ConstantVal = FwdRef;
2118 ID.Kind = ValID::t_Constant;
2119 return false;
2120 }
2121
Chris Lattnerdf986172009-01-02 07:01:27 +00002122 case lltok::kw_trunc:
2123 case lltok::kw_zext:
2124 case lltok::kw_sext:
2125 case lltok::kw_fptrunc:
2126 case lltok::kw_fpext:
2127 case lltok::kw_bitcast:
2128 case lltok::kw_uitofp:
2129 case lltok::kw_sitofp:
2130 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002131 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002132 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002133 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002134 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002135 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002136 Constant *SrcVal;
2137 Lex.Lex();
2138 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2139 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002140 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002141 ParseType(DestTy) ||
2142 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2143 return true;
2144 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2145 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2146 SrcVal->getType()->getDescription() + "' to '" +
2147 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002148 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002149 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002150 ID.Kind = ValID::t_Constant;
2151 return false;
2152 }
2153 case lltok::kw_extractvalue: {
2154 Lex.Lex();
2155 Constant *Val;
2156 SmallVector<unsigned, 4> Indices;
2157 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2158 ParseGlobalTypeAndValue(Val) ||
2159 ParseIndexList(Indices) ||
2160 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2161 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002162
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002163 if (!Val->getType()->isAggregateType())
2164 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2166 Indices.end()))
2167 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002168 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002169 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 ID.Kind = ValID::t_Constant;
2171 return false;
2172 }
2173 case lltok::kw_insertvalue: {
2174 Lex.Lex();
2175 Constant *Val0, *Val1;
2176 SmallVector<unsigned, 4> Indices;
2177 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2178 ParseGlobalTypeAndValue(Val0) ||
2179 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2180 ParseGlobalTypeAndValue(Val1) ||
2181 ParseIndexList(Indices) ||
2182 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2183 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002184 if (!Val0->getType()->isAggregateType())
2185 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2187 Indices.end()))
2188 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002189 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002190 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002191 ID.Kind = ValID::t_Constant;
2192 return false;
2193 }
2194 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002195 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002196 unsigned PredVal, Opc = Lex.getUIntVal();
2197 Constant *Val0, *Val1;
2198 Lex.Lex();
2199 if (ParseCmpPredicate(PredVal, Opc) ||
2200 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2201 ParseGlobalTypeAndValue(Val0) ||
2202 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2203 ParseGlobalTypeAndValue(Val1) ||
2204 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2205 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002206
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 if (Val0->getType() != Val1->getType())
2208 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002209
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002211
Chris Lattnerdf986172009-01-02 07:01:27 +00002212 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002213 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002214 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002215 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002216 } else {
2217 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002218 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002219 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002221 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 }
2223 ID.Kind = ValID::t_Constant;
2224 return false;
2225 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002226
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 // Binary Operators.
2228 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002229 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002231 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002232 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002233 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 case lltok::kw_udiv:
2235 case lltok::kw_sdiv:
2236 case lltok::kw_fdiv:
2237 case lltok::kw_urem:
2238 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002239 case lltok::kw_frem:
2240 case lltok::kw_shl:
2241 case lltok::kw_lshr:
2242 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002243 bool NUW = false;
2244 bool NSW = false;
2245 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002246 unsigned Opc = Lex.getUIntVal();
2247 Constant *Val0, *Val1;
2248 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002249 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002250 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2251 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002252 if (EatIfPresent(lltok::kw_nuw))
2253 NUW = true;
2254 if (EatIfPresent(lltok::kw_nsw)) {
2255 NSW = true;
2256 if (EatIfPresent(lltok::kw_nuw))
2257 NUW = true;
2258 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002259 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2260 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002261 if (EatIfPresent(lltok::kw_exact))
2262 Exact = true;
2263 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2265 ParseGlobalTypeAndValue(Val0) ||
2266 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2267 ParseGlobalTypeAndValue(Val1) ||
2268 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2269 return true;
2270 if (Val0->getType() != Val1->getType())
2271 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002272 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002273 if (NUW)
2274 return Error(ModifierLoc, "nuw only applies to integer operations");
2275 if (NSW)
2276 return Error(ModifierLoc, "nsw only applies to integer operations");
2277 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002278 // Check that the type is valid for the operator.
2279 switch (Opc) {
2280 case Instruction::Add:
2281 case Instruction::Sub:
2282 case Instruction::Mul:
2283 case Instruction::UDiv:
2284 case Instruction::SDiv:
2285 case Instruction::URem:
2286 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002287 case Instruction::Shl:
2288 case Instruction::AShr:
2289 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002290 if (!Val0->getType()->isIntOrIntVectorTy())
2291 return Error(ID.Loc, "constexpr requires integer operands");
2292 break;
2293 case Instruction::FAdd:
2294 case Instruction::FSub:
2295 case Instruction::FMul:
2296 case Instruction::FDiv:
2297 case Instruction::FRem:
2298 if (!Val0->getType()->isFPOrFPVectorTy())
2299 return Error(ID.Loc, "constexpr requires fp operands");
2300 break;
2301 default: llvm_unreachable("Unknown binary operator!");
2302 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002303 unsigned Flags = 0;
2304 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2305 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002306 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002307 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002308 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 ID.Kind = ValID::t_Constant;
2310 return false;
2311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002312
Chris Lattnerdf986172009-01-02 07:01:27 +00002313 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 case lltok::kw_and:
2315 case lltok::kw_or:
2316 case lltok::kw_xor: {
2317 unsigned Opc = Lex.getUIntVal();
2318 Constant *Val0, *Val1;
2319 Lex.Lex();
2320 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2321 ParseGlobalTypeAndValue(Val0) ||
2322 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2323 ParseGlobalTypeAndValue(Val1) ||
2324 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2325 return true;
2326 if (Val0->getType() != Val1->getType())
2327 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002328 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002329 return Error(ID.Loc,
2330 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002331 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002332 ID.Kind = ValID::t_Constant;
2333 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002334 }
2335
Chris Lattnerdf986172009-01-02 07:01:27 +00002336 case lltok::kw_getelementptr:
2337 case lltok::kw_shufflevector:
2338 case lltok::kw_insertelement:
2339 case lltok::kw_extractelement:
2340 case lltok::kw_select: {
2341 unsigned Opc = Lex.getUIntVal();
2342 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002343 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002345 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002346 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002347 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2348 ParseGlobalValueVector(Elts) ||
2349 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2350 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002351
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002353 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002354 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002355
Chris Lattnerdf986172009-01-02 07:01:27 +00002356 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002357 (Value**)(Elts.data() + 1),
2358 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002359 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002360 ID.ConstantVal = InBounds ?
2361 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2362 Elts.data() + 1,
2363 Elts.size() - 1) :
2364 ConstantExpr::getGetElementPtr(Elts[0],
2365 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 } else if (Opc == Instruction::Select) {
2367 if (Elts.size() != 3)
2368 return Error(ID.Loc, "expected three operands to select");
2369 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2370 Elts[2]))
2371 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002372 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 } else if (Opc == Instruction::ShuffleVector) {
2374 if (Elts.size() != 3)
2375 return Error(ID.Loc, "expected three operands to shufflevector");
2376 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2377 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002378 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002379 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002380 } else if (Opc == Instruction::ExtractElement) {
2381 if (Elts.size() != 2)
2382 return Error(ID.Loc, "expected two operands to extractelement");
2383 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2384 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002385 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 } else {
2387 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2388 if (Elts.size() != 3)
2389 return Error(ID.Loc, "expected three operands to insertelement");
2390 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2391 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002392 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002393 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002395
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 ID.Kind = ValID::t_Constant;
2397 return false;
2398 }
2399 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002400
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 Lex.Lex();
2402 return false;
2403}
2404
2405/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002406bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2407 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002408 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002409 Value *V = NULL;
2410 bool Parsed = ParseValID(ID) ||
2411 ConvertValIDToValue(Ty, ID, V, NULL);
2412 if (V && !(C = dyn_cast<Constant>(V)))
2413 return Error(ID.Loc, "global values must be constants");
2414 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002415}
2416
Victor Hernandez92f238d2010-01-11 22:31:58 +00002417bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2418 PATypeHolder Type(Type::getVoidTy(Context));
2419 return ParseType(Type) ||
2420 ParseGlobalValue(Type, V);
2421}
2422
2423/// ParseGlobalValueVector
2424/// ::= /*empty*/
2425/// ::= TypeAndValue (',' TypeAndValue)*
2426bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2427 // Empty list.
2428 if (Lex.getKind() == lltok::rbrace ||
2429 Lex.getKind() == lltok::rsquare ||
2430 Lex.getKind() == lltok::greater ||
2431 Lex.getKind() == lltok::rparen)
2432 return false;
2433
2434 Constant *C;
2435 if (ParseGlobalTypeAndValue(C)) return true;
2436 Elts.push_back(C);
2437
2438 while (EatIfPresent(lltok::comma)) {
2439 if (ParseGlobalTypeAndValue(C)) return true;
2440 Elts.push_back(C);
2441 }
2442
2443 return false;
2444}
2445
Dan Gohman309b3af2010-08-24 02:24:03 +00002446bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2447 assert(Lex.getKind() == lltok::lbrace);
2448 Lex.Lex();
2449
2450 SmallVector<Value*, 16> Elts;
2451 if (ParseMDNodeVector(Elts, PFS) ||
2452 ParseToken(lltok::rbrace, "expected end of metadata node"))
2453 return true;
2454
Jay Foadec9186b2011-04-21 19:59:31 +00002455 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002456 ID.Kind = ValID::t_MDNode;
2457 return false;
2458}
2459
Dan Gohman83448032010-07-14 18:26:50 +00002460/// ParseMetadataValue
2461/// ::= !42
2462/// ::= !{...}
2463/// ::= !"string"
2464bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2465 assert(Lex.getKind() == lltok::exclaim);
2466 Lex.Lex();
2467
2468 // MDNode:
2469 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002470 if (Lex.getKind() == lltok::lbrace)
2471 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002472
2473 // Standalone metadata reference
2474 // !42
2475 if (Lex.getKind() == lltok::APSInt) {
2476 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2477 ID.Kind = ValID::t_MDNode;
2478 return false;
2479 }
2480
2481 // MDString:
2482 // ::= '!' STRINGCONSTANT
2483 if (ParseMDString(ID.MDStringVal)) return true;
2484 ID.Kind = ValID::t_MDString;
2485 return false;
2486}
2487
Victor Hernandez92f238d2010-01-11 22:31:58 +00002488
2489//===----------------------------------------------------------------------===//
2490// Function Parsing.
2491//===----------------------------------------------------------------------===//
2492
2493bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2494 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002495 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002496 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002497
Chris Lattnerdf986172009-01-02 07:01:27 +00002498 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002499 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002500 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002501 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2502 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2503 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002504 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002505 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2506 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2507 return (V == 0);
2508 case ValID::t_InlineAsm: {
2509 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2510 const FunctionType *FTy =
2511 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2512 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2513 return Error(ID.Loc, "invalid type for inline asm constraint string");
2514 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2515 return false;
2516 }
2517 case ValID::t_MDNode:
2518 if (!Ty->isMetadataTy())
2519 return Error(ID.Loc, "metadata value must have metadata type");
2520 V = ID.MDNodeVal;
2521 return false;
2522 case ValID::t_MDString:
2523 if (!Ty->isMetadataTy())
2524 return Error(ID.Loc, "metadata value must have metadata type");
2525 V = ID.MDStringVal;
2526 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002527 case ValID::t_GlobalName:
2528 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2529 return V == 0;
2530 case ValID::t_GlobalID:
2531 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2532 return V == 0;
2533 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002534 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002536 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002537 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002538 return false;
2539 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002540 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2542 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002543
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 // The lexer has no type info, so builds all float and double FP constants
2545 // as double. Fix this here. Long double does not need this.
2546 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002547 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 bool Ignored;
2549 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2550 &Ignored);
2551 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002552 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002553
Chris Lattner959873d2009-01-05 18:24:23 +00002554 if (V->getType() != Ty)
2555 return Error(ID.Loc, "floating point constant does not have type '" +
2556 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002557
Chris Lattnerdf986172009-01-02 07:01:27 +00002558 return false;
2559 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002560 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002561 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002562 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002563 return false;
2564 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002565 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002566 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002567 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002568 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002569 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002571 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002572 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002573 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002574 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002575 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002577 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002578 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002579 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002580 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 return false;
2582 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002583 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002584 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002585
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 V = ID.ConstantVal;
2587 return false;
2588 }
2589}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002590
Chris Lattnerdf986172009-01-02 07:01:27 +00002591bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2592 V = 0;
2593 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002594 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002595 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002596}
2597
2598bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002599 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002600 return ParseType(T) ||
2601 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002602}
2603
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002604bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2605 PerFunctionState &PFS) {
2606 Value *V;
2607 Loc = Lex.getLoc();
2608 if (ParseTypeAndValue(V, PFS)) return true;
2609 if (!isa<BasicBlock>(V))
2610 return Error(Loc, "expected a basic block");
2611 BB = cast<BasicBlock>(V);
2612 return false;
2613}
2614
2615
Chris Lattnerdf986172009-01-02 07:01:27 +00002616/// FunctionHeader
2617/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002618/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002619/// OptionalAlign OptGC
2620bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2621 // Parse the linkage.
2622 LocTy LinkageLoc = Lex.getLoc();
2623 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002624
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002625 unsigned Visibility, RetAttrs;
2626 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002627 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002628 LocTy RetTypeLoc = Lex.getLoc();
2629 if (ParseOptionalLinkage(Linkage) ||
2630 ParseOptionalVisibility(Visibility) ||
2631 ParseOptionalCallingConv(CC) ||
2632 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002633 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 return true;
2635
2636 // Verify that the linkage is ok.
2637 switch ((GlobalValue::LinkageTypes)Linkage) {
2638 case GlobalValue::ExternalLinkage:
2639 break; // always ok.
2640 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002641 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 if (isDefine)
2643 return Error(LinkageLoc, "invalid linkage for function definition");
2644 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002645 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002646 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002647 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002648 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002649 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002650 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002651 case GlobalValue::LinkOnceAnyLinkage:
2652 case GlobalValue::LinkOnceODRLinkage:
2653 case GlobalValue::WeakAnyLinkage:
2654 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002655 case GlobalValue::DLLExportLinkage:
2656 if (!isDefine)
2657 return Error(LinkageLoc, "invalid linkage for function declaration");
2658 break;
2659 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002660 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002661 return Error(LinkageLoc, "invalid function linkage type");
2662 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002663
Chris Lattner99bb3152009-01-05 08:00:30 +00002664 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002665 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002666 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002667
Chris Lattnerdf986172009-01-02 07:01:27 +00002668 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002669
2670 std::string FunctionName;
2671 if (Lex.getKind() == lltok::GlobalVar) {
2672 FunctionName = Lex.getStrVal();
2673 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2674 unsigned NameID = Lex.getUIntVal();
2675
2676 if (NameID != NumberedVals.size())
2677 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002678 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002679 } else {
2680 return TokError("expected function name");
2681 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002682
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002683 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002684
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002685 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002686 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002687
Chris Lattnerdf986172009-01-02 07:01:27 +00002688 std::vector<ArgInfo> ArgList;
2689 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002693 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002694 bool UnnamedAddr;
2695 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002696
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002697 if (ParseArgumentList(ArgList, isVarArg, false) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002698 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2699 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002700 ParseOptionalAttrs(FuncAttrs, 2) ||
2701 (EatIfPresent(lltok::kw_section) &&
2702 ParseStringConstant(Section)) ||
2703 ParseOptionalAlignment(Alignment) ||
2704 (EatIfPresent(lltok::kw_gc) &&
2705 ParseStringConstant(GC)))
2706 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002707
2708 // If the alignment was parsed as an attribute, move to the alignment field.
2709 if (FuncAttrs & Attribute::Alignment) {
2710 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2711 FuncAttrs &= ~Attribute::Alignment;
2712 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002713
Chris Lattnerdf986172009-01-02 07:01:27 +00002714 // Okay, if we got here, the function is syntactically valid. Convert types
2715 // and do semantic checks.
2716 std::vector<const Type*> ParamTypeList;
2717 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002718
Chris Lattnerdf986172009-01-02 07:01:27 +00002719 if (RetAttrs != Attribute::None)
2720 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002721
Chris Lattnerdf986172009-01-02 07:01:27 +00002722 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2723 ParamTypeList.push_back(ArgList[i].Type);
2724 if (ArgList[i].Attrs != Attribute::None)
2725 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2726 }
2727
2728 if (FuncAttrs != Attribute::None)
2729 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2730
2731 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002732
Benjamin Kramerf0127052010-01-05 13:12:22 +00002733 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002734 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2735
Owen Andersonfba933c2009-07-01 23:57:11 +00002736 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002737 FunctionType::get(RetType, ParamTypeList, isVarArg);
2738 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002739
2740 Fn = 0;
2741 if (!FunctionName.empty()) {
2742 // If this was a definition of a forward reference, remove the definition
2743 // from the forward reference table and fill in the forward ref.
2744 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2745 ForwardRefVals.find(FunctionName);
2746 if (FRVI != ForwardRefVals.end()) {
2747 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002748 if (Fn->getType() != PFT)
2749 return Error(FRVI->second.second, "invalid forward reference to "
2750 "function '" + FunctionName + "' with wrong type!");
2751
Chris Lattnerdf986172009-01-02 07:01:27 +00002752 ForwardRefVals.erase(FRVI);
2753 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002754 // Reject redefinitions.
2755 return Error(NameLoc, "invalid redefinition of function '" +
2756 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002757 } else if (M->getNamedValue(FunctionName)) {
2758 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002759 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002760
Dan Gohman41905542009-08-29 23:37:49 +00002761 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 // If this is a definition of a forward referenced function, make sure the
2763 // types agree.
2764 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2765 = ForwardRefValIDs.find(NumberedVals.size());
2766 if (I != ForwardRefValIDs.end()) {
2767 Fn = cast<Function>(I->second.first);
2768 if (Fn->getType() != PFT)
2769 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002770 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002771 ForwardRefValIDs.erase(I);
2772 }
2773 }
2774
2775 if (Fn == 0)
2776 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2777 else // Move the forward-reference to the correct spot in the module.
2778 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2779
2780 if (FunctionName.empty())
2781 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782
Chris Lattnerdf986172009-01-02 07:01:27 +00002783 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2784 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2785 Fn->setCallingConv(CC);
2786 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002787 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002788 Fn->setAlignment(Alignment);
2789 Fn->setSection(Section);
2790 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerdf986172009-01-02 07:01:27 +00002792 // Add all of the arguments we parsed to the function.
2793 Function::arg_iterator ArgIt = Fn->arg_begin();
2794 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2795 // If the argument has a name, insert it into the argument symbol table.
2796 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Set the name, if it conflicted, it will be auto-renamed.
2799 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002800
Benjamin Krameraf812352010-10-16 11:28:23 +00002801 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002802 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2803 ArgList[i].Name + "'");
2804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002805
Chris Lattnerdf986172009-01-02 07:01:27 +00002806 return false;
2807}
2808
2809
2810/// ParseFunctionBody
2811/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002812///
2813bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002814 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 return TokError("expected '{' in function body");
2816 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002817
Chris Lattner09d9ef42009-10-28 03:39:23 +00002818 int FunctionNumber = -1;
2819 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2820
2821 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002822
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002823 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002824 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002825 return TokError("function body requires at least one basic block");
2826
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002827 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002829
Chris Lattnerdf986172009-01-02 07:01:27 +00002830 // Eat the }.
2831 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002832
Chris Lattnerdf986172009-01-02 07:01:27 +00002833 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002834 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002835}
2836
2837/// ParseBasicBlock
2838/// ::= LabelStr? Instruction*
2839bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2840 // If this basic block starts out with a name, remember it.
2841 std::string Name;
2842 LocTy NameLoc = Lex.getLoc();
2843 if (Lex.getKind() == lltok::LabelStr) {
2844 Name = Lex.getStrVal();
2845 Lex.Lex();
2846 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002847
Chris Lattnerdf986172009-01-02 07:01:27 +00002848 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2849 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002850
Chris Lattnerdf986172009-01-02 07:01:27 +00002851 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002852
Chris Lattnerdf986172009-01-02 07:01:27 +00002853 // Parse the instructions in this block until we get a terminator.
2854 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002855 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002856 do {
2857 // This instruction may have three possibilities for a name: a) none
2858 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2859 LocTy NameLoc = Lex.getLoc();
2860 int NameID = -1;
2861 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002862
Chris Lattnerdf986172009-01-02 07:01:27 +00002863 if (Lex.getKind() == lltok::LocalVarID) {
2864 NameID = Lex.getUIntVal();
2865 Lex.Lex();
2866 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2867 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002868 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 NameStr = Lex.getStrVal();
2870 Lex.Lex();
2871 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2872 return true;
2873 }
Devang Patelf633a062009-09-17 23:04:48 +00002874
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002875 switch (ParseInstruction(Inst, BB, PFS)) {
2876 default: assert(0 && "Unknown ParseInstruction result!");
2877 case InstError: return true;
2878 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002879 BB->getInstList().push_back(Inst);
2880
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002881 // With a normal result, we check to see if the instruction is followed by
2882 // a comma and metadata.
2883 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002884 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002885 return true;
2886 break;
2887 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002888 BB->getInstList().push_back(Inst);
2889
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002890 // If the instruction parser ate an extra comma at the end of it, it
2891 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002892 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002893 return true;
2894 break;
2895 }
Devang Patelf633a062009-09-17 23:04:48 +00002896
Chris Lattnerdf986172009-01-02 07:01:27 +00002897 // Set the name on the instruction.
2898 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2899 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002900
Chris Lattnerdf986172009-01-02 07:01:27 +00002901 return false;
2902}
2903
2904//===----------------------------------------------------------------------===//
2905// Instruction Parsing.
2906//===----------------------------------------------------------------------===//
2907
2908/// ParseInstruction - Parse one of the many different instructions.
2909///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002910int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2911 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002912 lltok::Kind Token = Lex.getKind();
2913 if (Token == lltok::Eof)
2914 return TokError("found end of file when expecting more instructions");
2915 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002916 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002917 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002918
Chris Lattnerdf986172009-01-02 07:01:27 +00002919 switch (Token) {
2920 default: return Error(Loc, "expected instruction opcode");
2921 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002922 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2923 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2925 case lltok::kw_br: return ParseBr(Inst, PFS);
2926 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002927 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2929 // Binary Operators.
2930 case lltok::kw_add:
2931 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002932 case lltok::kw_mul:
2933 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002934 bool NUW = EatIfPresent(lltok::kw_nuw);
2935 bool NSW = EatIfPresent(lltok::kw_nsw);
2936 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2937
2938 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2939
2940 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2941 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2942 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002943 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002944 case lltok::kw_fadd:
2945 case lltok::kw_fsub:
2946 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2947
Chris Lattner35bda892011-02-06 21:44:57 +00002948 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002949 case lltok::kw_udiv:
2950 case lltok::kw_lshr:
2951 case lltok::kw_ashr: {
2952 bool Exact = EatIfPresent(lltok::kw_exact);
2953
2954 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2955 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2956 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002957 }
2958
Chris Lattnerdf986172009-01-02 07:01:27 +00002959 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002960 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002961 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002962 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002963 case lltok::kw_and:
2964 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002965 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002966 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002967 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 // Casts.
2969 case lltok::kw_trunc:
2970 case lltok::kw_zext:
2971 case lltok::kw_sext:
2972 case lltok::kw_fptrunc:
2973 case lltok::kw_fpext:
2974 case lltok::kw_bitcast:
2975 case lltok::kw_uitofp:
2976 case lltok::kw_sitofp:
2977 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002978 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002980 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002981 // Other.
2982 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002983 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002984 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2985 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2986 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2987 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2988 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2989 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2990 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002991 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002992 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2993 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2994 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002995 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002997 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002998 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002999 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003000 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003001 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3002 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3003 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3004 }
3005}
3006
3007/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3008bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003009 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003010 switch (Lex.getKind()) {
3011 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3012 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3013 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3014 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3015 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3016 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3017 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3018 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3019 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3020 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3021 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3022 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3023 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3024 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3025 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3026 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3027 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3028 }
3029 } else {
3030 switch (Lex.getKind()) {
3031 default: TokError("expected icmp predicate (e.g. 'eq')");
3032 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3033 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3034 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3035 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3036 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3037 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3038 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3039 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3040 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3041 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3042 }
3043 }
3044 Lex.Lex();
3045 return false;
3046}
3047
3048//===----------------------------------------------------------------------===//
3049// Terminator Instructions.
3050//===----------------------------------------------------------------------===//
3051
3052/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003053/// ::= 'ret' void (',' !dbg, !1)*
3054/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003055bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003056 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003057 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003058 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003059
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003060 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003061 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 return false;
3063 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003064
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 Value *RV;
3066 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003067
Owen Anderson1d0be152009-08-13 21:58:54 +00003068 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003069 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003070}
3071
3072
3073/// ParseBr
3074/// ::= 'br' TypeAndValue
3075/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3076bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3077 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003078 Value *Op0;
3079 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003081
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3083 Inst = BranchInst::Create(BB);
3084 return false;
3085 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003086
Owen Anderson1d0be152009-08-13 21:58:54 +00003087 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003089
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003091 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003093 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003096 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 return false;
3098}
3099
3100/// ParseSwitch
3101/// Instruction
3102/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3103/// JumpTable
3104/// ::= (TypeAndValue ',' TypeAndValue)*
3105bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3106 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003107 Value *Cond;
3108 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3110 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003111 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3113 return true;
3114
Duncan Sands1df98592010-02-16 11:11:14 +00003115 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003116 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003117
Chris Lattnerdf986172009-01-02 07:01:27 +00003118 // Parse the jump table pairs.
3119 SmallPtrSet<Value*, 32> SeenCases;
3120 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3121 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003122 Value *Constant;
3123 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003124
Chris Lattnerdf986172009-01-02 07:01:27 +00003125 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3126 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003127 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003128 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003129
Chris Lattnerdf986172009-01-02 07:01:27 +00003130 if (!SeenCases.insert(Constant))
3131 return Error(CondLoc, "duplicate case value in switch");
3132 if (!isa<ConstantInt>(Constant))
3133 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003134
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003135 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003136 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003137
Chris Lattnerdf986172009-01-02 07:01:27 +00003138 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003139
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003140 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003141 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3142 SI->addCase(Table[i].first, Table[i].second);
3143 Inst = SI;
3144 return false;
3145}
3146
Chris Lattnerab21db72009-10-28 00:19:10 +00003147/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003148/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003149/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3150bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003151 LocTy AddrLoc;
3152 Value *Address;
3153 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003154 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3155 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003156 return true;
3157
Duncan Sands1df98592010-02-16 11:11:14 +00003158 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003159 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003160
3161 // Parse the destination list.
3162 SmallVector<BasicBlock*, 16> DestList;
3163
3164 if (Lex.getKind() != lltok::rsquare) {
3165 BasicBlock *DestBB;
3166 if (ParseTypeAndBasicBlock(DestBB, PFS))
3167 return true;
3168 DestList.push_back(DestBB);
3169
3170 while (EatIfPresent(lltok::comma)) {
3171 if (ParseTypeAndBasicBlock(DestBB, PFS))
3172 return true;
3173 DestList.push_back(DestBB);
3174 }
3175 }
3176
3177 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3178 return true;
3179
Chris Lattnerab21db72009-10-28 00:19:10 +00003180 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003181 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3182 IBI->addDestination(DestList[i]);
3183 Inst = IBI;
3184 return false;
3185}
3186
3187
Chris Lattnerdf986172009-01-02 07:01:27 +00003188/// ParseInvoke
3189/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3190/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3191bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3192 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003193 unsigned RetAttrs, FnAttrs;
3194 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003195 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 LocTy RetTypeLoc;
3197 ValID CalleeID;
3198 SmallVector<ParamInfo, 16> ArgList;
3199
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003200 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 if (ParseOptionalCallingConv(CC) ||
3202 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003203 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 ParseValID(CalleeID) ||
3205 ParseParameterList(ArgList, PFS) ||
3206 ParseOptionalAttrs(FnAttrs, 2) ||
3207 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003208 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003209 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003212
Chris Lattnerdf986172009-01-02 07:01:27 +00003213 // If RetType is a non-function pointer type, then this is the short syntax
3214 // for the call, which means that RetType is just the return type. Infer the
3215 // rest of the function argument types from the arguments that are present.
3216 const PointerType *PFTy = 0;
3217 const FunctionType *Ty = 0;
3218 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3219 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3220 // Pull out the types of all of the arguments...
3221 std::vector<const Type*> ParamTypes;
3222 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3223 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003224
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 if (!FunctionType::isValidReturnType(RetType))
3226 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003227
Owen Andersondebcb012009-07-29 22:17:13 +00003228 Ty = FunctionType::get(RetType, ParamTypes, false);
3229 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003230 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 // Look up the callee.
3233 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003234 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003235
Chris Lattnerdf986172009-01-02 07:01:27 +00003236 // Set up the Attributes for the function.
3237 SmallVector<AttributeWithIndex, 8> Attrs;
3238 if (RetAttrs != Attribute::None)
3239 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003240
Chris Lattnerdf986172009-01-02 07:01:27 +00003241 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003242
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 // Loop through FunctionType's arguments and ensure they are specified
3244 // correctly. Also, gather any parameter attributes.
3245 FunctionType::param_iterator I = Ty->param_begin();
3246 FunctionType::param_iterator E = Ty->param_end();
3247 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3248 const Type *ExpectedTy = 0;
3249 if (I != E) {
3250 ExpectedTy = *I++;
3251 } else if (!Ty->isVarArg()) {
3252 return Error(ArgList[i].Loc, "too many arguments specified");
3253 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003254
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3256 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3257 ExpectedTy->getDescription() + "'");
3258 Args.push_back(ArgList[i].V);
3259 if (ArgList[i].Attrs != Attribute::None)
3260 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3261 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003262
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 if (I != E)
3264 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003265
Chris Lattnerdf986172009-01-02 07:01:27 +00003266 if (FnAttrs != Attribute::None)
3267 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003268
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 // Finish off the Attributes and check them
3270 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003271
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003272 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 Args.begin(), Args.end());
3274 II->setCallingConv(CC);
3275 II->setAttributes(PAL);
3276 Inst = II;
3277 return false;
3278}
3279
3280
3281
3282//===----------------------------------------------------------------------===//
3283// Binary Operators.
3284//===----------------------------------------------------------------------===//
3285
3286/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003287/// ::= ArithmeticOps TypeAndValue ',' Value
3288///
3289/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3290/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003291bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003292 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003293 LocTy Loc; Value *LHS, *RHS;
3294 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3295 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3296 ParseValue(LHS->getType(), RHS, PFS))
3297 return true;
3298
Chris Lattnere914b592009-01-05 08:24:46 +00003299 bool Valid;
3300 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003301 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003302 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003303 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3304 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003305 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003306 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3307 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003308 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003309
Chris Lattnere914b592009-01-05 08:24:46 +00003310 if (!Valid)
3311 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003312
Chris Lattnerdf986172009-01-02 07:01:27 +00003313 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3314 return false;
3315}
3316
3317/// ParseLogical
3318/// ::= ArithmeticOps TypeAndValue ',' Value {
3319bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3320 unsigned Opc) {
3321 LocTy Loc; Value *LHS, *RHS;
3322 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3323 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3324 ParseValue(LHS->getType(), RHS, PFS))
3325 return true;
3326
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003327 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003328 return Error(Loc,"instruction requires integer or integer vector operands");
3329
3330 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3331 return false;
3332}
3333
3334
3335/// ParseCompare
3336/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3337/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003338bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3339 unsigned Opc) {
3340 // Parse the integer/fp comparison predicate.
3341 LocTy Loc;
3342 unsigned Pred;
3343 Value *LHS, *RHS;
3344 if (ParseCmpPredicate(Pred, Opc) ||
3345 ParseTypeAndValue(LHS, Loc, PFS) ||
3346 ParseToken(lltok::comma, "expected ',' after compare value") ||
3347 ParseValue(LHS->getType(), RHS, PFS))
3348 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003349
Chris Lattnerdf986172009-01-02 07:01:27 +00003350 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003351 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003353 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003354 } else {
3355 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003356 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003357 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003358 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003359 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 }
3361 return false;
3362}
3363
3364//===----------------------------------------------------------------------===//
3365// Other Instructions.
3366//===----------------------------------------------------------------------===//
3367
3368
3369/// ParseCast
3370/// ::= CastOpc TypeAndValue 'to' Type
3371bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3372 unsigned Opc) {
3373 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003374 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003375 if (ParseTypeAndValue(Op, Loc, PFS) ||
3376 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3377 ParseType(DestTy))
3378 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003379
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003380 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3381 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003382 return Error(Loc, "invalid cast opcode for cast from '" +
3383 Op->getType()->getDescription() + "' to '" +
3384 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003385 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3387 return false;
3388}
3389
3390/// ParseSelect
3391/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3392bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3393 LocTy Loc;
3394 Value *Op0, *Op1, *Op2;
3395 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3396 ParseToken(lltok::comma, "expected ',' after select condition") ||
3397 ParseTypeAndValue(Op1, PFS) ||
3398 ParseToken(lltok::comma, "expected ',' after select value") ||
3399 ParseTypeAndValue(Op2, PFS))
3400 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003401
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3403 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003404
Chris Lattnerdf986172009-01-02 07:01:27 +00003405 Inst = SelectInst::Create(Op0, Op1, Op2);
3406 return false;
3407}
3408
Chris Lattner0088a5c2009-01-05 08:18:44 +00003409/// ParseVA_Arg
3410/// ::= 'va_arg' TypeAndValue ',' Type
3411bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003413 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003414 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003415 if (ParseTypeAndValue(Op, PFS) ||
3416 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003417 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003418 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003419
Chris Lattner0088a5c2009-01-05 08:18:44 +00003420 if (!EltTy->isFirstClassType())
3421 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003422
3423 Inst = new VAArgInst(Op, EltTy);
3424 return false;
3425}
3426
3427/// ParseExtractElement
3428/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3429bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3430 LocTy Loc;
3431 Value *Op0, *Op1;
3432 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3433 ParseToken(lltok::comma, "expected ',' after extract value") ||
3434 ParseTypeAndValue(Op1, PFS))
3435 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003436
Chris Lattnerdf986172009-01-02 07:01:27 +00003437 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3438 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003439
Eric Christophera3500da2009-07-25 02:28:41 +00003440 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003441 return false;
3442}
3443
3444/// ParseInsertElement
3445/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3446bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3447 LocTy Loc;
3448 Value *Op0, *Op1, *Op2;
3449 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3450 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3451 ParseTypeAndValue(Op1, PFS) ||
3452 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3453 ParseTypeAndValue(Op2, PFS))
3454 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003455
Chris Lattnerdf986172009-01-02 07:01:27 +00003456 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003457 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003458
Chris Lattnerdf986172009-01-02 07:01:27 +00003459 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3460 return false;
3461}
3462
3463/// ParseShuffleVector
3464/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3465bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3466 LocTy Loc;
3467 Value *Op0, *Op1, *Op2;
3468 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3469 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3470 ParseTypeAndValue(Op1, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3472 ParseTypeAndValue(Op2, PFS))
3473 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003474
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3476 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003477
Chris Lattnerdf986172009-01-02 07:01:27 +00003478 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3479 return false;
3480}
3481
3482/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003483/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003484int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003485 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003486 Value *Op0, *Op1;
3487 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003488
Chris Lattnerdf986172009-01-02 07:01:27 +00003489 if (ParseType(Ty) ||
3490 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3491 ParseValue(Ty, Op0, PFS) ||
3492 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003493 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003494 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3495 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003496
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003497 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003498 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3499 while (1) {
3500 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003501
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003502 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 break;
3504
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003505 if (Lex.getKind() == lltok::MetadataVar) {
3506 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003507 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003508 }
Devang Patela43d46f2009-10-16 18:45:49 +00003509
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003510 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 ParseValue(Ty, Op0, PFS) ||
3512 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003513 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003514 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3515 return true;
3516 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003517
Chris Lattnerdf986172009-01-02 07:01:27 +00003518 if (!Ty->isFirstClassType())
3519 return Error(TypeLoc, "phi node must have first class type");
3520
Jay Foad3ecfc862011-03-30 11:28:46 +00003521 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3523 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3524 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003525 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003526}
3527
3528/// ParseCall
3529/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3530/// ParameterList OptionalAttrs
3531bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3532 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003533 unsigned RetAttrs, FnAttrs;
3534 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003535 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003536 LocTy RetTypeLoc;
3537 ValID CalleeID;
3538 SmallVector<ParamInfo, 16> ArgList;
3539 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003540
Chris Lattnerdf986172009-01-02 07:01:27 +00003541 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3542 ParseOptionalCallingConv(CC) ||
3543 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003544 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 ParseValID(CalleeID) ||
3546 ParseParameterList(ArgList, PFS) ||
3547 ParseOptionalAttrs(FnAttrs, 2))
3548 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003549
Chris Lattnerdf986172009-01-02 07:01:27 +00003550 // If RetType is a non-function pointer type, then this is the short syntax
3551 // for the call, which means that RetType is just the return type. Infer the
3552 // rest of the function argument types from the arguments that are present.
3553 const PointerType *PFTy = 0;
3554 const FunctionType *Ty = 0;
3555 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3556 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3557 // Pull out the types of all of the arguments...
3558 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003559 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3560 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003561
Chris Lattnerdf986172009-01-02 07:01:27 +00003562 if (!FunctionType::isValidReturnType(RetType))
3563 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003564
Owen Andersondebcb012009-07-29 22:17:13 +00003565 Ty = FunctionType::get(RetType, ParamTypes, false);
3566 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003568
Chris Lattnerdf986172009-01-02 07:01:27 +00003569 // Look up the callee.
3570 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003571 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003572
Chris Lattnerdf986172009-01-02 07:01:27 +00003573 // Set up the Attributes for the function.
3574 SmallVector<AttributeWithIndex, 8> Attrs;
3575 if (RetAttrs != Attribute::None)
3576 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003577
Chris Lattnerdf986172009-01-02 07:01:27 +00003578 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 // Loop through FunctionType's arguments and ensure they are specified
3581 // correctly. Also, gather any parameter attributes.
3582 FunctionType::param_iterator I = Ty->param_begin();
3583 FunctionType::param_iterator E = Ty->param_end();
3584 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3585 const Type *ExpectedTy = 0;
3586 if (I != E) {
3587 ExpectedTy = *I++;
3588 } else if (!Ty->isVarArg()) {
3589 return Error(ArgList[i].Loc, "too many arguments specified");
3590 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003591
Chris Lattnerdf986172009-01-02 07:01:27 +00003592 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3593 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3594 ExpectedTy->getDescription() + "'");
3595 Args.push_back(ArgList[i].V);
3596 if (ArgList[i].Attrs != Attribute::None)
3597 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3598 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003599
Chris Lattnerdf986172009-01-02 07:01:27 +00003600 if (I != E)
3601 return Error(CallLoc, "not enough parameters specified for call");
3602
3603 if (FnAttrs != Attribute::None)
3604 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3605
3606 // Finish off the Attributes and check them
3607 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003608
Chris Lattnerdf986172009-01-02 07:01:27 +00003609 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3610 CI->setTailCall(isTail);
3611 CI->setCallingConv(CC);
3612 CI->setAttributes(PAL);
3613 Inst = CI;
3614 return false;
3615}
3616
3617//===----------------------------------------------------------------------===//
3618// Memory Instructions.
3619//===----------------------------------------------------------------------===//
3620
3621/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003622/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003623int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003624 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003625 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003626 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003628 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003629
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003630 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003631 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003632 if (Lex.getKind() == lltok::kw_align) {
3633 if (ParseOptionalAlignment(Alignment)) return true;
3634 } else if (Lex.getKind() == lltok::MetadataVar) {
3635 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003636 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003637 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3638 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3639 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 }
3641 }
3642
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003643 if (Size && !Size->getType()->isIntegerTy())
3644 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003645
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003646 Inst = new AllocaInst(Ty, Size, Alignment);
3647 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003648}
3649
3650/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003651/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003652int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3653 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003654 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003655 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003656 bool AteExtraComma = false;
3657 if (ParseTypeAndValue(Val, Loc, PFS) ||
3658 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3659 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003660
Duncan Sands1df98592010-02-16 11:11:14 +00003661 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003662 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3663 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003664
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003666 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003667}
3668
3669/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003670/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003671int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3672 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003673 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003674 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003675 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003676 if (ParseTypeAndValue(Val, Loc, PFS) ||
3677 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003678 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3679 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003680 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003681
Duncan Sands1df98592010-02-16 11:11:14 +00003682 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003683 return Error(PtrLoc, "store operand must be a pointer");
3684 if (!Val->getType()->isFirstClassType())
3685 return Error(Loc, "store operand must be a first class value");
3686 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3687 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003688
Chris Lattnerdf986172009-01-02 07:01:27 +00003689 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003690 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003691}
3692
Chris Lattnerdf986172009-01-02 07:01:27 +00003693/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003694/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003695int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003696 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003697
Dan Gohmandcb40a32009-07-29 15:58:36 +00003698 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003699
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003700 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003701
Duncan Sands1df98592010-02-16 11:11:14 +00003702 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003703 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003704
Chris Lattnerdf986172009-01-02 07:01:27 +00003705 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003706 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003707 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003708 if (Lex.getKind() == lltok::MetadataVar) {
3709 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003710 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003711 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003712 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003713 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003714 return Error(EltLoc, "getelementptr index must be an integer");
3715 Indices.push_back(Val);
3716 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003717
Chris Lattnerdf986172009-01-02 07:01:27 +00003718 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3719 Indices.begin(), Indices.end()))
3720 return Error(Loc, "invalid getelementptr indices");
3721 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003722 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003723 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003724 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003725}
3726
3727/// ParseExtractValue
3728/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003729int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003730 Value *Val; LocTy Loc;
3731 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003732 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003733 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003734 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003735 return true;
3736
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003737 if (!Val->getType()->isAggregateType())
3738 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003739
3740 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3741 Indices.end()))
3742 return Error(Loc, "invalid indices for extractvalue");
3743 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003744 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003745}
3746
3747/// ParseInsertValue
3748/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003749int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003750 Value *Val0, *Val1; LocTy Loc0, Loc1;
3751 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003752 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003753 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3754 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3755 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003756 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003757 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003758
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003759 if (!Val0->getType()->isAggregateType())
3760 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003761
Chris Lattnerdf986172009-01-02 07:01:27 +00003762 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3763 Indices.end()))
3764 return Error(Loc0, "invalid indices for insertvalue");
3765 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003766 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003767}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003768
3769//===----------------------------------------------------------------------===//
3770// Embedded metadata.
3771//===----------------------------------------------------------------------===//
3772
3773/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003774/// ::= Element (',' Element)*
3775/// Element
3776/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003777bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003778 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003779 // Check for an empty list.
3780 if (Lex.getKind() == lltok::rbrace)
3781 return false;
3782
Nick Lewycky21cc4462009-04-04 07:22:01 +00003783 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003784 // Null is a special case since it is typeless.
3785 if (EatIfPresent(lltok::kw_null)) {
3786 Elts.push_back(0);
3787 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003788 }
Chris Lattnera7352392009-12-30 04:42:57 +00003789
3790 Value *V = 0;
3791 PATypeHolder Ty(Type::getVoidTy(Context));
3792 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003793 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003794 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003795 return true;
3796
Nick Lewyckycb337992009-05-10 20:57:05 +00003797 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003798 } while (EatIfPresent(lltok::comma));
3799
3800 return false;
3801}