blob: 01b3877adb60c016204227553caf4186c1f99800 [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;
1562 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001563 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 // FIXME: Allow, but ignore attributes on function types!
1565 // FIXME: Remove in LLVM 3.0
1566 ParseOptionalAttrs(Attrs, 2))
1567 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001568
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 // Reject names on the arguments lists.
1570 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1571 if (!ArgList[i].Name.empty())
1572 return Error(ArgList[i].Loc, "argument name invalid in function type");
1573 if (!ArgList[i].Attrs != 0) {
1574 // Allow but ignore attributes on function types; this permits
1575 // auto-upgrade.
1576 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1577 }
1578 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 std::vector<const Type*> ArgListTy;
1581 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1582 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Owen Andersondebcb012009-07-29 22:17:13 +00001584 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001585 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001586 return false;
1587}
1588
1589/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1590/// TypeRec
1591/// ::= '{' '}'
1592/// ::= '{' TypeRec (',' TypeRec)* '}'
1593/// ::= '<' '{' '}' '>'
1594/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1595bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1596 assert(Lex.getKind() == lltok::lbrace);
1597 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001598
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001599 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001600 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 return false;
1602 }
1603
1604 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001605 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001606 if (ParseTypeRec(Result)) return true;
1607 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001608
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001609 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001610 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001611 if (!StructType::isValidElementType(Result))
1612 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001614 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001615 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001618 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001619 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001620 if (!StructType::isValidElementType(Result))
1621 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 ParamsList.push_back(Result);
1624 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001625
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001626 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1627 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattnerdf986172009-01-02 07:01:27 +00001629 std::vector<const Type*> ParamsListTy;
1630 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1631 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001632 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001633 return false;
1634}
1635
1636/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1637/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001639/// ::= '[' APSINTVAL 'x' Types ']'
1640/// ::= '<' APSINTVAL 'x' Types '>'
1641bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1642 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1643 Lex.getAPSIntVal().getBitWidth() > 64)
1644 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001645
Chris Lattnerdf986172009-01-02 07:01:27 +00001646 LocTy SizeLoc = Lex.getLoc();
1647 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001648 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001650 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1651 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001652
1653 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001654 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001655 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001657 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001658 return Error(TypeLoc, "array and vector element type cannot be void");
1659
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001660 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1661 "expected end of sequential type"))
1662 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001665 if (Size == 0)
1666 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001667 if ((unsigned)Size != Size)
1668 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001669 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001671 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001672 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001673 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001674 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001675 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001676 }
1677 return false;
1678}
1679
1680//===----------------------------------------------------------------------===//
1681// Function Semantic Analysis.
1682//===----------------------------------------------------------------------===//
1683
Chris Lattner09d9ef42009-10-28 03:39:23 +00001684LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1685 int functionNumber)
1686 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001687
1688 // Insert unnamed arguments into the NumberedVals list.
1689 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1690 AI != E; ++AI)
1691 if (!AI->hasName())
1692 NumberedVals.push_back(AI);
1693}
1694
1695LLParser::PerFunctionState::~PerFunctionState() {
1696 // If there were any forward referenced non-basicblock values, delete them.
1697 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1698 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1699 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001700 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001701 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 delete I->second.first;
1703 I->second.first = 0;
1704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1707 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1708 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001709 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001710 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 delete I->second.first;
1712 I->second.first = 0;
1713 }
1714}
1715
Chris Lattner09d9ef42009-10-28 03:39:23 +00001716bool LLParser::PerFunctionState::FinishFunction() {
1717 // Check to see if someone took the address of labels in this block.
1718 if (!P.ForwardRefBlockAddresses.empty()) {
1719 ValID FunctionID;
1720 if (!F.getName().empty()) {
1721 FunctionID.Kind = ValID::t_GlobalName;
1722 FunctionID.StrVal = F.getName();
1723 } else {
1724 FunctionID.Kind = ValID::t_GlobalID;
1725 FunctionID.UIntVal = FunctionNumber;
1726 }
1727
1728 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1729 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1730 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1731 // Resolve all these references.
1732 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1733 return true;
1734
1735 P.ForwardRefBlockAddresses.erase(FRBAI);
1736 }
1737 }
1738
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 if (!ForwardRefVals.empty())
1740 return P.Error(ForwardRefVals.begin()->second.second,
1741 "use of undefined value '%" + ForwardRefVals.begin()->first +
1742 "'");
1743 if (!ForwardRefValIDs.empty())
1744 return P.Error(ForwardRefValIDs.begin()->second.second,
1745 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001746 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 return false;
1748}
1749
1750
1751/// GetVal - Get a value with the specified name or ID, creating a
1752/// forward reference record if needed. This can return null if the value
1753/// exists but does not have the right type.
1754Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1755 const Type *Ty, LocTy Loc) {
1756 // Look this name up in the normal function symbol table.
1757 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001758
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 // If this is a forward reference for the value, see if we already created a
1760 // forward ref record.
1761 if (Val == 0) {
1762 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1763 I = ForwardRefVals.find(Name);
1764 if (I != ForwardRefVals.end())
1765 Val = I->second.first;
1766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001767
Chris Lattnerdf986172009-01-02 07:01:27 +00001768 // If we have the value in the symbol table or fwd-ref table, return it.
1769 if (Val) {
1770 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001771 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 P.Error(Loc, "'%" + Name + "' is not a basic block");
1773 else
1774 P.Error(Loc, "'%" + Name + "' defined with type '" +
1775 Val->getType()->getDescription() + "'");
1776 return 0;
1777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001778
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001780 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 P.Error(Loc, "invalid use of a non-first-class type");
1782 return 0;
1783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 // Otherwise, create a new forward reference for this value and remember it.
1786 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001787 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001788 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 else
1790 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001791
Chris Lattnerdf986172009-01-02 07:01:27 +00001792 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1793 return FwdVal;
1794}
1795
1796Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1797 LocTy Loc) {
1798 // Look this name up in the normal function symbol table.
1799 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001800
Chris Lattnerdf986172009-01-02 07:01:27 +00001801 // If this is a forward reference for the value, see if we already created a
1802 // forward ref record.
1803 if (Val == 0) {
1804 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1805 I = ForwardRefValIDs.find(ID);
1806 if (I != ForwardRefValIDs.end())
1807 Val = I->second.first;
1808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001809
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 // If we have the value in the symbol table or fwd-ref table, return it.
1811 if (Val) {
1812 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001813 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001814 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001816 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 Val->getType()->getDescription() + "'");
1818 return 0;
1819 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001820
Duncan Sands47c51882010-02-16 14:50:09 +00001821 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 P.Error(Loc, "invalid use of a non-first-class type");
1823 return 0;
1824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 // Otherwise, create a new forward reference for this value and remember it.
1827 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001828 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001829 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 else
1831 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001832
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1834 return FwdVal;
1835}
1836
1837/// SetInstName - After an instruction is parsed and inserted into its
1838/// basic block, this installs its name.
1839bool LLParser::PerFunctionState::SetInstName(int NameID,
1840 const std::string &NameStr,
1841 LocTy NameLoc, Instruction *Inst) {
1842 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001843 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001844 if (NameID != -1 || !NameStr.empty())
1845 return P.Error(NameLoc, "instructions returning void cannot have a name");
1846 return false;
1847 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 // If this was a numbered instruction, verify that the instruction is the
1850 // expected value and resolve any forward references.
1851 if (NameStr.empty()) {
1852 // If neither a name nor an ID was specified, just use the next ID.
1853 if (NameID == -1)
1854 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001855
Chris Lattnerdf986172009-01-02 07:01:27 +00001856 if (unsigned(NameID) != NumberedVals.size())
1857 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001858 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1861 ForwardRefValIDs.find(NameID);
1862 if (FI != ForwardRefValIDs.end()) {
1863 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001864 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001865 FI->second.first->getType()->getDescription() + "'");
1866 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001867 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 ForwardRefValIDs.erase(FI);
1869 }
1870
1871 NumberedVals.push_back(Inst);
1872 return false;
1873 }
1874
1875 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1876 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1877 FI = ForwardRefVals.find(NameStr);
1878 if (FI != ForwardRefVals.end()) {
1879 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001880 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 FI->second.first->getType()->getDescription() + "'");
1882 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001883 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 ForwardRefVals.erase(FI);
1885 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 // Set the name on the instruction.
1888 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001889
Benjamin Krameraf812352010-10-16 11:28:23 +00001890 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001891 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 NameStr + "'");
1893 return false;
1894}
1895
1896/// GetBB - Get a basic block with the specified name or ID, creating a
1897/// forward reference record if needed.
1898BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1899 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001900 return cast_or_null<BasicBlock>(GetVal(Name,
1901 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001902}
1903
1904BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001905 return cast_or_null<BasicBlock>(GetVal(ID,
1906 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001907}
1908
1909/// DefineBB - Define the specified basic block, which is either named or
1910/// unnamed. If there is an error, this returns null otherwise it returns
1911/// the block being defined.
1912BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1913 LocTy Loc) {
1914 BasicBlock *BB;
1915 if (Name.empty())
1916 BB = GetBB(NumberedVals.size(), Loc);
1917 else
1918 BB = GetBB(Name, Loc);
1919 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 // Move the block to the end of the function. Forward ref'd blocks are
1922 // inserted wherever they happen to be referenced.
1923 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 // Remove the block from forward ref sets.
1926 if (Name.empty()) {
1927 ForwardRefValIDs.erase(NumberedVals.size());
1928 NumberedVals.push_back(BB);
1929 } else {
1930 // BB forward references are already in the function symbol table.
1931 ForwardRefVals.erase(Name);
1932 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001933
Chris Lattnerdf986172009-01-02 07:01:27 +00001934 return BB;
1935}
1936
1937//===----------------------------------------------------------------------===//
1938// Constants.
1939//===----------------------------------------------------------------------===//
1940
1941/// ParseValID - Parse an abstract value that doesn't necessarily have a
1942/// type implied. For example, if we parse "4" we don't know what integer type
1943/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001944/// sanity. PFS is used to convert function-local operands of metadata (since
1945/// metadata operands are not just parsed here but also converted to values).
1946/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001947bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001948 ID.Loc = Lex.getLoc();
1949 switch (Lex.getKind()) {
1950 default: return TokError("expected value token");
1951 case lltok::GlobalID: // @42
1952 ID.UIntVal = Lex.getUIntVal();
1953 ID.Kind = ValID::t_GlobalID;
1954 break;
1955 case lltok::GlobalVar: // @foo
1956 ID.StrVal = Lex.getStrVal();
1957 ID.Kind = ValID::t_GlobalName;
1958 break;
1959 case lltok::LocalVarID: // %42
1960 ID.UIntVal = Lex.getUIntVal();
1961 ID.Kind = ValID::t_LocalID;
1962 break;
1963 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 ID.StrVal = Lex.getStrVal();
1965 ID.Kind = ValID::t_LocalName;
1966 break;
Dan Gohman83448032010-07-14 18:26:50 +00001967 case lltok::exclaim: // !42, !{...}, or !"foo"
1968 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 ID.Kind = ValID::t_APSInt;
1972 break;
1973 case lltok::APFloat:
1974 ID.APFloatVal = Lex.getAPFloatVal();
1975 ID.Kind = ValID::t_APFloat;
1976 break;
1977 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001978 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 ID.Kind = ValID::t_Constant;
1980 break;
1981 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001982 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 ID.Kind = ValID::t_Constant;
1984 break;
1985 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1986 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1987 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 case lltok::lbrace: {
1990 // ValID ::= '{' ConstVector '}'
1991 Lex.Lex();
1992 SmallVector<Constant*, 16> Elts;
1993 if (ParseGlobalValueVector(Elts) ||
1994 ParseToken(lltok::rbrace, "expected end of struct constant"))
1995 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001996
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001997 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1998 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 ID.Kind = ValID::t_Constant;
2000 return false;
2001 }
2002 case lltok::less: {
2003 // ValID ::= '<' ConstVector '>' --> Vector.
2004 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2005 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002006 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002007
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 SmallVector<Constant*, 16> Elts;
2009 LocTy FirstEltLoc = Lex.getLoc();
2010 if (ParseGlobalValueVector(Elts) ||
2011 (isPackedStruct &&
2012 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2013 ParseToken(lltok::greater, "expected end of constant"))
2014 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002015
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002017 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002018 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 ID.Kind = ValID::t_Constant;
2020 return false;
2021 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 if (Elts.empty())
2024 return Error(ID.Loc, "constant vector must not be empty");
2025
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002026 if (!Elts[0]->getType()->isIntegerTy() &&
2027 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002028 return Error(FirstEltLoc,
2029 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002030
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 // Verify that all the vector elements have the same type.
2032 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2033 if (Elts[i]->getType() != Elts[0]->getType())
2034 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002035 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002037
Chris Lattner2ca5c862011-02-15 00:14:00 +00002038 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 ID.Kind = ValID::t_Constant;
2040 return false;
2041 }
2042 case lltok::lsquare: { // Array Constant
2043 Lex.Lex();
2044 SmallVector<Constant*, 16> Elts;
2045 LocTy FirstEltLoc = Lex.getLoc();
2046 if (ParseGlobalValueVector(Elts) ||
2047 ParseToken(lltok::rsquare, "expected end of array constant"))
2048 return true;
2049
2050 // Handle empty element.
2051 if (Elts.empty()) {
2052 // Use undef instead of an array because it's inconvenient to determine
2053 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002054 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 return false;
2056 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002057
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002059 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Owen Andersondebcb012009-07-29 22:17:13 +00002062 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002063
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002065 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 if (Elts[i]->getType() != Elts[0]->getType())
2067 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002068 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002069 " is not of type '" +Elts[0]->getType()->getDescription());
2070 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002071
Owen Anderson1fd70962009-07-28 18:32:17 +00002072 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 ID.Kind = ValID::t_Constant;
2074 return false;
2075 }
2076 case lltok::kw_c: // c "foo"
2077 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002078 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2080 ID.Kind = ValID::t_Constant;
2081 return false;
2082
2083 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002084 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2085 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 Lex.Lex();
2087 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002088 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002089 ParseStringConstant(ID.StrVal) ||
2090 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 ParseToken(lltok::StringConstant, "expected constraint string"))
2092 return true;
2093 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002094 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 ID.Kind = ValID::t_InlineAsm;
2096 return false;
2097 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098
Chris Lattner09d9ef42009-10-28 03:39:23 +00002099 case lltok::kw_blockaddress: {
2100 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2101 Lex.Lex();
2102
2103 ValID Fn, Label;
2104 LocTy FnLoc, LabelLoc;
2105
2106 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2107 ParseValID(Fn) ||
2108 ParseToken(lltok::comma, "expected comma in block address expression")||
2109 ParseValID(Label) ||
2110 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2111 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002112
Chris Lattner09d9ef42009-10-28 03:39:23 +00002113 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2114 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002115 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002116 return Error(Label.Loc, "expected basic block name in blockaddress");
2117
2118 // Make a global variable as a placeholder for this reference.
2119 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2120 false, GlobalValue::InternalLinkage,
2121 0, "");
2122 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2123 ID.ConstantVal = FwdRef;
2124 ID.Kind = ValID::t_Constant;
2125 return false;
2126 }
2127
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 case lltok::kw_trunc:
2129 case lltok::kw_zext:
2130 case lltok::kw_sext:
2131 case lltok::kw_fptrunc:
2132 case lltok::kw_fpext:
2133 case lltok::kw_bitcast:
2134 case lltok::kw_uitofp:
2135 case lltok::kw_sitofp:
2136 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002141 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 Constant *SrcVal;
2143 Lex.Lex();
2144 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2145 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002146 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 ParseType(DestTy) ||
2148 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2149 return true;
2150 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2151 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2152 SrcVal->getType()->getDescription() + "' to '" +
2153 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002154 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002155 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 ID.Kind = ValID::t_Constant;
2157 return false;
2158 }
2159 case lltok::kw_extractvalue: {
2160 Lex.Lex();
2161 Constant *Val;
2162 SmallVector<unsigned, 4> Indices;
2163 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2164 ParseGlobalTypeAndValue(Val) ||
2165 ParseIndexList(Indices) ||
2166 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2167 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002168
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002169 if (!Val->getType()->isAggregateType())
2170 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2172 Indices.end()))
2173 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002174 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002175 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 ID.Kind = ValID::t_Constant;
2177 return false;
2178 }
2179 case lltok::kw_insertvalue: {
2180 Lex.Lex();
2181 Constant *Val0, *Val1;
2182 SmallVector<unsigned, 4> Indices;
2183 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2184 ParseGlobalTypeAndValue(Val0) ||
2185 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2186 ParseGlobalTypeAndValue(Val1) ||
2187 ParseIndexList(Indices) ||
2188 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2189 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002190 if (!Val0->getType()->isAggregateType())
2191 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2193 Indices.end()))
2194 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002195 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002196 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 ID.Kind = ValID::t_Constant;
2198 return false;
2199 }
2200 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002201 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002202 unsigned PredVal, Opc = Lex.getUIntVal();
2203 Constant *Val0, *Val1;
2204 Lex.Lex();
2205 if (ParseCmpPredicate(PredVal, Opc) ||
2206 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2207 ParseGlobalTypeAndValue(Val0) ||
2208 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2209 ParseGlobalTypeAndValue(Val1) ||
2210 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2211 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002212
Chris Lattnerdf986172009-01-02 07:01:27 +00002213 if (Val0->getType() != Val1->getType())
2214 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002215
Chris Lattnerdf986172009-01-02 07:01:27 +00002216 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002219 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002221 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002222 } else {
2223 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002224 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002225 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002226 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002227 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 }
2229 ID.Kind = ValID::t_Constant;
2230 return false;
2231 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002232
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 // Binary Operators.
2234 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002235 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002237 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002238 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002239 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 case lltok::kw_udiv:
2241 case lltok::kw_sdiv:
2242 case lltok::kw_fdiv:
2243 case lltok::kw_urem:
2244 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002245 case lltok::kw_frem:
2246 case lltok::kw_shl:
2247 case lltok::kw_lshr:
2248 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002249 bool NUW = false;
2250 bool NSW = false;
2251 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 unsigned Opc = Lex.getUIntVal();
2253 Constant *Val0, *Val1;
2254 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002255 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002256 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2257 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002258 if (EatIfPresent(lltok::kw_nuw))
2259 NUW = true;
2260 if (EatIfPresent(lltok::kw_nsw)) {
2261 NSW = true;
2262 if (EatIfPresent(lltok::kw_nuw))
2263 NUW = true;
2264 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002265 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2266 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002267 if (EatIfPresent(lltok::kw_exact))
2268 Exact = true;
2269 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2271 ParseGlobalTypeAndValue(Val0) ||
2272 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2273 ParseGlobalTypeAndValue(Val1) ||
2274 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2275 return true;
2276 if (Val0->getType() != Val1->getType())
2277 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002278 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002279 if (NUW)
2280 return Error(ModifierLoc, "nuw only applies to integer operations");
2281 if (NSW)
2282 return Error(ModifierLoc, "nsw only applies to integer operations");
2283 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002284 // Check that the type is valid for the operator.
2285 switch (Opc) {
2286 case Instruction::Add:
2287 case Instruction::Sub:
2288 case Instruction::Mul:
2289 case Instruction::UDiv:
2290 case Instruction::SDiv:
2291 case Instruction::URem:
2292 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002293 case Instruction::Shl:
2294 case Instruction::AShr:
2295 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002296 if (!Val0->getType()->isIntOrIntVectorTy())
2297 return Error(ID.Loc, "constexpr requires integer operands");
2298 break;
2299 case Instruction::FAdd:
2300 case Instruction::FSub:
2301 case Instruction::FMul:
2302 case Instruction::FDiv:
2303 case Instruction::FRem:
2304 if (!Val0->getType()->isFPOrFPVectorTy())
2305 return Error(ID.Loc, "constexpr requires fp operands");
2306 break;
2307 default: llvm_unreachable("Unknown binary operator!");
2308 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002309 unsigned Flags = 0;
2310 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2311 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002312 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002313 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002314 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002315 ID.Kind = ValID::t_Constant;
2316 return false;
2317 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002318
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002320 case lltok::kw_and:
2321 case lltok::kw_or:
2322 case lltok::kw_xor: {
2323 unsigned Opc = Lex.getUIntVal();
2324 Constant *Val0, *Val1;
2325 Lex.Lex();
2326 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2327 ParseGlobalTypeAndValue(Val0) ||
2328 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2329 ParseGlobalTypeAndValue(Val1) ||
2330 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2331 return true;
2332 if (Val0->getType() != Val1->getType())
2333 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002334 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 return Error(ID.Loc,
2336 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002337 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002338 ID.Kind = ValID::t_Constant;
2339 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002340 }
2341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 case lltok::kw_getelementptr:
2343 case lltok::kw_shufflevector:
2344 case lltok::kw_insertelement:
2345 case lltok::kw_extractelement:
2346 case lltok::kw_select: {
2347 unsigned Opc = Lex.getUIntVal();
2348 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002349 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002351 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002352 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002353 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2354 ParseGlobalValueVector(Elts) ||
2355 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2356 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002357
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002359 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002360 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361
Chris Lattnerdf986172009-01-02 07:01:27 +00002362 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002363 (Value**)(Elts.data() + 1),
2364 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002366 ID.ConstantVal = InBounds ?
2367 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2368 Elts.data() + 1,
2369 Elts.size() - 1) :
2370 ConstantExpr::getGetElementPtr(Elts[0],
2371 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 } else if (Opc == Instruction::Select) {
2373 if (Elts.size() != 3)
2374 return Error(ID.Loc, "expected three operands to select");
2375 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2376 Elts[2]))
2377 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002378 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002379 } else if (Opc == Instruction::ShuffleVector) {
2380 if (Elts.size() != 3)
2381 return Error(ID.Loc, "expected three operands to shufflevector");
2382 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2383 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002384 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002385 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 } else if (Opc == Instruction::ExtractElement) {
2387 if (Elts.size() != 2)
2388 return Error(ID.Loc, "expected two operands to extractelement");
2389 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2390 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002391 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 } else {
2393 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2394 if (Elts.size() != 3)
2395 return Error(ID.Loc, "expected three operands to insertelement");
2396 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2397 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002398 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002399 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002401
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 ID.Kind = ValID::t_Constant;
2403 return false;
2404 }
2405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 Lex.Lex();
2408 return false;
2409}
2410
2411/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002412bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2413 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002415 Value *V = NULL;
2416 bool Parsed = ParseValID(ID) ||
2417 ConvertValIDToValue(Ty, ID, V, NULL);
2418 if (V && !(C = dyn_cast<Constant>(V)))
2419 return Error(ID.Loc, "global values must be constants");
2420 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002421}
2422
Victor Hernandez92f238d2010-01-11 22:31:58 +00002423bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2424 PATypeHolder Type(Type::getVoidTy(Context));
2425 return ParseType(Type) ||
2426 ParseGlobalValue(Type, V);
2427}
2428
2429/// ParseGlobalValueVector
2430/// ::= /*empty*/
2431/// ::= TypeAndValue (',' TypeAndValue)*
2432bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2433 // Empty list.
2434 if (Lex.getKind() == lltok::rbrace ||
2435 Lex.getKind() == lltok::rsquare ||
2436 Lex.getKind() == lltok::greater ||
2437 Lex.getKind() == lltok::rparen)
2438 return false;
2439
2440 Constant *C;
2441 if (ParseGlobalTypeAndValue(C)) return true;
2442 Elts.push_back(C);
2443
2444 while (EatIfPresent(lltok::comma)) {
2445 if (ParseGlobalTypeAndValue(C)) return true;
2446 Elts.push_back(C);
2447 }
2448
2449 return false;
2450}
2451
Dan Gohman309b3af2010-08-24 02:24:03 +00002452bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2453 assert(Lex.getKind() == lltok::lbrace);
2454 Lex.Lex();
2455
2456 SmallVector<Value*, 16> Elts;
2457 if (ParseMDNodeVector(Elts, PFS) ||
2458 ParseToken(lltok::rbrace, "expected end of metadata node"))
2459 return true;
2460
Jay Foadec9186b2011-04-21 19:59:31 +00002461 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002462 ID.Kind = ValID::t_MDNode;
2463 return false;
2464}
2465
Dan Gohman83448032010-07-14 18:26:50 +00002466/// ParseMetadataValue
2467/// ::= !42
2468/// ::= !{...}
2469/// ::= !"string"
2470bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2471 assert(Lex.getKind() == lltok::exclaim);
2472 Lex.Lex();
2473
2474 // MDNode:
2475 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002476 if (Lex.getKind() == lltok::lbrace)
2477 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002478
2479 // Standalone metadata reference
2480 // !42
2481 if (Lex.getKind() == lltok::APSInt) {
2482 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2483 ID.Kind = ValID::t_MDNode;
2484 return false;
2485 }
2486
2487 // MDString:
2488 // ::= '!' STRINGCONSTANT
2489 if (ParseMDString(ID.MDStringVal)) return true;
2490 ID.Kind = ValID::t_MDString;
2491 return false;
2492}
2493
Victor Hernandez92f238d2010-01-11 22:31:58 +00002494
2495//===----------------------------------------------------------------------===//
2496// Function Parsing.
2497//===----------------------------------------------------------------------===//
2498
2499bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2500 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002501 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002502 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002503
Chris Lattnerdf986172009-01-02 07:01:27 +00002504 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002505 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002506 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002507 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2508 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2509 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002511 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2512 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2513 return (V == 0);
2514 case ValID::t_InlineAsm: {
2515 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2516 const FunctionType *FTy =
2517 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2518 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2519 return Error(ID.Loc, "invalid type for inline asm constraint string");
2520 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2521 return false;
2522 }
2523 case ValID::t_MDNode:
2524 if (!Ty->isMetadataTy())
2525 return Error(ID.Loc, "metadata value must have metadata type");
2526 V = ID.MDNodeVal;
2527 return false;
2528 case ValID::t_MDString:
2529 if (!Ty->isMetadataTy())
2530 return Error(ID.Loc, "metadata value must have metadata type");
2531 V = ID.MDStringVal;
2532 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002533 case ValID::t_GlobalName:
2534 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2535 return V == 0;
2536 case ValID::t_GlobalID:
2537 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2538 return V == 0;
2539 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002540 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002542 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002543 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 return false;
2545 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002546 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2548 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002549
Chris Lattnerdf986172009-01-02 07:01:27 +00002550 // The lexer has no type info, so builds all float and double FP constants
2551 // as double. Fix this here. Long double does not need this.
2552 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002553 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 bool Ignored;
2555 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2556 &Ignored);
2557 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002558 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002559
Chris Lattner959873d2009-01-05 18:24:23 +00002560 if (V->getType() != Ty)
2561 return Error(ID.Loc, "floating point constant does not have type '" +
2562 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002563
Chris Lattnerdf986172009-01-02 07:01:27 +00002564 return false;
2565 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002566 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002567 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002568 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 return false;
2570 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002571 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002572 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002573 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002574 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002575 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002577 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002578 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002579 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002580 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002581 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002582 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002583 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002584 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002586 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 return false;
2588 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002589 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002591
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 V = ID.ConstantVal;
2593 return false;
2594 }
2595}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdf986172009-01-02 07:01:27 +00002597bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2598 V = 0;
2599 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002600 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002601 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002602}
2603
2604bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002605 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002606 return ParseType(T) ||
2607 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002608}
2609
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002610bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2611 PerFunctionState &PFS) {
2612 Value *V;
2613 Loc = Lex.getLoc();
2614 if (ParseTypeAndValue(V, PFS)) return true;
2615 if (!isa<BasicBlock>(V))
2616 return Error(Loc, "expected a basic block");
2617 BB = cast<BasicBlock>(V);
2618 return false;
2619}
2620
2621
Chris Lattnerdf986172009-01-02 07:01:27 +00002622/// FunctionHeader
2623/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002624/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002625/// OptionalAlign OptGC
2626bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2627 // Parse the linkage.
2628 LocTy LinkageLoc = Lex.getLoc();
2629 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002630
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002631 unsigned Visibility, RetAttrs;
2632 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002633 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 LocTy RetTypeLoc = Lex.getLoc();
2635 if (ParseOptionalLinkage(Linkage) ||
2636 ParseOptionalVisibility(Visibility) ||
2637 ParseOptionalCallingConv(CC) ||
2638 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002639 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 return true;
2641
2642 // Verify that the linkage is ok.
2643 switch ((GlobalValue::LinkageTypes)Linkage) {
2644 case GlobalValue::ExternalLinkage:
2645 break; // always ok.
2646 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002647 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 if (isDefine)
2649 return Error(LinkageLoc, "invalid linkage for function definition");
2650 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002651 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002652 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002653 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002654 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002655 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002656 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002657 case GlobalValue::LinkOnceAnyLinkage:
2658 case GlobalValue::LinkOnceODRLinkage:
2659 case GlobalValue::WeakAnyLinkage:
2660 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002661 case GlobalValue::DLLExportLinkage:
2662 if (!isDefine)
2663 return Error(LinkageLoc, "invalid linkage for function declaration");
2664 break;
2665 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002666 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002667 return Error(LinkageLoc, "invalid function linkage type");
2668 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002669
Chris Lattner99bb3152009-01-05 08:00:30 +00002670 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002671 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002672 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Chris Lattnerdf986172009-01-02 07:01:27 +00002674 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002675
2676 std::string FunctionName;
2677 if (Lex.getKind() == lltok::GlobalVar) {
2678 FunctionName = Lex.getStrVal();
2679 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2680 unsigned NameID = Lex.getUIntVal();
2681
2682 if (NameID != NumberedVals.size())
2683 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002684 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002685 } else {
2686 return TokError("expected function name");
2687 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002689 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002691 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002693
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 std::vector<ArgInfo> ArgList;
2695 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002697 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002699 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002700 bool UnnamedAddr;
2701 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002702
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002703 if (ParseArgumentList(ArgList, isVarArg, false) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002704 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2705 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002706 ParseOptionalAttrs(FuncAttrs, 2) ||
2707 (EatIfPresent(lltok::kw_section) &&
2708 ParseStringConstant(Section)) ||
2709 ParseOptionalAlignment(Alignment) ||
2710 (EatIfPresent(lltok::kw_gc) &&
2711 ParseStringConstant(GC)))
2712 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002713
2714 // If the alignment was parsed as an attribute, move to the alignment field.
2715 if (FuncAttrs & Attribute::Alignment) {
2716 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2717 FuncAttrs &= ~Attribute::Alignment;
2718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 // Okay, if we got here, the function is syntactically valid. Convert types
2721 // and do semantic checks.
2722 std::vector<const Type*> ParamTypeList;
2723 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 if (RetAttrs != Attribute::None)
2726 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2729 ParamTypeList.push_back(ArgList[i].Type);
2730 if (ArgList[i].Attrs != Attribute::None)
2731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2732 }
2733
2734 if (FuncAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2736
2737 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002738
Benjamin Kramerf0127052010-01-05 13:12:22 +00002739 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2741
Owen Andersonfba933c2009-07-01 23:57:11 +00002742 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002743 FunctionType::get(RetType, ParamTypeList, isVarArg);
2744 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002745
2746 Fn = 0;
2747 if (!FunctionName.empty()) {
2748 // If this was a definition of a forward reference, remove the definition
2749 // from the forward reference table and fill in the forward ref.
2750 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2751 ForwardRefVals.find(FunctionName);
2752 if (FRVI != ForwardRefVals.end()) {
2753 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002754 if (Fn->getType() != PFT)
2755 return Error(FRVI->second.second, "invalid forward reference to "
2756 "function '" + FunctionName + "' with wrong type!");
2757
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 ForwardRefVals.erase(FRVI);
2759 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002760 // Reject redefinitions.
2761 return Error(NameLoc, "invalid redefinition of function '" +
2762 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002763 } else if (M->getNamedValue(FunctionName)) {
2764 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Dan Gohman41905542009-08-29 23:37:49 +00002767 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002768 // If this is a definition of a forward referenced function, make sure the
2769 // types agree.
2770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2771 = ForwardRefValIDs.find(NumberedVals.size());
2772 if (I != ForwardRefValIDs.end()) {
2773 Fn = cast<Function>(I->second.first);
2774 if (Fn->getType() != PFT)
2775 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002776 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002777 ForwardRefValIDs.erase(I);
2778 }
2779 }
2780
2781 if (Fn == 0)
2782 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2783 else // Move the forward-reference to the correct spot in the module.
2784 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2785
2786 if (FunctionName.empty())
2787 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2790 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2791 Fn->setCallingConv(CC);
2792 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002793 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 Fn->setAlignment(Alignment);
2795 Fn->setSection(Section);
2796 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Add all of the arguments we parsed to the function.
2799 Function::arg_iterator ArgIt = Fn->arg_begin();
2800 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002801 // If we run out of arguments in the Function prototype, exit early.
2802 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2803 if (ArgIt == Fn->arg_end()) break;
2804
Chris Lattnerdf986172009-01-02 07:01:27 +00002805 // If the argument has a name, insert it into the argument symbol table.
2806 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002807
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 // Set the name, if it conflicted, it will be auto-renamed.
2809 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002810
Benjamin Krameraf812352010-10-16 11:28:23 +00002811 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2813 ArgList[i].Name + "'");
2814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 return false;
2817}
2818
2819
2820/// ParseFunctionBody
2821/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002822///
2823bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002824 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002825 return TokError("expected '{' in function body");
2826 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Chris Lattner09d9ef42009-10-28 03:39:23 +00002828 int FunctionNumber = -1;
2829 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2830
2831 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002832
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002833 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002834 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002835 return TokError("function body requires at least one basic block");
2836
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002837 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002838 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002839
Chris Lattnerdf986172009-01-02 07:01:27 +00002840 // Eat the }.
2841 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002842
Chris Lattnerdf986172009-01-02 07:01:27 +00002843 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002844 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002845}
2846
2847/// ParseBasicBlock
2848/// ::= LabelStr? Instruction*
2849bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2850 // If this basic block starts out with a name, remember it.
2851 std::string Name;
2852 LocTy NameLoc = Lex.getLoc();
2853 if (Lex.getKind() == lltok::LabelStr) {
2854 Name = Lex.getStrVal();
2855 Lex.Lex();
2856 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002857
Chris Lattnerdf986172009-01-02 07:01:27 +00002858 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2859 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002860
Chris Lattnerdf986172009-01-02 07:01:27 +00002861 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002862
Chris Lattnerdf986172009-01-02 07:01:27 +00002863 // Parse the instructions in this block until we get a terminator.
2864 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002865 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002866 do {
2867 // This instruction may have three possibilities for a name: a) none
2868 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2869 LocTy NameLoc = Lex.getLoc();
2870 int NameID = -1;
2871 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002872
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 if (Lex.getKind() == lltok::LocalVarID) {
2874 NameID = Lex.getUIntVal();
2875 Lex.Lex();
2876 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2877 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002878 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002879 NameStr = Lex.getStrVal();
2880 Lex.Lex();
2881 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2882 return true;
2883 }
Devang Patelf633a062009-09-17 23:04:48 +00002884
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002885 switch (ParseInstruction(Inst, BB, PFS)) {
2886 default: assert(0 && "Unknown ParseInstruction result!");
2887 case InstError: return true;
2888 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002889 BB->getInstList().push_back(Inst);
2890
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002891 // With a normal result, we check to see if the instruction is followed by
2892 // a comma and metadata.
2893 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002894 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002895 return true;
2896 break;
2897 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002898 BB->getInstList().push_back(Inst);
2899
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002900 // If the instruction parser ate an extra comma at the end of it, it
2901 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002902 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002903 return true;
2904 break;
2905 }
Devang Patelf633a062009-09-17 23:04:48 +00002906
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 // Set the name on the instruction.
2908 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2909 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002910
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 return false;
2912}
2913
2914//===----------------------------------------------------------------------===//
2915// Instruction Parsing.
2916//===----------------------------------------------------------------------===//
2917
2918/// ParseInstruction - Parse one of the many different instructions.
2919///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002920int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2921 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002922 lltok::Kind Token = Lex.getKind();
2923 if (Token == lltok::Eof)
2924 return TokError("found end of file when expecting more instructions");
2925 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002926 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002928
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 switch (Token) {
2930 default: return Error(Loc, "expected instruction opcode");
2931 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002932 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2933 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002934 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2935 case lltok::kw_br: return ParseBr(Inst, PFS);
2936 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002937 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2939 // Binary Operators.
2940 case lltok::kw_add:
2941 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002942 case lltok::kw_mul:
2943 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002944 bool NUW = EatIfPresent(lltok::kw_nuw);
2945 bool NSW = EatIfPresent(lltok::kw_nsw);
2946 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2947
2948 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2949
2950 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2951 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2952 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002953 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002954 case lltok::kw_fadd:
2955 case lltok::kw_fsub:
2956 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2957
Chris Lattner35bda892011-02-06 21:44:57 +00002958 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002959 case lltok::kw_udiv:
2960 case lltok::kw_lshr:
2961 case lltok::kw_ashr: {
2962 bool Exact = EatIfPresent(lltok::kw_exact);
2963
2964 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2965 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2966 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002967 }
2968
Chris Lattnerdf986172009-01-02 07:01:27 +00002969 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002970 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002971 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002972 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002973 case lltok::kw_and:
2974 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002975 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002976 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002977 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 // Casts.
2979 case lltok::kw_trunc:
2980 case lltok::kw_zext:
2981 case lltok::kw_sext:
2982 case lltok::kw_fptrunc:
2983 case lltok::kw_fpext:
2984 case lltok::kw_bitcast:
2985 case lltok::kw_uitofp:
2986 case lltok::kw_sitofp:
2987 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002988 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002989 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002990 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 // Other.
2992 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002993 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2995 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2996 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2997 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2998 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2999 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3000 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003001 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003002 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3003 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3004 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003005 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003006 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003007 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003008 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003009 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003010 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003011 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3012 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3013 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3014 }
3015}
3016
3017/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3018bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003019 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003020 switch (Lex.getKind()) {
3021 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3022 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3023 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3024 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3025 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3026 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3027 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3028 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3029 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3030 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3031 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3032 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3033 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3034 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3035 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3036 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3037 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3038 }
3039 } else {
3040 switch (Lex.getKind()) {
3041 default: TokError("expected icmp predicate (e.g. 'eq')");
3042 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3043 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3044 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3045 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3046 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3047 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3048 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3049 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3050 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3051 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3052 }
3053 }
3054 Lex.Lex();
3055 return false;
3056}
3057
3058//===----------------------------------------------------------------------===//
3059// Terminator Instructions.
3060//===----------------------------------------------------------------------===//
3061
3062/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003063/// ::= 'ret' void (',' !dbg, !1)*
3064/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003065bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003066 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003067 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003068 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003069
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003070 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003071 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 return false;
3073 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003074
Chris Lattnerdf986172009-01-02 07:01:27 +00003075 Value *RV;
3076 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003077
Owen Anderson1d0be152009-08-13 21:58:54 +00003078 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003079 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003080}
3081
3082
3083/// ParseBr
3084/// ::= 'br' TypeAndValue
3085/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3086bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3087 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003088 Value *Op0;
3089 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003091
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3093 Inst = BranchInst::Create(BB);
3094 return false;
3095 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003096
Owen Anderson1d0be152009-08-13 21:58:54 +00003097 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003099
Chris Lattnerdf986172009-01-02 07:01:27 +00003100 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003101 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003102 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003103 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003105
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003106 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 return false;
3108}
3109
3110/// ParseSwitch
3111/// Instruction
3112/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3113/// JumpTable
3114/// ::= (TypeAndValue ',' TypeAndValue)*
3115bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3116 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003117 Value *Cond;
3118 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003119 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3120 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003121 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003122 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3123 return true;
3124
Duncan Sands1df98592010-02-16 11:11:14 +00003125 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003126 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003127
Chris Lattnerdf986172009-01-02 07:01:27 +00003128 // Parse the jump table pairs.
3129 SmallPtrSet<Value*, 32> SeenCases;
3130 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3131 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003132 Value *Constant;
3133 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003134
Chris Lattnerdf986172009-01-02 07:01:27 +00003135 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3136 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003137 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003138 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003139
Chris Lattnerdf986172009-01-02 07:01:27 +00003140 if (!SeenCases.insert(Constant))
3141 return Error(CondLoc, "duplicate case value in switch");
3142 if (!isa<ConstantInt>(Constant))
3143 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003144
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003145 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003146 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003147
Chris Lattnerdf986172009-01-02 07:01:27 +00003148 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003149
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003150 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3152 SI->addCase(Table[i].first, Table[i].second);
3153 Inst = SI;
3154 return false;
3155}
3156
Chris Lattnerab21db72009-10-28 00:19:10 +00003157/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003158/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003159/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3160bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003161 LocTy AddrLoc;
3162 Value *Address;
3163 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003164 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3165 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166 return true;
3167
Duncan Sands1df98592010-02-16 11:11:14 +00003168 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003169 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003170
3171 // Parse the destination list.
3172 SmallVector<BasicBlock*, 16> DestList;
3173
3174 if (Lex.getKind() != lltok::rsquare) {
3175 BasicBlock *DestBB;
3176 if (ParseTypeAndBasicBlock(DestBB, PFS))
3177 return true;
3178 DestList.push_back(DestBB);
3179
3180 while (EatIfPresent(lltok::comma)) {
3181 if (ParseTypeAndBasicBlock(DestBB, PFS))
3182 return true;
3183 DestList.push_back(DestBB);
3184 }
3185 }
3186
3187 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3188 return true;
3189
Chris Lattnerab21db72009-10-28 00:19:10 +00003190 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003191 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3192 IBI->addDestination(DestList[i]);
3193 Inst = IBI;
3194 return false;
3195}
3196
3197
Chris Lattnerdf986172009-01-02 07:01:27 +00003198/// ParseInvoke
3199/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3200/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3201bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3202 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003203 unsigned RetAttrs, FnAttrs;
3204 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003205 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 LocTy RetTypeLoc;
3207 ValID CalleeID;
3208 SmallVector<ParamInfo, 16> ArgList;
3209
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 if (ParseOptionalCallingConv(CC) ||
3212 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003213 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003214 ParseValID(CalleeID) ||
3215 ParseParameterList(ArgList, PFS) ||
3216 ParseOptionalAttrs(FnAttrs, 2) ||
3217 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003218 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003219 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003220 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003222
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 // If RetType is a non-function pointer type, then this is the short syntax
3224 // for the call, which means that RetType is just the return type. Infer the
3225 // rest of the function argument types from the arguments that are present.
3226 const PointerType *PFTy = 0;
3227 const FunctionType *Ty = 0;
3228 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3229 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3230 // Pull out the types of all of the arguments...
3231 std::vector<const Type*> ParamTypes;
3232 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3233 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 if (!FunctionType::isValidReturnType(RetType))
3236 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Owen Andersondebcb012009-07-29 22:17:13 +00003238 Ty = FunctionType::get(RetType, ParamTypes, false);
3239 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 // Look up the callee.
3243 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003244 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003245
Chris Lattnerdf986172009-01-02 07:01:27 +00003246 // Set up the Attributes for the function.
3247 SmallVector<AttributeWithIndex, 8> Attrs;
3248 if (RetAttrs != Attribute::None)
3249 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003250
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003252
Chris Lattnerdf986172009-01-02 07:01:27 +00003253 // Loop through FunctionType's arguments and ensure they are specified
3254 // correctly. Also, gather any parameter attributes.
3255 FunctionType::param_iterator I = Ty->param_begin();
3256 FunctionType::param_iterator E = Ty->param_end();
3257 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3258 const Type *ExpectedTy = 0;
3259 if (I != E) {
3260 ExpectedTy = *I++;
3261 } else if (!Ty->isVarArg()) {
3262 return Error(ArgList[i].Loc, "too many arguments specified");
3263 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003264
Chris Lattnerdf986172009-01-02 07:01:27 +00003265 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3266 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3267 ExpectedTy->getDescription() + "'");
3268 Args.push_back(ArgList[i].V);
3269 if (ArgList[i].Attrs != Attribute::None)
3270 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3271 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003272
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 if (I != E)
3274 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003275
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 if (FnAttrs != Attribute::None)
3277 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003278
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 // Finish off the Attributes and check them
3280 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003281
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003282 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003283 Args.begin(), Args.end());
3284 II->setCallingConv(CC);
3285 II->setAttributes(PAL);
3286 Inst = II;
3287 return false;
3288}
3289
3290
3291
3292//===----------------------------------------------------------------------===//
3293// Binary Operators.
3294//===----------------------------------------------------------------------===//
3295
3296/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003297/// ::= ArithmeticOps TypeAndValue ',' Value
3298///
3299/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3300/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003301bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003302 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003303 LocTy Loc; Value *LHS, *RHS;
3304 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3305 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3306 ParseValue(LHS->getType(), RHS, PFS))
3307 return true;
3308
Chris Lattnere914b592009-01-05 08:24:46 +00003309 bool Valid;
3310 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003311 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003312 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003313 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3314 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003315 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003316 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3317 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003318 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003319
Chris Lattnere914b592009-01-05 08:24:46 +00003320 if (!Valid)
3321 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003322
Chris Lattnerdf986172009-01-02 07:01:27 +00003323 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3324 return false;
3325}
3326
3327/// ParseLogical
3328/// ::= ArithmeticOps TypeAndValue ',' Value {
3329bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3330 unsigned Opc) {
3331 LocTy Loc; Value *LHS, *RHS;
3332 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3333 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3334 ParseValue(LHS->getType(), RHS, PFS))
3335 return true;
3336
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003337 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 return Error(Loc,"instruction requires integer or integer vector operands");
3339
3340 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3341 return false;
3342}
3343
3344
3345/// ParseCompare
3346/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3347/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003348bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3349 unsigned Opc) {
3350 // Parse the integer/fp comparison predicate.
3351 LocTy Loc;
3352 unsigned Pred;
3353 Value *LHS, *RHS;
3354 if (ParseCmpPredicate(Pred, Opc) ||
3355 ParseTypeAndValue(LHS, Loc, PFS) ||
3356 ParseToken(lltok::comma, "expected ',' after compare value") ||
3357 ParseValue(LHS->getType(), RHS, PFS))
3358 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003361 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003362 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003363 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003364 } else {
3365 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003366 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003367 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003369 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 }
3371 return false;
3372}
3373
3374//===----------------------------------------------------------------------===//
3375// Other Instructions.
3376//===----------------------------------------------------------------------===//
3377
3378
3379/// ParseCast
3380/// ::= CastOpc TypeAndValue 'to' Type
3381bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3382 unsigned Opc) {
3383 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003384 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 if (ParseTypeAndValue(Op, Loc, PFS) ||
3386 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3387 ParseType(DestTy))
3388 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003390 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3391 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003392 return Error(Loc, "invalid cast opcode for cast from '" +
3393 Op->getType()->getDescription() + "' to '" +
3394 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003395 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003396 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3397 return false;
3398}
3399
3400/// ParseSelect
3401/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3402bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3403 LocTy Loc;
3404 Value *Op0, *Op1, *Op2;
3405 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3406 ParseToken(lltok::comma, "expected ',' after select condition") ||
3407 ParseTypeAndValue(Op1, PFS) ||
3408 ParseToken(lltok::comma, "expected ',' after select value") ||
3409 ParseTypeAndValue(Op2, PFS))
3410 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003411
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3413 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003414
Chris Lattnerdf986172009-01-02 07:01:27 +00003415 Inst = SelectInst::Create(Op0, Op1, Op2);
3416 return false;
3417}
3418
Chris Lattner0088a5c2009-01-05 08:18:44 +00003419/// ParseVA_Arg
3420/// ::= 'va_arg' TypeAndValue ',' Type
3421bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003422 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003423 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003424 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 if (ParseTypeAndValue(Op, PFS) ||
3426 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003427 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003428 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003429
Chris Lattner0088a5c2009-01-05 08:18:44 +00003430 if (!EltTy->isFirstClassType())
3431 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003432
3433 Inst = new VAArgInst(Op, EltTy);
3434 return false;
3435}
3436
3437/// ParseExtractElement
3438/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3439bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3440 LocTy Loc;
3441 Value *Op0, *Op1;
3442 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3443 ParseToken(lltok::comma, "expected ',' after extract value") ||
3444 ParseTypeAndValue(Op1, PFS))
3445 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003446
Chris Lattnerdf986172009-01-02 07:01:27 +00003447 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3448 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003449
Eric Christophera3500da2009-07-25 02:28:41 +00003450 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003451 return false;
3452}
3453
3454/// ParseInsertElement
3455/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3456bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3457 LocTy Loc;
3458 Value *Op0, *Op1, *Op2;
3459 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3460 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3461 ParseTypeAndValue(Op1, PFS) ||
3462 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3463 ParseTypeAndValue(Op2, PFS))
3464 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003465
Chris Lattnerdf986172009-01-02 07:01:27 +00003466 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003467 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003468
Chris Lattnerdf986172009-01-02 07:01:27 +00003469 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3470 return false;
3471}
3472
3473/// ParseShuffleVector
3474/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3475bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3476 LocTy Loc;
3477 Value *Op0, *Op1, *Op2;
3478 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3479 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3480 ParseTypeAndValue(Op1, PFS) ||
3481 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3482 ParseTypeAndValue(Op2, PFS))
3483 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003484
Chris Lattnerdf986172009-01-02 07:01:27 +00003485 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3486 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003487
Chris Lattnerdf986172009-01-02 07:01:27 +00003488 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3489 return false;
3490}
3491
3492/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003493/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003494int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003495 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003496 Value *Op0, *Op1;
3497 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003498
Chris Lattnerdf986172009-01-02 07:01:27 +00003499 if (ParseType(Ty) ||
3500 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3501 ParseValue(Ty, Op0, PFS) ||
3502 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003503 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3505 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003506
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003507 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3509 while (1) {
3510 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003511
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003512 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003513 break;
3514
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003515 if (Lex.getKind() == lltok::MetadataVar) {
3516 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003517 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003518 }
Devang Patela43d46f2009-10-16 18:45:49 +00003519
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003520 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003521 ParseValue(Ty, Op0, PFS) ||
3522 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003523 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3525 return true;
3526 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 if (!Ty->isFirstClassType())
3529 return Error(TypeLoc, "phi node must have first class type");
3530
Jay Foad3ecfc862011-03-30 11:28:46 +00003531 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003532 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3533 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3534 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003535 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003536}
3537
3538/// ParseCall
3539/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3540/// ParameterList OptionalAttrs
3541bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3542 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003543 unsigned RetAttrs, FnAttrs;
3544 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003545 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003546 LocTy RetTypeLoc;
3547 ValID CalleeID;
3548 SmallVector<ParamInfo, 16> ArgList;
3549 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003550
Chris Lattnerdf986172009-01-02 07:01:27 +00003551 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3552 ParseOptionalCallingConv(CC) ||
3553 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003554 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003555 ParseValID(CalleeID) ||
3556 ParseParameterList(ArgList, PFS) ||
3557 ParseOptionalAttrs(FnAttrs, 2))
3558 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003559
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 // If RetType is a non-function pointer type, then this is the short syntax
3561 // for the call, which means that RetType is just the return type. Infer the
3562 // rest of the function argument types from the arguments that are present.
3563 const PointerType *PFTy = 0;
3564 const FunctionType *Ty = 0;
3565 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3566 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3567 // Pull out the types of all of the arguments...
3568 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003569 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3570 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003571
Chris Lattnerdf986172009-01-02 07:01:27 +00003572 if (!FunctionType::isValidReturnType(RetType))
3573 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003574
Owen Andersondebcb012009-07-29 22:17:13 +00003575 Ty = FunctionType::get(RetType, ParamTypes, false);
3576 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003578
Chris Lattnerdf986172009-01-02 07:01:27 +00003579 // Look up the callee.
3580 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003581 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003582
Chris Lattnerdf986172009-01-02 07:01:27 +00003583 // Set up the Attributes for the function.
3584 SmallVector<AttributeWithIndex, 8> Attrs;
3585 if (RetAttrs != Attribute::None)
3586 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003587
Chris Lattnerdf986172009-01-02 07:01:27 +00003588 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003589
Chris Lattnerdf986172009-01-02 07:01:27 +00003590 // Loop through FunctionType's arguments and ensure they are specified
3591 // correctly. Also, gather any parameter attributes.
3592 FunctionType::param_iterator I = Ty->param_begin();
3593 FunctionType::param_iterator E = Ty->param_end();
3594 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3595 const Type *ExpectedTy = 0;
3596 if (I != E) {
3597 ExpectedTy = *I++;
3598 } else if (!Ty->isVarArg()) {
3599 return Error(ArgList[i].Loc, "too many arguments specified");
3600 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003601
Chris Lattnerdf986172009-01-02 07:01:27 +00003602 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3603 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3604 ExpectedTy->getDescription() + "'");
3605 Args.push_back(ArgList[i].V);
3606 if (ArgList[i].Attrs != Attribute::None)
3607 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3608 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 if (I != E)
3611 return Error(CallLoc, "not enough parameters specified for call");
3612
3613 if (FnAttrs != Attribute::None)
3614 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3615
3616 // Finish off the Attributes and check them
3617 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003618
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3620 CI->setTailCall(isTail);
3621 CI->setCallingConv(CC);
3622 CI->setAttributes(PAL);
3623 Inst = CI;
3624 return false;
3625}
3626
3627//===----------------------------------------------------------------------===//
3628// Memory Instructions.
3629//===----------------------------------------------------------------------===//
3630
3631/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003632/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003633int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003634 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003636 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003638 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003639
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003640 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003641 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003642 if (Lex.getKind() == lltok::kw_align) {
3643 if (ParseOptionalAlignment(Alignment)) return true;
3644 } else if (Lex.getKind() == lltok::MetadataVar) {
3645 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003646 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003647 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3648 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3649 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003650 }
3651 }
3652
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003653 if (Size && !Size->getType()->isIntegerTy())
3654 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003655
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003656 Inst = new AllocaInst(Ty, Size, Alignment);
3657 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003658}
3659
3660/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003661/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003662int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3663 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003664 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003665 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003666 bool AteExtraComma = false;
3667 if (ParseTypeAndValue(Val, Loc, PFS) ||
3668 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3669 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003670
Duncan Sands1df98592010-02-16 11:11:14 +00003671 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3673 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003674
Chris Lattnerdf986172009-01-02 07:01:27 +00003675 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003676 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003677}
3678
3679/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003680/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003681int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3682 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003683 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003684 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003685 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003686 if (ParseTypeAndValue(Val, Loc, PFS) ||
3687 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003688 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3689 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003690 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003691
Duncan Sands1df98592010-02-16 11:11:14 +00003692 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003693 return Error(PtrLoc, "store operand must be a pointer");
3694 if (!Val->getType()->isFirstClassType())
3695 return Error(Loc, "store operand must be a first class value");
3696 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3697 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003698
Chris Lattnerdf986172009-01-02 07:01:27 +00003699 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003700 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003701}
3702
Chris Lattnerdf986172009-01-02 07:01:27 +00003703/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003704/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003705int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003706 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003707
Dan Gohmandcb40a32009-07-29 15:58:36 +00003708 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003709
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003710 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003711
Duncan Sands1df98592010-02-16 11:11:14 +00003712 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003713 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003714
Chris Lattnerdf986172009-01-02 07:01:27 +00003715 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003716 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003717 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003718 if (Lex.getKind() == lltok::MetadataVar) {
3719 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003720 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003721 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003722 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003723 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 return Error(EltLoc, "getelementptr index must be an integer");
3725 Indices.push_back(Val);
3726 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003727
Chris Lattnerdf986172009-01-02 07:01:27 +00003728 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3729 Indices.begin(), Indices.end()))
3730 return Error(Loc, "invalid getelementptr indices");
3731 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003732 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003733 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003734 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003735}
3736
3737/// ParseExtractValue
3738/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003739int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 Value *Val; LocTy Loc;
3741 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003742 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003743 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003744 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003745 return true;
3746
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003747 if (!Val->getType()->isAggregateType())
3748 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003749
3750 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3751 Indices.end()))
3752 return Error(Loc, "invalid indices for extractvalue");
3753 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003754 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003755}
3756
3757/// ParseInsertValue
3758/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003759int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003760 Value *Val0, *Val1; LocTy Loc0, Loc1;
3761 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003762 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003763 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3764 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3765 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003766 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003767 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003768
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003769 if (!Val0->getType()->isAggregateType())
3770 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003771
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3773 Indices.end()))
3774 return Error(Loc0, "invalid indices for insertvalue");
3775 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003776 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003777}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003778
3779//===----------------------------------------------------------------------===//
3780// Embedded metadata.
3781//===----------------------------------------------------------------------===//
3782
3783/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003784/// ::= Element (',' Element)*
3785/// Element
3786/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003787bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003788 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003789 // Check for an empty list.
3790 if (Lex.getKind() == lltok::rbrace)
3791 return false;
3792
Nick Lewycky21cc4462009-04-04 07:22:01 +00003793 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003794 // Null is a special case since it is typeless.
3795 if (EatIfPresent(lltok::kw_null)) {
3796 Elts.push_back(0);
3797 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003798 }
Chris Lattnera7352392009-12-30 04:42:57 +00003799
3800 Value *V = 0;
3801 PATypeHolder Ty(Type::getVoidTy(Context));
3802 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003803 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003804 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003805 return true;
3806
Nick Lewyckycb337992009-05-10 20:57:05 +00003807 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003808 } while (EatIfPresent(lltok::comma));
3809
3810 return false;
3811}