blob: b33d6ad35c989dbc7c440a1af387a7054684f208 [file] [log] [blame]
Chris Lattnerac161bf2009-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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000022#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000028#include "llvm/Support/raw_ostream.h"
29using namespace llvm;
30
Chris Lattner229907c2011-07-18 04:54:35 +000031static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000032 std::string Result;
33 raw_string_ostream Tmp(Result);
34 Tmp << *T;
35 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000036}
37
Chris Lattner3822f632009-01-02 08:05:26 +000038/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000039bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000040 // Prime the lexer.
41 Lex.Lex();
42
Chris Lattnerad6f3352009-01-04 20:44:11 +000043 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000045}
46
47/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48/// module.
49bool LLParser::ValidateEndOfModule() {
Chris Lattner8eff0152010-04-01 05:14:45 +000050 // Handle any instruction metadata forward references.
51 if (!ForwardRefInstMetadata.empty()) {
52 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
53 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 I != E; ++I) {
55 Instruction *Inst = I->first;
56 const std::vector<MDRef> &MDList = I->second;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000057
Chris Lattner8eff0152010-04-01 05:14:45 +000058 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
59 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman26ee2b82012-11-15 22:34:00 +000060
Craig Topper2617dcc2014-04-15 06:32:26 +000061 if (SlotNo >= NumberedMetadata.size() ||
62 NumberedMetadata[SlotNo] == nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +000063 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +000064 Twine(SlotNo) + "'");
Chris Lattner8eff0152010-04-01 05:14:45 +000065 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
66 }
67 }
68 ForwardRefInstMetadata.clear();
69 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +000070
Manman Ren209b17c2013-09-28 00:22:27 +000071 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
72 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73
Bill Wendlingb32b0412013-02-08 06:32:06 +000074 // Handle any function attribute group forward references.
75 for (std::map<Value*, std::vector<unsigned> >::iterator
76 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
77 I != E; ++I) {
78 Value *V = I->first;
79 std::vector<unsigned> &Vec = I->second;
80 AttrBuilder B;
81
82 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 VI != VE; ++VI)
84 B.merge(NumberedAttrBuilders[*VI]);
85
86 if (Function *Fn = dyn_cast<Function>(V)) {
87 AttributeSet AS = Fn->getAttributes();
88 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
89 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
90 AS.getFnAttributes());
91
92 FnAttrs.merge(B);
93
94 // If the alignment was parsed as an attribute, move to the alignment
95 // field.
96 if (FnAttrs.hasAlignmentAttr()) {
97 Fn->setAlignment(FnAttrs.getAlignment());
98 FnAttrs.removeAttribute(Attribute::Alignment);
99 }
100
101 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
102 AttributeSet::get(Context,
103 AttributeSet::FunctionIndex,
104 FnAttrs));
105 Fn->setAttributes(AS);
106 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
107 AttributeSet AS = CI->getAttributes();
108 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
109 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
110 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000111 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000112 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
113 AttributeSet::get(Context,
114 AttributeSet::FunctionIndex,
115 FnAttrs));
116 CI->setAttributes(AS);
117 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
118 AttributeSet AS = II->getAttributes();
119 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
120 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
121 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000122 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
124 AttributeSet::get(Context,
125 AttributeSet::FunctionIndex,
126 FnAttrs));
127 II->setAttributes(AS);
128 } else {
129 llvm_unreachable("invalid object with forward attribute group reference");
130 }
131 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000132
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000133 // If there are entries in ForwardRefBlockAddresses at this point, the
134 // function was never defined.
135 if (!ForwardRefBlockAddresses.empty())
136 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
137 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000139 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
140 if (NumberedTypes[i].second.isValid())
141 return Error(NumberedTypes[i].second,
142 "use of undefined type '%" + Twine(i) + "'");
143
144 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
145 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
146 if (I->second.second.isValid())
147 return Error(I->second.second,
148 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000149
David Majnemerdad0a642014-06-27 18:19:56 +0000150 if (!ForwardRefComdats.empty())
151 return Error(ForwardRefComdats.begin()->second,
152 "use of undefined comdat '$" +
153 ForwardRefComdats.begin()->first + "'");
154
Chris Lattnerac161bf2009-01-02 07:01:27 +0000155 if (!ForwardRefVals.empty())
156 return Error(ForwardRefVals.begin()->second.second,
157 "use of undefined value '@" + ForwardRefVals.begin()->first +
158 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000159
Chris Lattnerac161bf2009-01-02 07:01:27 +0000160 if (!ForwardRefValIDs.empty())
161 return Error(ForwardRefValIDs.begin()->second.second,
162 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000163 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000164
Devang Pateld2541152009-07-08 19:23:54 +0000165 if (!ForwardRefMDNodes.empty())
166 return Error(ForwardRefMDNodes.begin()->second.second,
167 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000168 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000169
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000170 // Resolve metadata cycles.
171 for (auto &N : NumberedMetadata)
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000172 if (auto *U = cast_or_null<UniquableMDNode>(N))
173 U->resolveCycles();
Devang Pateld2541152009-07-08 19:23:54 +0000174
Chris Lattnerac161bf2009-01-02 07:01:27 +0000175 // Look for intrinsic functions and CallInst that need to be upgraded
176 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
177 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000178
Manman Ren8b4306c2013-12-02 21:29:56 +0000179 UpgradeDebugInfo(*M);
180
Chris Lattnerac161bf2009-01-02 07:01:27 +0000181 return false;
182}
183
184//===----------------------------------------------------------------------===//
185// Top-Level Entities
186//===----------------------------------------------------------------------===//
187
188bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000189 while (1) {
190 switch (Lex.getKind()) {
191 default: return TokError("expected top-level entity");
192 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000193 case lltok::kw_declare: if (ParseDeclare()) return true; break;
194 case lltok::kw_define: if (ParseDefine()) return true; break;
195 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
196 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000197 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000198 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000199 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000200 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000202 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000203 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000204 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000205
206 // The Global variable production with no name can have many different
207 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000208 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
209 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000210 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000211 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000212 case lltok::kw_internal: // OptionalLinkage
213 case lltok::kw_weak: // OptionalLinkage
214 case lltok::kw_weak_odr: // OptionalLinkage
215 case lltok::kw_linkonce: // OptionalLinkage
216 case lltok::kw_linkonce_odr: // OptionalLinkage
217 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000218 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000219 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000220 case lltok::kw_external: // OptionalLinkage
221 case lltok::kw_default: // OptionalVisibility
222 case lltok::kw_hidden: // OptionalVisibility
223 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000224 case lltok::kw_dllimport: // OptionalDLLStorageClass
225 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000226 case lltok::kw_thread_local: // OptionalThreadLocal
227 case lltok::kw_addrspace: // OptionalAddrSpace
228 case lltok::kw_constant: // GlobalType
229 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000230 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000231 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000232 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000233 bool HasLinkage;
234 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000235 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000236 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000237 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000238 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000239 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000240 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000241 return true;
242 break;
243 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000244
245 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000246 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
247 case lltok::kw_uselistorder_bb:
248 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000249 }
250 }
251}
252
253
254/// toplevelentity
255/// ::= 'module' 'asm' STRINGCONSTANT
256bool LLParser::ParseModuleAsm() {
257 assert(Lex.getKind() == lltok::kw_module);
258 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000259
260 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000261 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
262 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000263
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000264 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 return false;
266}
267
268/// toplevelentity
269/// ::= 'target' 'triple' '=' STRINGCONSTANT
270/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
271bool LLParser::ParseTargetDefinition() {
272 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000273 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000274 switch (Lex.Lex()) {
275 default: return TokError("unknown target property");
276 case lltok::kw_triple:
277 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000278 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
279 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000281 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000282 return false;
283 case lltok::kw_datalayout:
284 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000285 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
286 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000287 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000288 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000289 return false;
290 }
291}
292
Bill Wendling706d3d62012-11-28 08:41:48 +0000293/// toplevelentity
294/// ::= 'deplibs' '=' '[' ']'
295/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
296/// FIXME: Remove in 4.0. Currently parse, but ignore.
297bool LLParser::ParseDepLibs() {
298 assert(Lex.getKind() == lltok::kw_deplibs);
299 Lex.Lex();
300 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
301 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
302 return true;
303
304 if (EatIfPresent(lltok::rsquare))
305 return false;
306
307 do {
308 std::string Str;
309 if (ParseStringConstant(Str)) return true;
310 } while (EatIfPresent(lltok::comma));
311
312 return ParseToken(lltok::rsquare, "expected ']' at end of list");
313}
314
Dan Gohman466876b2009-08-12 23:32:33 +0000315/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000316/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000317bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000318 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000319 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000320 Lex.Lex(); // eat LocalVarID;
321
322 if (ParseToken(lltok::equal, "expected '=' after name") ||
323 ParseToken(lltok::kw_type, "expected 'type' after '='"))
324 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000326 if (TypeID >= NumberedTypes.size())
327 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000328
Craig Topper2617dcc2014-04-15 06:32:26 +0000329 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000330 if (ParseStructDefinition(TypeLoc, "",
331 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333 if (!isa<StructType>(Result)) {
334 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
335 if (Entry.first)
336 return Error(TypeLoc, "non-struct types may not be recursive");
337 Entry.first = Result;
338 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000339 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000340
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341 return false;
342}
343
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000344
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345/// toplevelentity
346/// ::= LocalVar '=' 'type' type
347bool LLParser::ParseNamedType() {
348 std::string Name = Lex.getStrVal();
349 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000350 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000351
Chris Lattner3822f632009-01-02 08:05:26 +0000352 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000354 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000355
Craig Topper2617dcc2014-04-15 06:32:26 +0000356 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 if (ParseStructDefinition(NameLoc, Name,
358 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000359
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000360 if (!isa<StructType>(Result)) {
361 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
362 if (Entry.first)
363 return Error(NameLoc, "non-struct types may not be recursive");
364 Entry.first = Result;
365 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000366 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000368 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000369}
370
371
372/// toplevelentity
373/// ::= 'declare' FunctionHeader
374bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
376 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000377
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 Function *F;
379 return ParseFunctionHeader(F, false);
380}
381
382/// toplevelentity
383/// ::= 'define' FunctionHeader '{' ...
384bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
386 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000387
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000389 return ParseFunctionHeader(F, true) ||
390 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391}
392
Chris Lattner3822f632009-01-02 08:05:26 +0000393/// ParseGlobalType
394/// ::= 'constant'
395/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000396bool LLParser::ParseGlobalType(bool &IsConstant) {
397 if (Lex.getKind() == lltok::kw_constant)
398 IsConstant = true;
399 else if (Lex.getKind() == lltok::kw_global)
400 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000401 else {
402 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000403 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000404 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000405 Lex.Lex();
406 return false;
407}
408
Dan Gohman466876b2009-08-12 23:32:33 +0000409/// ParseUnnamedGlobal:
410/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000411/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
412/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000413/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000414/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
415/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000416bool LLParser::ParseUnnamedGlobal() {
417 unsigned VarID = NumberedVals.size();
418 std::string Name;
419 LocTy NameLoc = Lex.getLoc();
420
421 // Handle the GlobalID form.
422 if (Lex.getKind() == lltok::GlobalID) {
423 if (Lex.getUIntVal() != VarID)
424 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000425 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000426 Lex.Lex(); // eat GlobalID;
427
428 if (ParseToken(lltok::equal, "expected '=' after name"))
429 return true;
430 }
431
432 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000433 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000434 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000435 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000436 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000437 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000438 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000439 ParseOptionalThreadLocal(TLM) ||
440 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000441 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000442
Rafael Espindola464fe022014-07-30 22:51:54 +0000443 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000444 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000445 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000446 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000447 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000448}
449
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450/// ParseNamedGlobal:
451/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000452/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454bool LLParser::ParseNamedGlobal() {
455 assert(Lex.getKind() == lltok::GlobalVar);
456 LocTy NameLoc = Lex.getLoc();
457 std::string Name = Lex.getStrVal();
458 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000459
Chris Lattnerac161bf2009-01-02 07:01:27 +0000460 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000461 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000462 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000463 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000464 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
465 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000466 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000467 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000468 ParseOptionalThreadLocal(TLM) ||
469 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000471
Rafael Espindola464fe022014-07-30 22:51:54 +0000472 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000473 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000474 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000475
476 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000477 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000478}
479
David Majnemerdad0a642014-06-27 18:19:56 +0000480bool LLParser::parseComdat() {
481 assert(Lex.getKind() == lltok::ComdatVar);
482 std::string Name = Lex.getStrVal();
483 LocTy NameLoc = Lex.getLoc();
484 Lex.Lex();
485
486 if (ParseToken(lltok::equal, "expected '=' here"))
487 return true;
488
489 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
490 return TokError("expected comdat type");
491
492 Comdat::SelectionKind SK;
493 switch (Lex.getKind()) {
494 default:
495 return TokError("unknown selection kind");
496 case lltok::kw_any:
497 SK = Comdat::Any;
498 break;
499 case lltok::kw_exactmatch:
500 SK = Comdat::ExactMatch;
501 break;
502 case lltok::kw_largest:
503 SK = Comdat::Largest;
504 break;
505 case lltok::kw_noduplicates:
506 SK = Comdat::NoDuplicates;
507 break;
508 case lltok::kw_samesize:
509 SK = Comdat::SameSize;
510 break;
511 }
512 Lex.Lex();
513
514 // See if the comdat was forward referenced, if so, use the comdat.
515 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
516 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
517 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
518 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
519
520 Comdat *C;
521 if (I != ComdatSymTab.end())
522 C = &I->second;
523 else
524 C = M->getOrInsertComdat(Name);
525 C->setSelectionKind(SK);
526
527 return false;
528}
529
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000530// MDString:
531// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000532bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000533 std::string Str;
534 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000535 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000536 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000537 return false;
538}
539
540// MDNode:
541// ::= '!' MDNodeNumber
Chris Lattner8eff0152010-04-01 05:14:45 +0000542//
543/// This version of ParseMDNodeID returns the slot number and null in the case
544/// of a forward reference.
545bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
546 // !{ ..., !42, ... }
547 if (ParseUInt32(SlotNo)) return true;
548
549 // Check existing MDNode.
Craig Topper2617dcc2014-04-15 06:32:26 +0000550 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
Chris Lattner8eff0152010-04-01 05:14:45 +0000551 Result = NumberedMetadata[SlotNo];
552 else
Craig Topper2617dcc2014-04-15 06:32:26 +0000553 Result = nullptr;
Chris Lattner8eff0152010-04-01 05:14:45 +0000554 return false;
555}
556
Chris Lattner6dac02a2009-12-30 04:15:23 +0000557bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000558 // !{ ..., !42, ... }
559 unsigned MID = 0;
Chris Lattner8eff0152010-04-01 05:14:45 +0000560 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000561
Chris Lattner8eff0152010-04-01 05:14:45 +0000562 // If not a forward reference, just return it now.
563 if (Result) return false;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000564
Chris Lattner8eff0152010-04-01 05:14:45 +0000565 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000566 MDNodeFwdDecl *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000567 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000568
Chris Lattnerfc58af22009-12-30 04:51:58 +0000569 if (NumberedMetadata.size() <= MID)
570 NumberedMetadata.resize(MID+1);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000571 NumberedMetadata[MID].reset(FwdNode);
Chris Lattner1797fc72009-12-29 21:53:55 +0000572 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000573 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000574}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000575
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000576/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000577/// !foo = !{ !1, !2 }
578bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000579 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000580 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000581 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000582
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000583 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000584 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000585 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000586 return true;
587
Dan Gohman2637cc12010-07-21 23:38:33 +0000588 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000589 if (Lex.getKind() != lltok::rbrace)
590 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000591 if (ParseToken(lltok::exclaim, "Expected '!' here"))
592 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000593
Craig Topper2617dcc2014-04-15 06:32:26 +0000594 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000595 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000596 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000597 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000598
599 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
600 return true;
601
Devang Patelbe626972009-07-29 00:34:02 +0000602 return false;
603}
604
Devang Patel39e64d42009-07-01 19:21:12 +0000605/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000606/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000607bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000608 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000609 Lex.Lex();
610 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000611
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000612 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000613 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000614 ParseToken(lltok::equal, "expected '=' here"))
615 return true;
616
617 // Detect common error, from old metadata syntax.
618 if (Lex.getKind() == lltok::Type)
619 return TokError("unexpected type in metadata definition");
620
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000621 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000622 if (ParseToken(lltok::exclaim, "Expected '!' here") ||
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000623 ParseMDNode(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000624 return true;
625
Chris Lattnerfc58af22009-12-30 04:51:58 +0000626 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000627 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000628 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000629 auto *Temp = FI->second.first;
Dan Gohman16a5d982010-08-20 22:02:26 +0000630 Temp->replaceAllUsesWith(Init);
631 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000632 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000633
Chris Lattnerfc58af22009-12-30 04:51:58 +0000634 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
635 } else {
636 if (MetadataID >= NumberedMetadata.size())
637 NumberedMetadata.resize(MetadataID+1);
638
Craig Topper2617dcc2014-04-15 06:32:26 +0000639 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000640 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000641 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000642 }
643
Devang Patel39e64d42009-07-01 19:21:12 +0000644 return false;
645}
646
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000647static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
648 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
649 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
650}
651
Chris Lattnerac161bf2009-01-02 07:01:27 +0000652/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000653/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
654/// OptionalDLLStorageClass OptionalThreadLocal
655/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000656///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000657/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000658/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000659///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000660/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000661///
Rafael Espindola464fe022014-07-30 22:51:54 +0000662bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000663 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000664 GlobalVariable::ThreadLocalMode TLM,
665 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000666 assert(Lex.getKind() == lltok::kw_alias);
667 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000668
Rafael Espindola78527052013-10-06 15:10:43 +0000669 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
670
Rafael Espindolacaa43562013-10-09 16:07:32 +0000671 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000672 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000673
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000674 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000675 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000676 "symbol with local linkage must have default visibility");
677
Rafael Espindola64c1e182014-06-03 02:41:57 +0000678 Constant *Aliasee;
679 LocTy AliaseeLoc = Lex.getLoc();
680 if (Lex.getKind() != lltok::kw_bitcast &&
681 Lex.getKind() != lltok::kw_getelementptr &&
682 Lex.getKind() != lltok::kw_addrspacecast &&
683 Lex.getKind() != lltok::kw_inttoptr) {
684 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000685 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000686 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000687 // The bitcast dest type is not present, it is implied by the dest type.
688 ValID ID;
689 if (ParseValID(ID))
690 return true;
691 if (ID.Kind != ValID::t_Constant)
692 return Error(AliaseeLoc, "invalid aliasee");
693 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000694 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000695
Rafael Espindola64c1e182014-06-03 02:41:57 +0000696 Type *AliaseeType = Aliasee->getType();
697 auto *PTy = dyn_cast<PointerType>(AliaseeType);
698 if (!PTy)
699 return Error(AliaseeLoc, "An alias must have pointer type");
700 Type *Ty = PTy->getElementType();
701 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000702
703 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000704 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000705 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
706 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000707 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000708 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000709 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000710 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000711
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712 // See if this value already exists in the symbol table. If so, it is either
713 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000714 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715 // See if this was a redefinition. If so, there is no entry in
716 // ForwardRefVals.
717 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
718 I = ForwardRefVals.find(Name);
719 if (I == ForwardRefVals.end())
720 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
721
722 // Otherwise, this was a definition of forward ref. Verify that types
723 // agree.
724 if (Val->getType() != GA->getType())
725 return Error(NameLoc,
726 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000727
Chris Lattnerac161bf2009-01-02 07:01:27 +0000728 // If they agree, just RAUW the old value with the alias and remove the
729 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000730 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000731 Val->eraseFromParent();
732 ForwardRefVals.erase(I);
733 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Chris Lattnerac161bf2009-01-02 07:01:27 +0000735 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000736 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000737 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000738
Rafael Espindolaaa273822014-05-09 21:49:17 +0000739 // The module owns this now
740 GA.release();
741
Chris Lattnerac161bf2009-01-02 07:01:27 +0000742 return false;
743}
744
745/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000746/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000747/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000748/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000749/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000750/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000751/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000753/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000754/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000755///
756bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
757 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000758 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000759 GlobalVariable::ThreadLocalMode TLM,
760 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000761 if (!isValidVisibilityForLinkage(Visibility, Linkage))
762 return Error(NameLoc,
763 "symbol with local linkage must have default visibility");
764
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000766 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000767 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000768 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000769
Craig Topper2617dcc2014-04-15 06:32:26 +0000770 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000771 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000772 ParseOptionalToken(lltok::kw_externally_initialized,
773 IsExternallyInitialized,
774 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000775 ParseGlobalType(IsConstant) ||
776 ParseType(Ty, TyLoc))
777 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000778
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 // If the linkage is specified and is external, then no initializer is
780 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000781 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000782 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000783 Linkage != GlobalValue::ExternalLinkage)) {
784 if (ParseGlobalValue(Ty, Init))
785 return true;
786 }
787
Duncan Sands19d0b472010-02-16 11:11:14 +0000788 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000789 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000790
David Majnemer598bd052014-12-09 05:56:09 +0000791 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792
793 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000794 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000795 GVal = M->getNamedValue(Name);
796 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000797 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
798 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000799 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 } else {
801 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
802 I = ForwardRefValIDs.find(NumberedVals.size());
803 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000804 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000805 ForwardRefValIDs.erase(I);
806 }
807 }
808
David Majnemer598bd052014-12-09 05:56:09 +0000809 GlobalVariable *GV;
810 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000811 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
812 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000813 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000814 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000815 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000816 return Error(TyLoc,
817 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
David Majnemer598bd052014-12-09 05:56:09 +0000819 GV = cast<GlobalVariable>(GVal);
820
Chris Lattnerac161bf2009-01-02 07:01:27 +0000821 // Move the forward-reference to the correct spot in the module.
822 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
823 }
824
825 if (Name.empty())
826 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 // Set the parsed properties on the global.
829 if (Init)
830 GV->setInitializer(Init);
831 GV->setConstant(IsConstant);
832 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
833 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000834 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000835 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000836 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000837 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000838
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839 // Parse attributes on the global.
840 while (Lex.getKind() == lltok::comma) {
841 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000842
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843 if (Lex.getKind() == lltok::kw_section) {
844 Lex.Lex();
845 GV->setSection(Lex.getStrVal());
846 if (ParseToken(lltok::StringConstant, "expected global section string"))
847 return true;
848 } else if (Lex.getKind() == lltok::kw_align) {
849 unsigned Alignment;
850 if (ParseOptionalAlignment(Alignment)) return true;
851 GV->setAlignment(Alignment);
852 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000853 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000854 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000855 return true;
856 if (C)
857 GV->setComdat(C);
858 else
859 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000860 }
861 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000862
Chris Lattnerac161bf2009-01-02 07:01:27 +0000863 return false;
864}
865
Bill Wendling63b88192013-02-06 06:52:58 +0000866/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000867/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000868bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000869 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000870 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000871 Lex.Lex();
872
David Majnemerb39e22b2014-12-09 18:33:57 +0000873 if (Lex.getKind() != lltok::AttrGrpID)
874 return TokError("expected attribute group id");
875
Bill Wendling63b88192013-02-06 06:52:58 +0000876 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000877 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000878 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000879 Lex.Lex();
880
881 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000882 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000883 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000884 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000885 ParseToken(lltok::rbrace, "expected end of attribute group"))
886 return true;
887
Bill Wendlingb32b0412013-02-08 06:32:06 +0000888 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000889 return Error(AttrGrpLoc, "attribute group has no attributes");
890
891 return false;
892}
893
Bill Wendling8b0321d2013-02-08 00:52:31 +0000894/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000895/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000896bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
897 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000898 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000899 bool HaveError = false;
900
901 B.clear();
902
Bill Wendling63b88192013-02-06 06:52:58 +0000903 while (true) {
904 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000905 if (Token == lltok::kw_builtin)
906 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000907 switch (Token) {
908 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000909 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000910 return Error(Lex.getLoc(), "unterminated attribute group");
911 case lltok::rbrace:
912 // Finished.
913 return false;
914
Bill Wendlingb32b0412013-02-08 06:32:06 +0000915 case lltok::AttrGrpID: {
916 // Allow a function to reference an attribute group:
917 //
918 // define void @foo() #1 { ... }
919 if (inAttrGrp)
920 HaveError |=
921 Error(Lex.getLoc(),
922 "cannot have an attribute group reference in an attribute group");
923
924 unsigned AttrGrpNum = Lex.getUIntVal();
925 if (inAttrGrp) break;
926
927 // Save the reference to the attribute group. We'll fill it in later.
928 FwdRefAttrGrps.push_back(AttrGrpNum);
929 break;
930 }
Bill Wendling63b88192013-02-06 06:52:58 +0000931 // Target-dependent attributes:
932 case lltok::StringConstant: {
933 std::string Attr = Lex.getStrVal();
934 Lex.Lex();
935 std::string Val;
936 if (EatIfPresent(lltok::equal) &&
937 ParseStringConstant(Val))
938 return true;
939
940 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000941 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000942 }
943
944 // Target-independent attributes:
945 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000946 // As a hack, we allow function alignment to be initially parsed as an
947 // attribute on a function declaration/definition or added to an attribute
948 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000949 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000950 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000951 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000952 if (ParseToken(lltok::equal, "expected '=' here") ||
953 ParseUInt32(Alignment))
954 return true;
955 } else {
956 if (ParseOptionalAlignment(Alignment))
957 return true;
958 }
Bill Wendling63b88192013-02-06 06:52:58 +0000959 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000960 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000961 }
962 case lltok::kw_alignstack: {
963 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000964 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000965 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000966 if (ParseToken(lltok::equal, "expected '=' here") ||
967 ParseUInt32(Alignment))
968 return true;
969 } else {
970 if (ParseOptionalStackAlignment(Alignment))
971 return true;
972 }
Bill Wendling63b88192013-02-06 06:52:58 +0000973 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000974 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000975 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000976 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000977 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000978 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000979 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000980 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000981 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
982 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
983 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
984 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
985 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
986 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
987 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
988 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
989 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
990 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000991 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000992 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
993 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
994 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
995 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
996 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
997 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
998 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
999 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1000 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1001 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1002 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001003
1004 // Error handling.
1005 case lltok::kw_inreg:
1006 case lltok::kw_signext:
1007 case lltok::kw_zeroext:
1008 HaveError |=
1009 Error(Lex.getLoc(),
1010 "invalid use of attribute on a function");
1011 break;
1012 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001013 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +00001014 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001015 case lltok::kw_nest:
1016 case lltok::kw_noalias:
1017 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001018 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001019 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001020 case lltok::kw_sret:
1021 HaveError |=
1022 Error(Lex.getLoc(),
1023 "invalid use of parameter-only attribute on a function");
1024 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001025 }
1026
1027 Lex.Lex();
1028 }
1029}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001030
1031//===----------------------------------------------------------------------===//
1032// GlobalValue Reference/Resolution Routines.
1033//===----------------------------------------------------------------------===//
1034
1035/// GetGlobalVal - Get a value with the specified name or ID, creating a
1036/// forward reference record if needed. This can return null if the value
1037/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001038GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001040 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001041 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001042 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001043 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001044 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattnerac161bf2009-01-02 07:01:27 +00001046 // Look this name up in the normal function symbol table.
1047 GlobalValue *Val =
1048 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001049
Chris Lattnerac161bf2009-01-02 07:01:27 +00001050 // If this is a forward reference for the value, see if we already created a
1051 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1054 I = ForwardRefVals.find(Name);
1055 if (I != ForwardRefVals.end())
1056 Val = I->second.first;
1057 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001058
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 // If we have the value in the symbol table or fwd-ref table, return it.
1060 if (Val) {
1061 if (Val->getType() == Ty) return Val;
1062 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001063 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001064 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001065 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001066
Chris Lattnerac161bf2009-01-02 07:01:27 +00001067 // Otherwise, create a new forward reference for this value and remember it.
1068 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001069 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001070 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001071 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001072 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001073 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1074 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001075 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001076
Chris Lattnerac161bf2009-01-02 07:01:27 +00001077 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1078 return FwdVal;
1079}
1080
Chris Lattner229907c2011-07-18 04:54:35 +00001081GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1082 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001083 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001085 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001087
Craig Topper2617dcc2014-04-15 06:32:26 +00001088 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001089
Chris Lattnerac161bf2009-01-02 07:01:27 +00001090 // If this is a forward reference for the value, see if we already created a
1091 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001092 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001093 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1094 I = ForwardRefValIDs.find(ID);
1095 if (I != ForwardRefValIDs.end())
1096 Val = I->second.first;
1097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001098
Chris Lattnerac161bf2009-01-02 07:01:27 +00001099 // If we have the value in the symbol table or fwd-ref table, return it.
1100 if (Val) {
1101 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001102 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001103 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001104 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001105 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001106
Chris Lattnerac161bf2009-01-02 07:01:27 +00001107 // Otherwise, create a new forward reference for this value and remember it.
1108 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001109 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001110 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001111 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001112 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001113 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001114
Chris Lattnerac161bf2009-01-02 07:01:27 +00001115 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1116 return FwdVal;
1117}
1118
1119
1120//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001121// Comdat Reference/Resolution Routines.
1122//===----------------------------------------------------------------------===//
1123
1124Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1125 // Look this name up in the comdat symbol table.
1126 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1127 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1128 if (I != ComdatSymTab.end())
1129 return &I->second;
1130
1131 // Otherwise, create a new forward reference for this value and remember it.
1132 Comdat *C = M->getOrInsertComdat(Name);
1133 ForwardRefComdats[Name] = Loc;
1134 return C;
1135}
1136
1137
1138//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001139// Helper Routines.
1140//===----------------------------------------------------------------------===//
1141
1142/// ParseToken - If the current token has the specified kind, eat it and return
1143/// success. Otherwise, emit the specified error and return failure.
1144bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1145 if (Lex.getKind() != T)
1146 return TokError(ErrMsg);
1147 Lex.Lex();
1148 return false;
1149}
1150
Chris Lattner3822f632009-01-02 08:05:26 +00001151/// ParseStringConstant
1152/// ::= StringConstant
1153bool LLParser::ParseStringConstant(std::string &Result) {
1154 if (Lex.getKind() != lltok::StringConstant)
1155 return TokError("expected string constant");
1156 Result = Lex.getStrVal();
1157 Lex.Lex();
1158 return false;
1159}
1160
1161/// ParseUInt32
1162/// ::= uint32
1163bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001164 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1165 return TokError("expected integer");
1166 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1167 if (Val64 != unsigned(Val64))
1168 return TokError("expected 32-bit integer (too large)");
1169 Val = Val64;
1170 Lex.Lex();
1171 return false;
1172}
1173
Hal Finkelb0407ba2014-07-18 15:51:28 +00001174/// ParseUInt64
1175/// ::= uint64
1176bool LLParser::ParseUInt64(uint64_t &Val) {
1177 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1178 return TokError("expected integer");
1179 Val = Lex.getAPSIntVal().getLimitedValue();
1180 Lex.Lex();
1181 return false;
1182}
1183
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001184/// ParseTLSModel
1185/// := 'localdynamic'
1186/// := 'initialexec'
1187/// := 'localexec'
1188bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1189 switch (Lex.getKind()) {
1190 default:
1191 return TokError("expected localdynamic, initialexec or localexec");
1192 case lltok::kw_localdynamic:
1193 TLM = GlobalVariable::LocalDynamicTLSModel;
1194 break;
1195 case lltok::kw_initialexec:
1196 TLM = GlobalVariable::InitialExecTLSModel;
1197 break;
1198 case lltok::kw_localexec:
1199 TLM = GlobalVariable::LocalExecTLSModel;
1200 break;
1201 }
1202
1203 Lex.Lex();
1204 return false;
1205}
1206
1207/// ParseOptionalThreadLocal
1208/// := /*empty*/
1209/// := 'thread_local'
1210/// := 'thread_local' '(' tlsmodel ')'
1211bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1212 TLM = GlobalVariable::NotThreadLocal;
1213 if (!EatIfPresent(lltok::kw_thread_local))
1214 return false;
1215
1216 TLM = GlobalVariable::GeneralDynamicTLSModel;
1217 if (Lex.getKind() == lltok::lparen) {
1218 Lex.Lex();
1219 return ParseTLSModel(TLM) ||
1220 ParseToken(lltok::rparen, "expected ')' after thread local model");
1221 }
1222 return false;
1223}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224
1225/// ParseOptionalAddrSpace
1226/// := /*empty*/
1227/// := 'addrspace' '(' uint32 ')'
1228bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1229 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001230 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001233 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001234 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001235}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001236
Bill Wendling34c2eb22012-12-04 23:40:58 +00001237/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1238bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1239 bool HaveError = false;
1240
1241 B.clear();
1242
1243 while (1) {
1244 lltok::Kind Token = Lex.getKind();
1245 switch (Token) {
1246 default: // End of attributes.
1247 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001248 case lltok::kw_align: {
1249 unsigned Alignment;
1250 if (ParseOptionalAlignment(Alignment))
1251 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001252 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001253 continue;
1254 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001255 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001256 case lltok::kw_dereferenceable: {
1257 uint64_t Bytes;
1258 if (ParseOptionalDereferenceableBytes(Bytes))
1259 return true;
1260 B.addDereferenceableAttr(Bytes);
1261 continue;
1262 }
Reid Klecknera534a382013-12-19 02:14:12 +00001263 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001264 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1265 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1266 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1267 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001268 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001269 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1270 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001271 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001272 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1273 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1274 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001275
Stephen Lin7577ed52013-04-20 13:16:13 +00001276 case lltok::kw_alignstack:
1277 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001278 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001279 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001280 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001281 case lltok::kw_minsize:
1282 case lltok::kw_naked:
1283 case lltok::kw_nobuiltin:
1284 case lltok::kw_noduplicate:
1285 case lltok::kw_noimplicitfloat:
1286 case lltok::kw_noinline:
1287 case lltok::kw_nonlazybind:
1288 case lltok::kw_noredzone:
1289 case lltok::kw_noreturn:
1290 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001291 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001292 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001293 case lltok::kw_returns_twice:
1294 case lltok::kw_sanitize_address:
1295 case lltok::kw_sanitize_memory:
1296 case lltok::kw_sanitize_thread:
1297 case lltok::kw_ssp:
1298 case lltok::kw_sspreq:
1299 case lltok::kw_sspstrong:
1300 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001301 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1302 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001303 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001304
Bill Wendling34c2eb22012-12-04 23:40:58 +00001305 Lex.Lex();
1306 }
1307}
1308
1309/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1310bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1311 bool HaveError = false;
1312
1313 B.clear();
1314
1315 while (1) {
1316 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001317 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001318 default: // End of attributes.
1319 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001320 case lltok::kw_dereferenceable: {
1321 uint64_t Bytes;
1322 if (ParseOptionalDereferenceableBytes(Bytes))
1323 return true;
1324 B.addDereferenceableAttr(Bytes);
1325 continue;
1326 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001327 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1328 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001329 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001330 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1331 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001332
Bill Wendling34c2eb22012-12-04 23:40:58 +00001333 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001334 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001335 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001336 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001337 case lltok::kw_nest:
1338 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001339 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001340 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001341 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001342 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001343
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001344 case lltok::kw_alignstack:
1345 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001346 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001347 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001348 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001349 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001350 case lltok::kw_minsize:
1351 case lltok::kw_naked:
1352 case lltok::kw_nobuiltin:
1353 case lltok::kw_noduplicate:
1354 case lltok::kw_noimplicitfloat:
1355 case lltok::kw_noinline:
1356 case lltok::kw_nonlazybind:
1357 case lltok::kw_noredzone:
1358 case lltok::kw_noreturn:
1359 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001360 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001361 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001362 case lltok::kw_returns_twice:
1363 case lltok::kw_sanitize_address:
1364 case lltok::kw_sanitize_memory:
1365 case lltok::kw_sanitize_thread:
1366 case lltok::kw_ssp:
1367 case lltok::kw_sspreq:
1368 case lltok::kw_sspstrong:
1369 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001370 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001371 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001372
1373 case lltok::kw_readnone:
1374 case lltok::kw_readonly:
1375 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001376 }
1377
Chris Lattnerac161bf2009-01-02 07:01:27 +00001378 Lex.Lex();
1379 }
1380}
1381
1382/// ParseOptionalLinkage
1383/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001384/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385/// ::= 'internal'
1386/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001387/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001388/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001389/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001390/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001392/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001393/// ::= 'extern_weak'
1394/// ::= 'external'
1395bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1396 HasLinkage = false;
1397 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001398 default: Res=GlobalValue::ExternalLinkage; return false;
1399 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001400 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1401 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1402 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1403 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1404 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001405 case lltok::kw_available_externally:
1406 Res = GlobalValue::AvailableExternallyLinkage;
1407 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001408 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001409 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001410 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1411 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001412 }
1413 Lex.Lex();
1414 HasLinkage = true;
1415 return false;
1416}
1417
1418/// ParseOptionalVisibility
1419/// ::= /*empty*/
1420/// ::= 'default'
1421/// ::= 'hidden'
1422/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001423///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001424bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1425 switch (Lex.getKind()) {
1426 default: Res = GlobalValue::DefaultVisibility; return false;
1427 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1428 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1429 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1430 }
1431 Lex.Lex();
1432 return false;
1433}
1434
Nico Rieck7157bb72014-01-14 15:22:47 +00001435/// ParseOptionalDLLStorageClass
1436/// ::= /*empty*/
1437/// ::= 'dllimport'
1438/// ::= 'dllexport'
1439///
1440bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1441 switch (Lex.getKind()) {
1442 default: Res = GlobalValue::DefaultStorageClass; return false;
1443 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1444 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1445 }
1446 Lex.Lex();
1447 return false;
1448}
1449
Chris Lattnerac161bf2009-01-02 07:01:27 +00001450/// ParseOptionalCallingConv
1451/// ::= /*empty*/
1452/// ::= 'ccc'
1453/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001454/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001455/// ::= 'coldcc'
1456/// ::= 'x86_stdcallcc'
1457/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001458/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001459/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001460/// ::= 'arm_apcscc'
1461/// ::= 'arm_aapcscc'
1462/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001463/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001464/// ::= 'ptx_kernel'
1465/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001466/// ::= 'spir_func'
1467/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001468/// ::= 'x86_64_sysvcc'
1469/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001470/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001471/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001472/// ::= 'preserve_mostcc'
1473/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001474/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001475/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001476///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001477bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001478 switch (Lex.getKind()) {
1479 default: CC = CallingConv::C; return false;
1480 case lltok::kw_ccc: CC = CallingConv::C; break;
1481 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1482 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1483 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1484 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001485 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001486 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001487 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1488 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1489 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001490 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001491 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1492 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001493 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1494 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001495 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001496 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1497 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001498 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001499 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001500 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1501 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001502 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001503 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001504 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001505 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001506 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001507 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001508
Chris Lattnerac161bf2009-01-02 07:01:27 +00001509 Lex.Lex();
1510 return false;
1511}
1512
Chris Lattner5c427632009-12-30 05:31:19 +00001513/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001514/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001515bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1516 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001517 do {
1518 if (Lex.getKind() != lltok::MetadataVar)
1519 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001520
Chris Lattner596760d2009-12-29 21:25:40 +00001521 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001522 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001523 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001524
Chris Lattner1797fc72009-12-29 21:53:55 +00001525 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001526 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001527
1528 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001529 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001530
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001531 // This code is similar to that of ParseMetadata, however it needs to
Dan Gohmanf0715b12010-08-24 14:35:45 +00001532 // have special-case code for a forward reference; see the comments on
1533 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1534 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001535 if (Lex.getKind() == lltok::lbrace) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001536 MDNode *N;
1537 if (ParseMDNode(N))
Dan Gohmanc828c542010-08-24 02:24:03 +00001538 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001539 Inst->setMetadata(MDK, N);
Chris Lattner8eff0152010-04-01 05:14:45 +00001540 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001541 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001542 if (ParseMDNodeID(Node, NodeID))
1543 return true;
1544 if (Node) {
1545 // If we got the node, add it to the instruction.
1546 Inst->setMetadata(MDK, Node);
1547 } else {
1548 MDRef R = { Loc, MDK, NodeID };
1549 // Otherwise, remember that this should be resolved later.
1550 ForwardRefInstMetadata[Inst].push_back(R);
1551 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001552 }
Chris Lattner596760d2009-12-29 21:25:40 +00001553
Manman Ren209b17c2013-09-28 00:22:27 +00001554 if (MDK == LLVMContext::MD_tbaa)
1555 InstsWithTBAATag.push_back(Inst);
1556
Chris Lattner596760d2009-12-29 21:25:40 +00001557 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001558 } while (EatIfPresent(lltok::comma));
1559 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001560}
1561
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562/// ParseOptionalAlignment
1563/// ::= /* empty */
1564/// ::= 'align' 4
1565bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1566 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001567 if (!EatIfPresent(lltok::kw_align))
1568 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001569 LocTy AlignLoc = Lex.getLoc();
1570 if (ParseUInt32(Alignment)) return true;
1571 if (!isPowerOf2_32(Alignment))
1572 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001573 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001574 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001575 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001576}
1577
Hal Finkelb0407ba2014-07-18 15:51:28 +00001578/// ParseOptionalDereferenceableBytes
1579/// ::= /* empty */
1580/// ::= 'dereferenceable' '(' 4 ')'
1581bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1582 Bytes = 0;
1583 if (!EatIfPresent(lltok::kw_dereferenceable))
1584 return false;
1585 LocTy ParenLoc = Lex.getLoc();
1586 if (!EatIfPresent(lltok::lparen))
1587 return Error(ParenLoc, "expected '('");
1588 LocTy DerefLoc = Lex.getLoc();
1589 if (ParseUInt64(Bytes)) return true;
1590 ParenLoc = Lex.getLoc();
1591 if (!EatIfPresent(lltok::rparen))
1592 return Error(ParenLoc, "expected ')'");
1593 if (!Bytes)
1594 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1595 return false;
1596}
1597
Chris Lattnerb2f39502009-12-30 05:44:30 +00001598/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001599/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001600/// ::= ',' align 4
1601///
1602/// This returns with AteExtraComma set to true if it ate an excess comma at the
1603/// end.
1604bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1605 bool &AteExtraComma) {
1606 AteExtraComma = false;
1607 while (EatIfPresent(lltok::comma)) {
1608 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001609 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001610 AteExtraComma = true;
1611 return false;
1612 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001613
Chris Lattner95b0ff42010-04-23 00:50:50 +00001614 if (Lex.getKind() != lltok::kw_align)
1615 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001616
Chris Lattner95b0ff42010-04-23 00:50:50 +00001617 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001619
Devang Patelea8a4b92009-09-17 23:04:48 +00001620 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621}
1622
Eli Friedmanfee02c62011-07-25 23:16:38 +00001623/// ParseScopeAndOrdering
1624/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1625/// else: ::=
1626///
1627/// This sets Scope and Ordering to the parsed values.
1628bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1629 AtomicOrdering &Ordering) {
1630 if (!isAtomic)
1631 return false;
1632
1633 Scope = CrossThread;
1634 if (EatIfPresent(lltok::kw_singlethread))
1635 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001636
1637 return ParseOrdering(Ordering);
1638}
1639
1640/// ParseOrdering
1641/// ::= AtomicOrdering
1642///
1643/// This sets Ordering to the parsed value.
1644bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001645 switch (Lex.getKind()) {
1646 default: return TokError("Expected ordering on atomic instruction");
1647 case lltok::kw_unordered: Ordering = Unordered; break;
1648 case lltok::kw_monotonic: Ordering = Monotonic; break;
1649 case lltok::kw_acquire: Ordering = Acquire; break;
1650 case lltok::kw_release: Ordering = Release; break;
1651 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1652 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1653 }
1654 Lex.Lex();
1655 return false;
1656}
1657
Charles Davisbe5557e2010-02-12 00:31:15 +00001658/// ParseOptionalStackAlignment
1659/// ::= /* empty */
1660/// ::= 'alignstack' '(' 4 ')'
1661bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1662 Alignment = 0;
1663 if (!EatIfPresent(lltok::kw_alignstack))
1664 return false;
1665 LocTy ParenLoc = Lex.getLoc();
1666 if (!EatIfPresent(lltok::lparen))
1667 return Error(ParenLoc, "expected '('");
1668 LocTy AlignLoc = Lex.getLoc();
1669 if (ParseUInt32(Alignment)) return true;
1670 ParenLoc = Lex.getLoc();
1671 if (!EatIfPresent(lltok::rparen))
1672 return Error(ParenLoc, "expected ')'");
1673 if (!isPowerOf2_32(Alignment))
1674 return Error(AlignLoc, "stack alignment is not a power of two");
1675 return false;
1676}
Devang Patelea8a4b92009-09-17 23:04:48 +00001677
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001678/// ParseIndexList - This parses the index list for an insert/extractvalue
1679/// instruction. This sets AteExtraComma in the case where we eat an extra
1680/// comma at the end of the line and find that it is followed by metadata.
1681/// Clients that don't allow metadata can call the version of this function that
1682/// only takes one argument.
1683///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001684/// ParseIndexList
1685/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001686///
1687bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1688 bool &AteExtraComma) {
1689 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001690
Chris Lattnerac161bf2009-01-02 07:01:27 +00001691 if (Lex.getKind() != lltok::comma)
1692 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001693
Chris Lattner3822f632009-01-02 08:05:26 +00001694 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001695 if (Lex.getKind() == lltok::MetadataVar) {
1696 AteExtraComma = true;
1697 return false;
1698 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001699 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001700 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701 Indices.push_back(Idx);
1702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001703
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704 return false;
1705}
1706
1707//===----------------------------------------------------------------------===//
1708// Type Parsing.
1709//===----------------------------------------------------------------------===//
1710
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001712bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001714 switch (Lex.getKind()) {
1715 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001716 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001717 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001718 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001720 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001721 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001723 // Type ::= StructType
1724 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 return true;
1726 break;
1727 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001728 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729 Lex.Lex(); // eat the lsquare.
1730 if (ParseArrayVectorType(Result, false))
1731 return true;
1732 break;
1733 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001734 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001735 Lex.Lex();
1736 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001737 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001738 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740 } else if (ParseArrayVectorType(Result, true))
1741 return true;
1742 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 case lltok::LocalVar: {
1744 // Type ::= %foo
1745 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001746
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 // If the type hasn't been defined yet, create a forward definition and
1748 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001749 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001750 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 Lex.Lex();
1755 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001757
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001758 case lltok::LocalVarID: {
1759 // Type ::= %4
1760 if (Lex.getUIntVal() >= NumberedTypes.size())
1761 NumberedTypes.resize(Lex.getUIntVal()+1);
1762 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001763
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001764 // If the type hasn't been defined yet, create a forward definition and
1765 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001766 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001767 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001768 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001769 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001770 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 Lex.Lex();
1772 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 }
1774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001775
1776 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001777 while (1) {
1778 switch (Lex.getKind()) {
1779 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001780 default:
1781 if (!AllowVoid && Result->isVoidTy())
1782 return Error(TypeLoc, "void type only allowed for function results");
1783 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001785 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001786 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001787 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001788 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001789 if (Result->isVoidTy())
1790 return TokError("pointers to void are invalid - use i8* instead");
1791 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001792 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001794 Lex.Lex();
1795 break;
1796
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001798 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001799 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001800 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001801 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001802 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001803 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001804 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001805 unsigned AddrSpace;
1806 if (ParseOptionalAddrSpace(AddrSpace) ||
1807 ParseToken(lltok::star, "expected '*' in address space"))
1808 return true;
1809
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001810 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 break;
1812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001813
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1815 case lltok::lparen:
1816 if (ParseFunctionType(Result))
1817 return true;
1818 break;
1819 }
1820 }
1821}
1822
1823/// ParseParameterList
1824/// ::= '(' ')'
1825/// ::= '(' Arg (',' Arg)* ')'
1826/// Arg
1827/// ::= Type OptionalAttributes Value OptionalAttributes
1828bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001829 PerFunctionState &PFS, bool IsMustTailCall,
1830 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 if (ParseToken(lltok::lparen, "expected '(' in call"))
1832 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001833
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001834 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001835 while (Lex.getKind() != lltok::rparen) {
1836 // If this isn't the first argument, we need a comma.
1837 if (!ArgList.empty() &&
1838 ParseToken(lltok::comma, "expected ',' in argument list"))
1839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001840
Reid Kleckner83498642014-08-26 00:33:28 +00001841 // Parse an ellipsis if this is a musttail call in a variadic function.
1842 if (Lex.getKind() == lltok::dotdotdot) {
1843 const char *Msg = "unexpected ellipsis in argument list for ";
1844 if (!IsMustTailCall)
1845 return TokError(Twine(Msg) + "non-musttail call");
1846 if (!InVarArgsFunc)
1847 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1848 Lex.Lex(); // Lex the '...', it is purely for readability.
1849 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1850 }
1851
Chris Lattnerac161bf2009-01-02 07:01:27 +00001852 // Parse the argument.
1853 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001854 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001855 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001857 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001859
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001860 if (ArgTy->isMetadataTy()) {
1861 if (ParseMetadataAsValue(V, PFS))
1862 return true;
1863 } else {
1864 // Otherwise, handle normal operands.
1865 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1866 return true;
1867 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001868 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1869 AttrIndex++,
1870 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871 }
1872
Reid Kleckner83498642014-08-26 00:33:28 +00001873 if (IsMustTailCall && InVarArgsFunc)
1874 return TokError("expected '...' at end of argument list for musttail call "
1875 "in varargs function");
1876
Chris Lattnerac161bf2009-01-02 07:01:27 +00001877 Lex.Lex(); // Lex the ')'.
1878 return false;
1879}
1880
1881
1882
Chris Lattner2ed06b42009-01-05 18:34:07 +00001883/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001884/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885/// ::= '(' ArgTypeListI ')'
1886/// ArgTypeListI
1887/// ::= /*empty*/
1888/// ::= '...'
1889/// ::= ArgTypeList ',' '...'
1890/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001891///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1893 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 isVarArg = false;
1895 assert(Lex.getKind() == lltok::lparen);
1896 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001897
Chris Lattnerac161bf2009-01-02 07:01:27 +00001898 if (Lex.getKind() == lltok::rparen) {
1899 // empty
1900 } else if (Lex.getKind() == lltok::dotdotdot) {
1901 isVarArg = true;
1902 Lex.Lex();
1903 } else {
1904 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001905 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001906 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001909 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001910 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001911
Chris Lattnerfdd87902009-10-05 05:54:46 +00001912 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001913 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001914
Chris Lattnerdef19492011-06-17 06:36:20 +00001915 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001916 Name = Lex.getStrVal();
1917 Lex.Lex();
1918 }
Chris Lattner3822f632009-01-02 08:05:26 +00001919
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001920 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001921 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001922
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001923 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001924 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001925 AttributeSet::get(ArgTy->getContext(),
1926 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001927
Chris Lattner3822f632009-01-02 08:05:26 +00001928 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001930 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 break;
1933 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001934
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935 // Otherwise must be an argument type.
1936 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001937 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001938
Chris Lattnerfdd87902009-10-05 05:54:46 +00001939 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001940 return Error(TypeLoc, "argument can not have void type");
1941
Chris Lattnerdef19492011-06-17 06:36:20 +00001942 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943 Name = Lex.getStrVal();
1944 Lex.Lex();
1945 } else {
1946 Name = "";
1947 }
Chris Lattner3822f632009-01-02 08:05:26 +00001948
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001950 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001951
Bill Wendlingd079a442012-10-15 04:46:55 +00001952 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001953 AttributeSet::get(ArgTy->getContext(),
1954 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001955 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 }
1957 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Chris Lattner3822f632009-01-02 08:05:26 +00001959 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001960}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001961
Chris Lattnerac161bf2009-01-02 07:01:27 +00001962/// ParseFunctionType
1963/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001964bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 assert(Lex.getKind() == lltok::lparen);
1966
Chris Lattnerce473c72009-01-05 08:04:33 +00001967 if (!FunctionType::isValidReturnType(Result))
1968 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001972 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001974
Chris Lattnerac161bf2009-01-02 07:01:27 +00001975 // Reject names on the arguments lists.
1976 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1977 if (!ArgList[i].Name.empty())
1978 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001979 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001980 return Error(ArgList[i].Loc,
1981 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001982 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001983
Jay Foadb804a2b2011-07-12 14:06:48 +00001984 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001986 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001987
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001988 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 return false;
1990}
1991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001992/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1993/// other structs.
1994bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1995 SmallVector<Type*, 8> Elts;
1996 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001997
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001998 Result = StructType::get(Context, Elts, Packed);
1999 return false;
2000}
2001
2002/// ParseStructDefinition - Parse a struct in a 'type' definition.
2003bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2004 std::pair<Type*, LocTy> &Entry,
2005 Type *&ResultTy) {
2006 // If the type was already defined, diagnose the redefinition.
2007 if (Entry.first && !Entry.second.isValid())
2008 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 // If we have opaque, just return without filling in the definition for the
2011 // struct. This counts as a definition as far as the .ll file goes.
2012 if (EatIfPresent(lltok::kw_opaque)) {
2013 // This type is being defined, so clear the location to indicate this.
2014 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002016 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002017 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002018 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 ResultTy = Entry.first;
2020 return false;
2021 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002022
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023 // If the type starts with '<', then it is either a packed struct or a vector.
2024 bool isPacked = EatIfPresent(lltok::less);
2025
2026 // If we don't have a struct, then we have a random type alias, which we
2027 // accept for compatibility with old files. These types are not allowed to be
2028 // forward referenced and not allowed to be recursive.
2029 if (Lex.getKind() != lltok::lbrace) {
2030 if (Entry.first)
2031 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002032
Craig Topper2617dcc2014-04-15 06:32:26 +00002033 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 if (isPacked)
2035 return ParseArrayVectorType(ResultTy, true);
2036 return ParseType(ResultTy);
2037 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002038
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002039 // This type is being defined, so clear the location to indicate this.
2040 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002041
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002043 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002044 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002045
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002046 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002047
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002048 SmallVector<Type*, 8> Body;
2049 if (ParseStructBody(Body) ||
2050 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2051 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002052
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 STy->setBody(Body, isPacked);
2054 ResultTy = STy;
2055 return false;
2056}
2057
2058
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002062/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002063/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002064/// ::= '<' '{' Type (',' Type)* '}' '>'
2065bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 assert(Lex.getKind() == lltok::lbrace);
2067 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002068
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 // Handle the empty struct.
2070 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072
Chris Lattnerf880ca22009-03-09 04:49:14 +00002073 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002074 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002075 if (ParseType(Ty)) return true;
2076 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002077
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002079 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002080
Chris Lattner3822f632009-01-02 08:05:26 +00002081 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002082 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002084
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002085 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002086 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002090
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092}
2093
2094/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2095/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002096/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002097/// ::= '[' APSINTVAL 'x' Types ']'
2098/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002099bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2101 Lex.getAPSIntVal().getBitWidth() > 64)
2102 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 LocTy SizeLoc = Lex.getLoc();
2105 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002106 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002107
Chris Lattner3822f632009-01-02 08:05:26 +00002108 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2109 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110
2111 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002112 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002114
Chris Lattner3822f632009-01-02 08:05:26 +00002115 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2116 "expected end of sequential type"))
2117 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002118
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002120 if (Size == 0)
2121 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 if ((unsigned)Size != Size)
2123 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002124 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002125 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002126 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002128 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002130 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002131 }
2132 return false;
2133}
2134
2135//===----------------------------------------------------------------------===//
2136// Function Semantic Analysis.
2137//===----------------------------------------------------------------------===//
2138
Chris Lattner3432c622009-10-28 03:39:23 +00002139LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2140 int functionNumber)
2141 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142
2143 // Insert unnamed arguments into the NumberedVals list.
2144 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2145 AI != E; ++AI)
2146 if (!AI->hasName())
2147 NumberedVals.push_back(AI);
2148}
2149
2150LLParser::PerFunctionState::~PerFunctionState() {
2151 // If there were any forward referenced non-basicblock values, delete them.
2152 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2153 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2154 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002155 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002156 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002158 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002160
Chris Lattnerac161bf2009-01-02 07:01:27 +00002161 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2162 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2163 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002164 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002165 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002166 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002167 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 }
2169}
2170
Chris Lattner3432c622009-10-28 03:39:23 +00002171bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 if (!ForwardRefVals.empty())
2173 return P.Error(ForwardRefVals.begin()->second.second,
2174 "use of undefined value '%" + ForwardRefVals.begin()->first +
2175 "'");
2176 if (!ForwardRefValIDs.empty())
2177 return P.Error(ForwardRefValIDs.begin()->second.second,
2178 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002179 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 return false;
2181}
2182
2183
2184/// GetVal - Get a value with the specified name or ID, creating a
2185/// forward reference record if needed. This can return null if the value
2186/// exists but does not have the right type.
2187Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002188 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002189 // Look this name up in the normal function symbol table.
2190 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002191
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 // If this is a forward reference for the value, see if we already created a
2193 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002194 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2196 I = ForwardRefVals.find(Name);
2197 if (I != ForwardRefVals.end())
2198 Val = I->second.first;
2199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 // If we have the value in the symbol table or fwd-ref table, return it.
2202 if (Val) {
2203 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002204 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 P.Error(Loc, "'%" + Name + "' is not a basic block");
2206 else
2207 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002208 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002209 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002213 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002215 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002217
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218 // Otherwise, create a new forward reference for this value and remember it.
2219 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002220 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002221 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 else
2223 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2226 return FwdVal;
2227}
2228
Chris Lattner229907c2011-07-18 04:54:35 +00002229Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002230 LocTy Loc) {
2231 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002232 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 // If this is a forward reference for the value, see if we already created a
2235 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002236 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2238 I = ForwardRefValIDs.find(ID);
2239 if (I != ForwardRefValIDs.end())
2240 Val = I->second.first;
2241 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002242
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 // If we have the value in the symbol table or fwd-ref table, return it.
2244 if (Val) {
2245 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002246 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002247 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002249 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002250 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002251 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002254 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002256 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002258
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 // Otherwise, create a new forward reference for this value and remember it.
2260 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002261 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002262 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 else
2264 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265
Chris Lattnerac161bf2009-01-02 07:01:27 +00002266 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2267 return FwdVal;
2268}
2269
2270/// SetInstName - After an instruction is parsed and inserted into its
2271/// basic block, this installs its name.
2272bool LLParser::PerFunctionState::SetInstName(int NameID,
2273 const std::string &NameStr,
2274 LocTy NameLoc, Instruction *Inst) {
2275 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002276 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277 if (NameID != -1 || !NameStr.empty())
2278 return P.Error(NameLoc, "instructions returning void cannot have a name");
2279 return false;
2280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 // If this was a numbered instruction, verify that the instruction is the
2283 // expected value and resolve any forward references.
2284 if (NameStr.empty()) {
2285 // If neither a name nor an ID was specified, just use the next ID.
2286 if (NameID == -1)
2287 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002288
Chris Lattnerac161bf2009-01-02 07:01:27 +00002289 if (unsigned(NameID) != NumberedVals.size())
2290 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002291 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002292
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2294 ForwardRefValIDs.find(NameID);
2295 if (FI != ForwardRefValIDs.end()) {
2296 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002297 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002298 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002300 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301 ForwardRefValIDs.erase(FI);
2302 }
2303
2304 NumberedVals.push_back(Inst);
2305 return false;
2306 }
2307
2308 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2309 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2310 FI = ForwardRefVals.find(NameStr);
2311 if (FI != ForwardRefVals.end()) {
2312 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002313 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002314 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002316 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 ForwardRefVals.erase(FI);
2318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002319
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 // Set the name on the instruction.
2321 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002323 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002324 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 NameStr + "'");
2326 return false;
2327}
2328
2329/// GetBB - Get a basic block with the specified name or ID, creating a
2330/// forward reference record if needed.
2331BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2332 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002333 return cast_or_null<BasicBlock>(GetVal(Name,
2334 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335}
2336
2337BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002338 return cast_or_null<BasicBlock>(GetVal(ID,
2339 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002340}
2341
2342/// DefineBB - Define the specified basic block, which is either named or
2343/// unnamed. If there is an error, this returns null otherwise it returns
2344/// the block being defined.
2345BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2346 LocTy Loc) {
2347 BasicBlock *BB;
2348 if (Name.empty())
2349 BB = GetBB(NumberedVals.size(), Loc);
2350 else
2351 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002352 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002353
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 // Move the block to the end of the function. Forward ref'd blocks are
2355 // inserted wherever they happen to be referenced.
2356 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002357
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 // Remove the block from forward ref sets.
2359 if (Name.empty()) {
2360 ForwardRefValIDs.erase(NumberedVals.size());
2361 NumberedVals.push_back(BB);
2362 } else {
2363 // BB forward references are already in the function symbol table.
2364 ForwardRefVals.erase(Name);
2365 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002366
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367 return BB;
2368}
2369
2370//===----------------------------------------------------------------------===//
2371// Constants.
2372//===----------------------------------------------------------------------===//
2373
2374/// ParseValID - Parse an abstract value that doesn't necessarily have a
2375/// type implied. For example, if we parse "4" we don't know what integer type
2376/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002377/// sanity. PFS is used to convert function-local operands of metadata (since
2378/// metadata operands are not just parsed here but also converted to values).
2379/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002380bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002381 ID.Loc = Lex.getLoc();
2382 switch (Lex.getKind()) {
2383 default: return TokError("expected value token");
2384 case lltok::GlobalID: // @42
2385 ID.UIntVal = Lex.getUIntVal();
2386 ID.Kind = ValID::t_GlobalID;
2387 break;
2388 case lltok::GlobalVar: // @foo
2389 ID.StrVal = Lex.getStrVal();
2390 ID.Kind = ValID::t_GlobalName;
2391 break;
2392 case lltok::LocalVarID: // %42
2393 ID.UIntVal = Lex.getUIntVal();
2394 ID.Kind = ValID::t_LocalID;
2395 break;
2396 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 ID.StrVal = Lex.getStrVal();
2398 ID.Kind = ValID::t_LocalName;
2399 break;
2400 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 ID.Kind = ValID::t_APSInt;
2403 break;
2404 case lltok::APFloat:
2405 ID.APFloatVal = Lex.getAPFloatVal();
2406 ID.Kind = ValID::t_APFloat;
2407 break;
2408 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002409 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 ID.Kind = ValID::t_Constant;
2411 break;
2412 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002413 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 ID.Kind = ValID::t_Constant;
2415 break;
2416 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2417 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2418 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002419
Chris Lattnerac161bf2009-01-02 07:01:27 +00002420 case lltok::lbrace: {
2421 // ValID ::= '{' ConstVector '}'
2422 Lex.Lex();
2423 SmallVector<Constant*, 16> Elts;
2424 if (ParseGlobalValueVector(Elts) ||
2425 ParseToken(lltok::rbrace, "expected end of struct constant"))
2426 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002427
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002428 ID.ConstantStructElts = new Constant*[Elts.size()];
2429 ID.UIntVal = Elts.size();
2430 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2431 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 return false;
2433 }
2434 case lltok::less: {
2435 // ValID ::= '<' ConstVector '>' --> Vector.
2436 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2437 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002438 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002439
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 SmallVector<Constant*, 16> Elts;
2441 LocTy FirstEltLoc = Lex.getLoc();
2442 if (ParseGlobalValueVector(Elts) ||
2443 (isPackedStruct &&
2444 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2445 ParseToken(lltok::greater, "expected end of constant"))
2446 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002447
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002449 ID.ConstantStructElts = new Constant*[Elts.size()];
2450 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2451 ID.UIntVal = Elts.size();
2452 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 return false;
2454 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002455
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 if (Elts.empty())
2457 return Error(ID.Loc, "constant vector must not be empty");
2458
Duncan Sands9dff9be2010-02-15 16:12:20 +00002459 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002460 !Elts[0]->getType()->isFloatingPointTy() &&
2461 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002463 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002464
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 // Verify that all the vector elements have the same type.
2466 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2467 if (Elts[i]->getType() != Elts[0]->getType())
2468 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002469 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002470 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002471
Chris Lattner69229312011-02-15 00:14:00 +00002472 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 ID.Kind = ValID::t_Constant;
2474 return false;
2475 }
2476 case lltok::lsquare: { // Array Constant
2477 Lex.Lex();
2478 SmallVector<Constant*, 16> Elts;
2479 LocTy FirstEltLoc = Lex.getLoc();
2480 if (ParseGlobalValueVector(Elts) ||
2481 ParseToken(lltok::rsquare, "expected end of array constant"))
2482 return true;
2483
2484 // Handle empty element.
2485 if (Elts.empty()) {
2486 // Use undef instead of an array because it's inconvenient to determine
2487 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002488 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 return false;
2490 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002493 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002494 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002495
Owen Anderson4056ca92009-07-29 22:17:13 +00002496 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002497
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002499 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 if (Elts[i]->getType() != Elts[0]->getType())
2501 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002502 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002503 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505
Jay Foad83be3612011-06-22 09:24:39 +00002506 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 ID.Kind = ValID::t_Constant;
2508 return false;
2509 }
2510 case lltok::kw_c: // c "foo"
2511 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002512 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2513 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002514 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2515 ID.Kind = ValID::t_Constant;
2516 return false;
2517
2518 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002519 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2520 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002521 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 Lex.Lex();
2523 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002524 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002525 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002526 ParseStringConstant(ID.StrVal) ||
2527 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 ParseToken(lltok::StringConstant, "expected constraint string"))
2529 return true;
2530 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002531 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002532 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 ID.Kind = ValID::t_InlineAsm;
2534 return false;
2535 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536
Chris Lattner3432c622009-10-28 03:39:23 +00002537 case lltok::kw_blockaddress: {
2538 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2539 Lex.Lex();
2540
2541 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002542
Chris Lattner3432c622009-10-28 03:39:23 +00002543 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2544 ParseValID(Fn) ||
2545 ParseToken(lltok::comma, "expected comma in block address expression")||
2546 ParseValID(Label) ||
2547 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2548 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002549
Chris Lattner3432c622009-10-28 03:39:23 +00002550 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2551 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002552 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002553 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002554
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002555 // Try to find the function (but skip it if it's forward-referenced).
2556 GlobalValue *GV = nullptr;
2557 if (Fn.Kind == ValID::t_GlobalID) {
2558 if (Fn.UIntVal < NumberedVals.size())
2559 GV = NumberedVals[Fn.UIntVal];
2560 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2561 GV = M->getNamedValue(Fn.StrVal);
2562 }
2563 Function *F = nullptr;
2564 if (GV) {
2565 // Confirm that it's actually a function with a definition.
2566 if (!isa<Function>(GV))
2567 return Error(Fn.Loc, "expected function name in blockaddress");
2568 F = cast<Function>(GV);
2569 if (F->isDeclaration())
2570 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2571 }
2572
2573 if (!F) {
2574 // Make a global variable as a placeholder for this reference.
2575 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2576 if (!FwdRef)
2577 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2578 GlobalValue::InternalLinkage, nullptr, "");
2579 ID.ConstantVal = FwdRef;
2580 ID.Kind = ValID::t_Constant;
2581 return false;
2582 }
2583
2584 // We found the function; now find the basic block. Don't use PFS, since we
2585 // might be inside a constant expression.
2586 BasicBlock *BB;
2587 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2588 if (Label.Kind == ValID::t_LocalID)
2589 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2590 else
2591 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2592 if (!BB)
2593 return Error(Label.Loc, "referenced value is not a basic block");
2594 } else {
2595 if (Label.Kind == ValID::t_LocalID)
2596 return Error(Label.Loc, "cannot take address of numeric label after "
2597 "the function is defined");
2598 BB = dyn_cast_or_null<BasicBlock>(
2599 F->getValueSymbolTable().lookup(Label.StrVal));
2600 if (!BB)
2601 return Error(Label.Loc, "referenced value is not a basic block");
2602 }
2603
2604 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002605 ID.Kind = ValID::t_Constant;
2606 return false;
2607 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002608
Chris Lattnerac161bf2009-01-02 07:01:27 +00002609 case lltok::kw_trunc:
2610 case lltok::kw_zext:
2611 case lltok::kw_sext:
2612 case lltok::kw_fptrunc:
2613 case lltok::kw_fpext:
2614 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002615 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002616 case lltok::kw_uitofp:
2617 case lltok::kw_sitofp:
2618 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002619 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002621 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002623 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 Constant *SrcVal;
2625 Lex.Lex();
2626 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2627 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002628 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002629 ParseType(DestTy) ||
2630 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2631 return true;
2632 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2633 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002634 getTypeString(SrcVal->getType()) + "' to '" +
2635 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002637 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 ID.Kind = ValID::t_Constant;
2639 return false;
2640 }
2641 case lltok::kw_extractvalue: {
2642 Lex.Lex();
2643 Constant *Val;
2644 SmallVector<unsigned, 4> Indices;
2645 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2646 ParseGlobalTypeAndValue(Val) ||
2647 ParseIndexList(Indices) ||
2648 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2649 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002650
Chris Lattner392be582010-02-12 20:49:41 +00002651 if (!Val->getType()->isAggregateType())
2652 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002653 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002655 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656 ID.Kind = ValID::t_Constant;
2657 return false;
2658 }
2659 case lltok::kw_insertvalue: {
2660 Lex.Lex();
2661 Constant *Val0, *Val1;
2662 SmallVector<unsigned, 4> Indices;
2663 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2664 ParseGlobalTypeAndValue(Val0) ||
2665 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2666 ParseGlobalTypeAndValue(Val1) ||
2667 ParseIndexList(Indices) ||
2668 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2669 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002670 if (!Val0->getType()->isAggregateType())
2671 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002672 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002673 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002674 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 ID.Kind = ValID::t_Constant;
2676 return false;
2677 }
2678 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002679 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 unsigned PredVal, Opc = Lex.getUIntVal();
2681 Constant *Val0, *Val1;
2682 Lex.Lex();
2683 if (ParseCmpPredicate(PredVal, Opc) ||
2684 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2685 ParseGlobalTypeAndValue(Val0) ||
2686 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2687 ParseGlobalTypeAndValue(Val1) ||
2688 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2689 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 if (Val0->getType() != Val1->getType())
2692 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002695
Chris Lattnerac161bf2009-01-02 07:01:27 +00002696 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002697 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002699 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002700 } else {
2701 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002702 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002703 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002705 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 }
2707 ID.Kind = ValID::t_Constant;
2708 return false;
2709 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002710
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 // Binary Operators.
2712 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002713 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002714 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002715 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002717 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002718 case lltok::kw_udiv:
2719 case lltok::kw_sdiv:
2720 case lltok::kw_fdiv:
2721 case lltok::kw_urem:
2722 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002723 case lltok::kw_frem:
2724 case lltok::kw_shl:
2725 case lltok::kw_lshr:
2726 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002727 bool NUW = false;
2728 bool NSW = false;
2729 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730 unsigned Opc = Lex.getUIntVal();
2731 Constant *Val0, *Val1;
2732 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002733 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002734 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2735 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002736 if (EatIfPresent(lltok::kw_nuw))
2737 NUW = true;
2738 if (EatIfPresent(lltok::kw_nsw)) {
2739 NSW = true;
2740 if (EatIfPresent(lltok::kw_nuw))
2741 NUW = true;
2742 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002743 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2744 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002745 if (EatIfPresent(lltok::kw_exact))
2746 Exact = true;
2747 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002748 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2749 ParseGlobalTypeAndValue(Val0) ||
2750 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2751 ParseGlobalTypeAndValue(Val1) ||
2752 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2753 return true;
2754 if (Val0->getType() != Val1->getType())
2755 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002756 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002757 if (NUW)
2758 return Error(ModifierLoc, "nuw only applies to integer operations");
2759 if (NSW)
2760 return Error(ModifierLoc, "nsw only applies to integer operations");
2761 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002762 // Check that the type is valid for the operator.
2763 switch (Opc) {
2764 case Instruction::Add:
2765 case Instruction::Sub:
2766 case Instruction::Mul:
2767 case Instruction::UDiv:
2768 case Instruction::SDiv:
2769 case Instruction::URem:
2770 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002771 case Instruction::Shl:
2772 case Instruction::AShr:
2773 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002774 if (!Val0->getType()->isIntOrIntVectorTy())
2775 return Error(ID.Loc, "constexpr requires integer operands");
2776 break;
2777 case Instruction::FAdd:
2778 case Instruction::FSub:
2779 case Instruction::FMul:
2780 case Instruction::FDiv:
2781 case Instruction::FRem:
2782 if (!Val0->getType()->isFPOrFPVectorTy())
2783 return Error(ID.Loc, "constexpr requires fp operands");
2784 break;
2785 default: llvm_unreachable("Unknown binary operator!");
2786 }
Dan Gohman1b849082009-09-07 23:54:19 +00002787 unsigned Flags = 0;
2788 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2789 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002790 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002791 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002792 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 ID.Kind = ValID::t_Constant;
2794 return false;
2795 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002796
Chris Lattnerac161bf2009-01-02 07:01:27 +00002797 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002798 case lltok::kw_and:
2799 case lltok::kw_or:
2800 case lltok::kw_xor: {
2801 unsigned Opc = Lex.getUIntVal();
2802 Constant *Val0, *Val1;
2803 Lex.Lex();
2804 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2805 ParseGlobalTypeAndValue(Val0) ||
2806 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2807 ParseGlobalTypeAndValue(Val1) ||
2808 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2809 return true;
2810 if (Val0->getType() != Val1->getType())
2811 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002812 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 return Error(ID.Loc,
2814 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002815 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002816 ID.Kind = ValID::t_Constant;
2817 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002818 }
2819
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 case lltok::kw_getelementptr:
2821 case lltok::kw_shufflevector:
2822 case lltok::kw_insertelement:
2823 case lltok::kw_extractelement:
2824 case lltok::kw_select: {
2825 unsigned Opc = Lex.getUIntVal();
2826 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002827 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002829 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002830 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2832 ParseGlobalValueVector(Elts) ||
2833 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2834 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002835
Chris Lattnerac161bf2009-01-02 07:01:27 +00002836 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002837 if (Elts.size() == 0 ||
2838 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002839 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Jay Foaded8db7d2011-07-21 14:31:17 +00002841 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002842 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002844 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2845 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002846 } else if (Opc == Instruction::Select) {
2847 if (Elts.size() != 3)
2848 return Error(ID.Loc, "expected three operands to select");
2849 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2850 Elts[2]))
2851 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002852 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 } else if (Opc == Instruction::ShuffleVector) {
2854 if (Elts.size() != 3)
2855 return Error(ID.Loc, "expected three operands to shufflevector");
2856 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2857 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002858 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002859 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 } else if (Opc == Instruction::ExtractElement) {
2861 if (Elts.size() != 2)
2862 return Error(ID.Loc, "expected two operands to extractelement");
2863 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2864 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002865 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002866 } else {
2867 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2868 if (Elts.size() != 3)
2869 return Error(ID.Loc, "expected three operands to insertelement");
2870 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2871 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002872 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002873 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002874 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002875
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 ID.Kind = ValID::t_Constant;
2877 return false;
2878 }
2879 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002880
Chris Lattnerac161bf2009-01-02 07:01:27 +00002881 Lex.Lex();
2882 return false;
2883}
2884
2885/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002886bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002887 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002888 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002889 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002890 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002891 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002892 if (V && !(C = dyn_cast<Constant>(V)))
2893 return Error(ID.Loc, "global values must be constants");
2894 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002895}
2896
Victor Hernandez9d75c962010-01-11 22:31:58 +00002897bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002898 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002899 return ParseType(Ty) ||
2900 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002901}
2902
Rafael Espindola83a362c2015-01-06 22:55:16 +00002903bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002904 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002905
2906 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002907 if (!EatIfPresent(lltok::kw_comdat))
2908 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002909
2910 if (EatIfPresent(lltok::lparen)) {
2911 if (Lex.getKind() != lltok::ComdatVar)
2912 return TokError("expected comdat variable");
2913 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2914 Lex.Lex();
2915 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2916 return true;
2917 } else {
2918 if (GlobalName.empty())
2919 return TokError("comdat cannot be unnamed");
2920 C = getComdat(GlobalName, KwLoc);
2921 }
2922
David Majnemerdad0a642014-06-27 18:19:56 +00002923 return false;
2924}
2925
Victor Hernandez9d75c962010-01-11 22:31:58 +00002926/// ParseGlobalValueVector
2927/// ::= /*empty*/
2928/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002929bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002930 // Empty list.
2931 if (Lex.getKind() == lltok::rbrace ||
2932 Lex.getKind() == lltok::rsquare ||
2933 Lex.getKind() == lltok::greater ||
2934 Lex.getKind() == lltok::rparen)
2935 return false;
2936
2937 Constant *C;
2938 if (ParseGlobalTypeAndValue(C)) return true;
2939 Elts.push_back(C);
2940
2941 while (EatIfPresent(lltok::comma)) {
2942 if (ParseGlobalTypeAndValue(C)) return true;
2943 Elts.push_back(C);
2944 }
2945
2946 return false;
2947}
2948
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002949bool LLParser::ParseMDNode(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002950 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002951 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002952 return true;
2953
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002954 if (IsDistinct)
2955 MD = MDNode::getDistinct(Context, Elts);
2956 else
2957 MD = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002958 return false;
2959}
2960
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002961/// ParseMetadataAsValue
2962/// ::= metadata i32 %local
2963/// ::= metadata i32 @global
2964/// ::= metadata i32 7
2965/// ::= metadata !0
2966/// ::= metadata !{...}
2967/// ::= metadata !"string"
2968bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
2969 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002970 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002971 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002972 return true;
2973
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002974 V = MetadataAsValue::get(Context, MD);
2975 return false;
2976}
2977
2978/// ParseValueAsMetadata
2979/// ::= i32 %local
2980/// ::= i32 @global
2981/// ::= i32 7
2982bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
2983 Type *Ty;
2984 LocTy Loc;
2985 if (ParseType(Ty, "expected metadata operand", Loc))
2986 return true;
2987 if (Ty->isMetadataTy())
2988 return Error(Loc, "invalid metadata-value-metadata roundtrip");
2989
2990 Value *V;
2991 if (ParseValue(Ty, V, PFS))
2992 return true;
2993
2994 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002995 return false;
2996}
2997
2998/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002999/// ::= i32 %local
3000/// ::= i32 @global
3001/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003002/// ::= !42
3003/// ::= !{...}
3004/// ::= !"string"
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003005bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003006 // ValueAsMetadata:
3007 // <type> <value>
3008 if (Lex.getKind() != lltok::exclaim)
3009 return ParseValueAsMetadata(MD, PFS);
3010
3011 // '!'.
3012 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3013 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003014
3015 // MDNode:
3016 // !{ ... }
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003017 if (Lex.getKind() == lltok::lbrace) {
3018 MDNode *N;
3019 if (ParseMDNode(N))
3020 return true;
3021 MD = N;
3022 return false;
3023 }
Dan Gohman8939ba332010-07-14 18:26:50 +00003024
3025 // Standalone metadata reference
3026 // !42
3027 if (Lex.getKind() == lltok::APSInt) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003028 MDNode *N;
3029 if (ParseMDNodeID(N))
3030 return true;
3031 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003032 return false;
3033 }
3034
3035 // MDString:
3036 // ::= '!' STRINGCONSTANT
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003037 MDString *S;
3038 if (ParseMDString(S))
3039 return true;
3040 MD = S;
Dan Gohman8939ba332010-07-14 18:26:50 +00003041 return false;
3042}
3043
Victor Hernandez9d75c962010-01-11 22:31:58 +00003044
3045//===----------------------------------------------------------------------===//
3046// Function Parsing.
3047//===----------------------------------------------------------------------===//
3048
Chris Lattner229907c2011-07-18 04:54:35 +00003049bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003050 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003051 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003053
Chris Lattnerac161bf2009-01-02 07:01:27 +00003054 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003056 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3057 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003058 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003060 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3061 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003062 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003063 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003064 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003065 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003066 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003067 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3068 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003069 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003070 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003071 return false;
3072 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 case ValID::t_GlobalName:
3074 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003075 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003076 case ValID::t_GlobalID:
3077 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003078 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003080 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003081 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003082 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003083 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003084 return false;
3085 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003086 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3088 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003089
Dan Gohman518cda42011-12-17 00:04:22 +00003090 // The lexer has no type info, so builds all half, float, and double FP
3091 // constants as double. Fix this here. Long double does not need this.
3092 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003094 if (Ty->isHalfTy())
3095 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3096 &Ignored);
3097 else if (Ty->isFloatTy())
3098 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3099 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003100 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003101 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003102
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003103 if (V->getType() != Ty)
3104 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003105 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003106
Chris Lattnerac161bf2009-01-02 07:01:27 +00003107 return false;
3108 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003109 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003110 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003111 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112 return false;
3113 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003114 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003115 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003116 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003117 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003118 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003119 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003120 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003121 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003122 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003123 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003125 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003126 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003127 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003128 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129 return false;
3130 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003131 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003132 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003133
Chris Lattnerac161bf2009-01-02 07:01:27 +00003134 V = ID.ConstantVal;
3135 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003136 case ValID::t_ConstantStruct:
3137 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003138 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003139 if (ST->getNumElements() != ID.UIntVal)
3140 return Error(ID.Loc,
3141 "initializer with struct type has wrong # elements");
3142 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3143 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003144
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003145 // Verify that the elements are compatible with the structtype.
3146 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3147 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3148 return Error(ID.Loc, "element " + Twine(i) +
3149 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003150
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003151 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3152 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003153 } else
3154 return Error(ID.Loc, "constant expression type mismatch");
3155 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003156 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003157 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003159
Chris Lattner229907c2011-07-18 04:54:35 +00003160bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003161 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003162 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003163 return ParseValID(ID, PFS) ||
3164 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165}
3166
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003167bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003168 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003169 return ParseType(Ty) ||
3170 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003171}
3172
Chris Lattner3ed871f2009-10-27 19:13:16 +00003173bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3174 PerFunctionState &PFS) {
3175 Value *V;
3176 Loc = Lex.getLoc();
3177 if (ParseTypeAndValue(V, PFS)) return true;
3178 if (!isa<BasicBlock>(V))
3179 return Error(Loc, "expected a basic block");
3180 BB = cast<BasicBlock>(V);
3181 return false;
3182}
3183
3184
Chris Lattnerac161bf2009-01-02 07:01:27 +00003185/// FunctionHeader
3186/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003187/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003188/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003189bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3190 // Parse the linkage.
3191 LocTy LinkageLoc = Lex.getLoc();
3192 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003193
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003194 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003195 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003196 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003197 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003198 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003199 LocTy RetTypeLoc = Lex.getLoc();
3200 if (ParseOptionalLinkage(Linkage) ||
3201 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003202 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003204 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003205 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003206 return true;
3207
3208 // Verify that the linkage is ok.
3209 switch ((GlobalValue::LinkageTypes)Linkage) {
3210 case GlobalValue::ExternalLinkage:
3211 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003212 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 if (isDefine)
3214 return Error(LinkageLoc, "invalid linkage for function definition");
3215 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003216 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003217 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003218 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003219 case GlobalValue::LinkOnceAnyLinkage:
3220 case GlobalValue::LinkOnceODRLinkage:
3221 case GlobalValue::WeakAnyLinkage:
3222 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 if (!isDefine)
3224 return Error(LinkageLoc, "invalid linkage for function declaration");
3225 break;
3226 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003227 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003228 return Error(LinkageLoc, "invalid function linkage type");
3229 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003230
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003231 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3232 return Error(LinkageLoc,
3233 "symbol with local linkage must have default visibility");
3234
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003235 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003236 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003237
Chris Lattnerac161bf2009-01-02 07:01:27 +00003238 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003239
3240 std::string FunctionName;
3241 if (Lex.getKind() == lltok::GlobalVar) {
3242 FunctionName = Lex.getStrVal();
3243 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3244 unsigned NameID = Lex.getUIntVal();
3245
3246 if (NameID != NumberedVals.size())
3247 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003248 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003249 } else {
3250 return TokError("expected function name");
3251 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003252
Chris Lattner3822f632009-01-02 08:05:26 +00003253 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003254
Chris Lattner3822f632009-01-02 08:05:26 +00003255 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003256 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003258 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003259 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003260 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003261 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003262 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003263 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003264 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003265 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003266 bool UnnamedAddr;
3267 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003268 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003269 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003270 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003271
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003272 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003273 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3274 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003275 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003276 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003277 (EatIfPresent(lltok::kw_section) &&
3278 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00003279 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003280 ParseOptionalAlignment(Alignment) ||
3281 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003282 ParseStringConstant(GC)) ||
3283 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003284 ParseGlobalTypeAndValue(Prefix)) ||
3285 (EatIfPresent(lltok::kw_prologue) &&
3286 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003287 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288
Michael Gottesman41748d72013-06-27 00:25:01 +00003289 if (FuncAttrs.contains(Attribute::Builtin))
3290 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003291
Chris Lattnerac161bf2009-01-02 07:01:27 +00003292 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003293 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003294 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003295 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003297
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298 // Okay, if we got here, the function is syntactically valid. Convert types
3299 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003300 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003301 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003302
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003303 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003304 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3305 AttributeSet::ReturnIndex,
3306 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003307
Chris Lattnerac161bf2009-01-02 07:01:27 +00003308 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003309 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003310 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3311 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003312 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3313 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003314 }
3315
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003316 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003317 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3318 AttributeSet::FunctionIndex,
3319 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320
Bill Wendlinge94d8432012-12-07 23:16:57 +00003321 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003322
Bill Wendling749a43d2012-12-30 13:50:49 +00003323 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003324 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3325
Chris Lattner229907c2011-07-18 04:54:35 +00003326 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003327 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003328 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003329
Craig Topper2617dcc2014-04-15 06:32:26 +00003330 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003331 if (!FunctionName.empty()) {
3332 // If this was a definition of a forward reference, remove the definition
3333 // from the forward reference table and fill in the forward ref.
3334 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3335 ForwardRefVals.find(FunctionName);
3336 if (FRVI != ForwardRefVals.end()) {
3337 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003338 if (!Fn)
3339 return Error(FRVI->second.second, "invalid forward reference to "
3340 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003341 if (Fn->getType() != PFT)
3342 return Error(FRVI->second.second, "invalid forward reference to "
3343 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003344
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345 ForwardRefVals.erase(FRVI);
3346 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003347 // Reject redefinitions.
3348 return Error(NameLoc, "invalid redefinition of function '" +
3349 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003350 } else if (M->getNamedValue(FunctionName)) {
3351 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003352 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003353
Dan Gohman399d6ae2009-08-29 23:37:49 +00003354 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003355 // If this is a definition of a forward referenced function, make sure the
3356 // types agree.
3357 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3358 = ForwardRefValIDs.find(NumberedVals.size());
3359 if (I != ForwardRefValIDs.end()) {
3360 Fn = cast<Function>(I->second.first);
3361 if (Fn->getType() != PFT)
3362 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003363 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003364 ForwardRefValIDs.erase(I);
3365 }
3366 }
3367
Craig Topper2617dcc2014-04-15 06:32:26 +00003368 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003369 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3370 else // Move the forward-reference to the correct spot in the module.
3371 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3372
3373 if (FunctionName.empty())
3374 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003375
Chris Lattnerac161bf2009-01-02 07:01:27 +00003376 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3377 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003378 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003379 Fn->setCallingConv(CC);
3380 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003381 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003382 Fn->setAlignment(Alignment);
3383 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003384 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003385 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003386 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003387 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003388 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003389
Chris Lattnerac161bf2009-01-02 07:01:27 +00003390 // Add all of the arguments we parsed to the function.
3391 Function::arg_iterator ArgIt = Fn->arg_begin();
3392 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3393 // If the argument has a name, insert it into the argument symbol table.
3394 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003395
Chris Lattnerac161bf2009-01-02 07:01:27 +00003396 // Set the name, if it conflicted, it will be auto-renamed.
3397 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003398
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003399 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003400 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3401 ArgList[i].Name + "'");
3402 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003403
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003404 if (isDefine)
3405 return false;
3406
Robin Morisset039781e2014-08-29 21:53:01 +00003407 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003408 ValID ID;
3409 if (FunctionName.empty()) {
3410 ID.Kind = ValID::t_GlobalID;
3411 ID.UIntVal = NumberedVals.size() - 1;
3412 } else {
3413 ID.Kind = ValID::t_GlobalName;
3414 ID.StrVal = FunctionName;
3415 }
3416 auto Blocks = ForwardRefBlockAddresses.find(ID);
3417 if (Blocks != ForwardRefBlockAddresses.end())
3418 return Error(Blocks->first.Loc,
3419 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003420 return false;
3421}
3422
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003423bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3424 ValID ID;
3425 if (FunctionNumber == -1) {
3426 ID.Kind = ValID::t_GlobalName;
3427 ID.StrVal = F.getName();
3428 } else {
3429 ID.Kind = ValID::t_GlobalID;
3430 ID.UIntVal = FunctionNumber;
3431 }
3432
3433 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3434 if (Blocks == P.ForwardRefBlockAddresses.end())
3435 return false;
3436
3437 for (const auto &I : Blocks->second) {
3438 const ValID &BBID = I.first;
3439 GlobalValue *GV = I.second;
3440
3441 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3442 "Expected local id or name");
3443 BasicBlock *BB;
3444 if (BBID.Kind == ValID::t_LocalName)
3445 BB = GetBB(BBID.StrVal, BBID.Loc);
3446 else
3447 BB = GetBB(BBID.UIntVal, BBID.Loc);
3448 if (!BB)
3449 return P.Error(BBID.Loc, "referenced value is not a basic block");
3450
3451 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3452 GV->eraseFromParent();
3453 }
3454
3455 P.ForwardRefBlockAddresses.erase(Blocks);
3456 return false;
3457}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003458
3459/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003460/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003461bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003462 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003463 return TokError("expected '{' in function body");
3464 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003465
Chris Lattner3432c622009-10-28 03:39:23 +00003466 int FunctionNumber = -1;
3467 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003468
Chris Lattner3432c622009-10-28 03:39:23 +00003469 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003470
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003471 // Resolve block addresses and allow basic blocks to be forward-declared
3472 // within this function.
3473 if (PFS.resolveForwardRefBlockAddresses())
3474 return true;
3475 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3476
Chris Lattnerbbddd962010-01-09 19:20:07 +00003477 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003478 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003479 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003480
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003481 while (Lex.getKind() != lltok::rbrace &&
3482 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003483 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003484
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003485 while (Lex.getKind() != lltok::rbrace)
3486 if (ParseUseListOrder(&PFS))
3487 return true;
3488
Chris Lattnerac161bf2009-01-02 07:01:27 +00003489 // Eat the }.
3490 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003491
Chris Lattnerac161bf2009-01-02 07:01:27 +00003492 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003493 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003494}
3495
3496/// ParseBasicBlock
3497/// ::= LabelStr? Instruction*
3498bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3499 // If this basic block starts out with a name, remember it.
3500 std::string Name;
3501 LocTy NameLoc = Lex.getLoc();
3502 if (Lex.getKind() == lltok::LabelStr) {
3503 Name = Lex.getStrVal();
3504 Lex.Lex();
3505 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003506
Chris Lattnerac161bf2009-01-02 07:01:27 +00003507 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003508 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003509
Chris Lattnerac161bf2009-01-02 07:01:27 +00003510 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003511
Chris Lattnerac161bf2009-01-02 07:01:27 +00003512 // Parse the instructions in this block until we get a terminator.
3513 Instruction *Inst;
3514 do {
3515 // This instruction may have three possibilities for a name: a) none
3516 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3517 LocTy NameLoc = Lex.getLoc();
3518 int NameID = -1;
3519 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003520
Chris Lattnerac161bf2009-01-02 07:01:27 +00003521 if (Lex.getKind() == lltok::LocalVarID) {
3522 NameID = Lex.getUIntVal();
3523 Lex.Lex();
3524 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3525 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003526 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003527 NameStr = Lex.getStrVal();
3528 Lex.Lex();
3529 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3530 return true;
3531 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003532
Chris Lattner77b89dc2009-12-30 05:23:43 +00003533 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003534 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003535 case InstError: return true;
3536 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003537 BB->getInstList().push_back(Inst);
3538
Chris Lattner77b89dc2009-12-30 05:23:43 +00003539 // With a normal result, we check to see if the instruction is followed by
3540 // a comma and metadata.
3541 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003542 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003543 return true;
3544 break;
3545 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003546 BB->getInstList().push_back(Inst);
3547
Chris Lattner77b89dc2009-12-30 05:23:43 +00003548 // If the instruction parser ate an extra comma at the end of it, it
3549 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003550 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003551 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003552 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003553 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003554
Chris Lattnerac161bf2009-01-02 07:01:27 +00003555 // Set the name on the instruction.
3556 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3557 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003558
Chris Lattnerac161bf2009-01-02 07:01:27 +00003559 return false;
3560}
3561
3562//===----------------------------------------------------------------------===//
3563// Instruction Parsing.
3564//===----------------------------------------------------------------------===//
3565
3566/// ParseInstruction - Parse one of the many different instructions.
3567///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003568int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3569 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003570 lltok::Kind Token = Lex.getKind();
3571 if (Token == lltok::Eof)
3572 return TokError("found end of file when expecting more instructions");
3573 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003574 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003575 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003576
Chris Lattnerac161bf2009-01-02 07:01:27 +00003577 switch (Token) {
3578 default: return Error(Loc, "expected instruction opcode");
3579 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003580 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003581 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3582 case lltok::kw_br: return ParseBr(Inst, PFS);
3583 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003584 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003585 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003586 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003587 // Binary Operators.
3588 case lltok::kw_add:
3589 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003590 case lltok::kw_mul:
3591 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003592 bool NUW = EatIfPresent(lltok::kw_nuw);
3593 bool NSW = EatIfPresent(lltok::kw_nsw);
3594 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003595
Chris Lattnera676c0f2011-02-07 16:40:21 +00003596 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003597
Chris Lattnera676c0f2011-02-07 16:40:21 +00003598 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3599 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3600 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003601 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003602 case lltok::kw_fadd:
3603 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003604 case lltok::kw_fmul:
3605 case lltok::kw_fdiv:
3606 case lltok::kw_frem: {
3607 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3608 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3609 if (Res != 0)
3610 return Res;
3611 if (FMF.any())
3612 Inst->setFastMathFlags(FMF);
3613 return 0;
3614 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003615
Chris Lattner35315d02011-02-06 21:44:57 +00003616 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003617 case lltok::kw_udiv:
3618 case lltok::kw_lshr:
3619 case lltok::kw_ashr: {
3620 bool Exact = EatIfPresent(lltok::kw_exact);
3621
3622 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3623 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3624 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003625 }
3626
Chris Lattnerac161bf2009-01-02 07:01:27 +00003627 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003628 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003629 case lltok::kw_and:
3630 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003631 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003632 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003633 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003634 // Casts.
3635 case lltok::kw_trunc:
3636 case lltok::kw_zext:
3637 case lltok::kw_sext:
3638 case lltok::kw_fptrunc:
3639 case lltok::kw_fpext:
3640 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003641 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003642 case lltok::kw_uitofp:
3643 case lltok::kw_sitofp:
3644 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003645 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003646 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003647 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003648 // Other.
3649 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003650 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003651 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3652 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3653 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3654 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003655 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003656 // Call.
3657 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3658 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3659 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003660 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003661 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003662 case lltok::kw_load: return ParseLoad(Inst, PFS);
3663 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003664 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3665 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003666 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003667 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3668 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3669 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3670 }
3671}
3672
3673/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3674bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003675 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003676 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003677 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003678 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3679 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3680 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3681 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3682 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3683 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3684 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3685 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3686 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3687 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3688 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3689 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3690 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3691 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3692 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3693 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3694 }
3695 } else {
3696 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003697 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003698 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3699 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3700 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3701 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3702 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3703 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3704 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3705 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3706 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3707 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3708 }
3709 }
3710 Lex.Lex();
3711 return false;
3712}
3713
3714//===----------------------------------------------------------------------===//
3715// Terminator Instructions.
3716//===----------------------------------------------------------------------===//
3717
3718/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003719/// ::= 'ret' void (',' !dbg, !1)*
3720/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003721bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003722 PerFunctionState &PFS) {
3723 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003724 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003725 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003726
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003727 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003728
Chris Lattnerfdd87902009-10-05 05:54:46 +00003729 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003730 if (!ResType->isVoidTy())
3731 return Error(TypeLoc, "value doesn't match function result type '" +
3732 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003733
Owen Anderson55f1c092009-08-13 21:58:54 +00003734 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003735 return false;
3736 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003737
Chris Lattnerac161bf2009-01-02 07:01:27 +00003738 Value *RV;
3739 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003740
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003741 if (ResType != RV->getType())
3742 return Error(TypeLoc, "value doesn't match function result type '" +
3743 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003744
Owen Anderson55f1c092009-08-13 21:58:54 +00003745 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003746 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003747}
3748
3749
3750/// ParseBr
3751/// ::= 'br' TypeAndValue
3752/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3753bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3754 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003755 Value *Op0;
3756 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003757 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003758
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3760 Inst = BranchInst::Create(BB);
3761 return false;
3762 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003763
Owen Anderson55f1c092009-08-13 21:58:54 +00003764 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003765 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003766
Chris Lattnerac161bf2009-01-02 07:01:27 +00003767 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003768 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003769 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003770 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003771 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003772
Chris Lattner3ed871f2009-10-27 19:13:16 +00003773 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003774 return false;
3775}
3776
3777/// ParseSwitch
3778/// Instruction
3779/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3780/// JumpTable
3781/// ::= (TypeAndValue ',' TypeAndValue)*
3782bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3783 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003784 Value *Cond;
3785 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003786 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3787 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003788 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003789 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3790 return true;
3791
Duncan Sands19d0b472010-02-16 11:11:14 +00003792 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003793 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003794
Chris Lattnerac161bf2009-01-02 07:01:27 +00003795 // Parse the jump table pairs.
3796 SmallPtrSet<Value*, 32> SeenCases;
3797 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3798 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003799 Value *Constant;
3800 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003801
Chris Lattnerac161bf2009-01-02 07:01:27 +00003802 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3803 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003804 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003805 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003806
David Blaikie70573dc2014-11-19 07:49:26 +00003807 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003808 return Error(CondLoc, "duplicate case value in switch");
3809 if (!isa<ConstantInt>(Constant))
3810 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003811
Chris Lattner3ed871f2009-10-27 19:13:16 +00003812 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003813 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003814
Chris Lattnerac161bf2009-01-02 07:01:27 +00003815 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003816
Chris Lattner3ed871f2009-10-27 19:13:16 +00003817 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003818 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3819 SI->addCase(Table[i].first, Table[i].second);
3820 Inst = SI;
3821 return false;
3822}
3823
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003824/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003825/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003826/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3827bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003828 LocTy AddrLoc;
3829 Value *Address;
3830 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003831 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3832 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003833 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003834
Duncan Sands19d0b472010-02-16 11:11:14 +00003835 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003836 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003837
Chris Lattner3ed871f2009-10-27 19:13:16 +00003838 // Parse the destination list.
3839 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003840
Chris Lattner3ed871f2009-10-27 19:13:16 +00003841 if (Lex.getKind() != lltok::rsquare) {
3842 BasicBlock *DestBB;
3843 if (ParseTypeAndBasicBlock(DestBB, PFS))
3844 return true;
3845 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003846
Chris Lattner3ed871f2009-10-27 19:13:16 +00003847 while (EatIfPresent(lltok::comma)) {
3848 if (ParseTypeAndBasicBlock(DestBB, PFS))
3849 return true;
3850 DestList.push_back(DestBB);
3851 }
3852 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003853
Chris Lattner3ed871f2009-10-27 19:13:16 +00003854 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3855 return true;
3856
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003857 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003858 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3859 IBI->addDestination(DestList[i]);
3860 Inst = IBI;
3861 return false;
3862}
3863
3864
Chris Lattnerac161bf2009-01-02 07:01:27 +00003865/// ParseInvoke
3866/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3867/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3868bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3869 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003870 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003871 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003872 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003873 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003874 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003875 LocTy RetTypeLoc;
3876 ValID CalleeID;
3877 SmallVector<ParamInfo, 16> ArgList;
3878
Chris Lattner3ed871f2009-10-27 19:13:16 +00003879 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003880 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003881 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003882 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003883 ParseValID(CalleeID) ||
3884 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003885 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3886 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003887 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003888 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003889 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003890 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003891 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003892
Chris Lattnerac161bf2009-01-02 07:01:27 +00003893 // If RetType is a non-function pointer type, then this is the short syntax
3894 // for the call, which means that RetType is just the return type. Infer the
3895 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003896 PointerType *PFTy = nullptr;
3897 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003898 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3899 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3900 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003901 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003902 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3903 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003904
Chris Lattnerac161bf2009-01-02 07:01:27 +00003905 if (!FunctionType::isValidReturnType(RetType))
3906 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003907
Owen Anderson4056ca92009-07-29 22:17:13 +00003908 Ty = FunctionType::get(RetType, ParamTypes, false);
3909 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003910 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003911
Chris Lattnerac161bf2009-01-02 07:01:27 +00003912 // Look up the callee.
3913 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003914 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003915
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003916 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003917 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003918 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003919 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3920 AttributeSet::ReturnIndex,
3921 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003922
Chris Lattnerac161bf2009-01-02 07:01:27 +00003923 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003924
Chris Lattnerac161bf2009-01-02 07:01:27 +00003925 // Loop through FunctionType's arguments and ensure they are specified
3926 // correctly. Also, gather any parameter attributes.
3927 FunctionType::param_iterator I = Ty->param_begin();
3928 FunctionType::param_iterator E = Ty->param_end();
3929 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003930 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931 if (I != E) {
3932 ExpectedTy = *I++;
3933 } else if (!Ty->isVarArg()) {
3934 return Error(ArgList[i].Loc, "too many arguments specified");
3935 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003936
Chris Lattnerac161bf2009-01-02 07:01:27 +00003937 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3938 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003939 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003940 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003941 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3942 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003943 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3944 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003945 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003946
Chris Lattnerac161bf2009-01-02 07:01:27 +00003947 if (I != E)
3948 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003949
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003950 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003951 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3952 AttributeSet::FunctionIndex,
3953 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003954
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003955 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003956 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003957
Jay Foad5bd375a2011-07-15 08:37:34 +00003958 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003959 II->setCallingConv(CC);
3960 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003961 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003962 Inst = II;
3963 return false;
3964}
3965
Bill Wendlingf891bf82011-07-31 06:30:59 +00003966/// ParseResume
3967/// ::= 'resume' TypeAndValue
3968bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3969 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003970 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3971 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003972
Bill Wendlingf891bf82011-07-31 06:30:59 +00003973 ResumeInst *RI = ResumeInst::Create(Exn);
3974 Inst = RI;
3975 return false;
3976}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003977
3978//===----------------------------------------------------------------------===//
3979// Binary Operators.
3980//===----------------------------------------------------------------------===//
3981
3982/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003983/// ::= ArithmeticOps TypeAndValue ',' Value
3984///
3985/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3986/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003987bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003988 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003989 LocTy Loc; Value *LHS, *RHS;
3990 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3991 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3992 ParseValue(LHS->getType(), RHS, PFS))
3993 return true;
3994
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003995 bool Valid;
3996 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003997 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003998 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003999 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4000 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004001 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004002 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4003 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004004 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004005
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004006 if (!Valid)
4007 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004008
Chris Lattnerac161bf2009-01-02 07:01:27 +00004009 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4010 return false;
4011}
4012
4013/// ParseLogical
4014/// ::= ArithmeticOps TypeAndValue ',' Value {
4015bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4016 unsigned Opc) {
4017 LocTy Loc; Value *LHS, *RHS;
4018 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4019 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4020 ParseValue(LHS->getType(), RHS, PFS))
4021 return true;
4022
Duncan Sands9dff9be2010-02-15 16:12:20 +00004023 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004024 return Error(Loc,"instruction requires integer or integer vector operands");
4025
4026 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4027 return false;
4028}
4029
4030
4031/// ParseCompare
4032/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4033/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004034bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4035 unsigned Opc) {
4036 // Parse the integer/fp comparison predicate.
4037 LocTy Loc;
4038 unsigned Pred;
4039 Value *LHS, *RHS;
4040 if (ParseCmpPredicate(Pred, Opc) ||
4041 ParseTypeAndValue(LHS, Loc, PFS) ||
4042 ParseToken(lltok::comma, "expected ',' after compare value") ||
4043 ParseValue(LHS->getType(), RHS, PFS))
4044 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004045
Chris Lattnerac161bf2009-01-02 07:01:27 +00004046 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004047 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004048 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004049 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004050 } else {
4051 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004052 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004053 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004054 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004055 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056 }
4057 return false;
4058}
4059
4060//===----------------------------------------------------------------------===//
4061// Other Instructions.
4062//===----------------------------------------------------------------------===//
4063
4064
4065/// ParseCast
4066/// ::= CastOpc TypeAndValue 'to' Type
4067bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4068 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004069 LocTy Loc;
4070 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004071 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004072 if (ParseTypeAndValue(Op, Loc, PFS) ||
4073 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4074 ParseType(DestTy))
4075 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004076
Chris Lattner89d856e2009-03-01 00:53:13 +00004077 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4078 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004079 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004080 getTypeString(Op->getType()) + "' to '" +
4081 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004082 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004083 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4084 return false;
4085}
4086
4087/// ParseSelect
4088/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4089bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4090 LocTy Loc;
4091 Value *Op0, *Op1, *Op2;
4092 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4093 ParseToken(lltok::comma, "expected ',' after select condition") ||
4094 ParseTypeAndValue(Op1, PFS) ||
4095 ParseToken(lltok::comma, "expected ',' after select value") ||
4096 ParseTypeAndValue(Op2, PFS))
4097 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004098
Chris Lattnerac161bf2009-01-02 07:01:27 +00004099 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4100 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004101
Chris Lattnerac161bf2009-01-02 07:01:27 +00004102 Inst = SelectInst::Create(Op0, Op1, Op2);
4103 return false;
4104}
4105
Chris Lattnerb55ab542009-01-05 08:18:44 +00004106/// ParseVA_Arg
4107/// ::= 'va_arg' TypeAndValue ',' Type
4108bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004109 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004110 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004111 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004112 if (ParseTypeAndValue(Op, PFS) ||
4113 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004114 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004115 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004116
Chris Lattnerb55ab542009-01-05 08:18:44 +00004117 if (!EltTy->isFirstClassType())
4118 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004119
4120 Inst = new VAArgInst(Op, EltTy);
4121 return false;
4122}
4123
4124/// ParseExtractElement
4125/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4126bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4127 LocTy Loc;
4128 Value *Op0, *Op1;
4129 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4130 ParseToken(lltok::comma, "expected ',' after extract value") ||
4131 ParseTypeAndValue(Op1, PFS))
4132 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004133
Chris Lattnerac161bf2009-01-02 07:01:27 +00004134 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4135 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004136
Eric Christopherc9742252009-07-25 02:28:41 +00004137 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004138 return false;
4139}
4140
4141/// ParseInsertElement
4142/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4143bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4144 LocTy Loc;
4145 Value *Op0, *Op1, *Op2;
4146 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4147 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4148 ParseTypeAndValue(Op1, PFS) ||
4149 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4150 ParseTypeAndValue(Op2, PFS))
4151 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004152
Chris Lattnerac161bf2009-01-02 07:01:27 +00004153 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004154 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004155
Chris Lattnerac161bf2009-01-02 07:01:27 +00004156 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4157 return false;
4158}
4159
4160/// ParseShuffleVector
4161/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4162bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4163 LocTy Loc;
4164 Value *Op0, *Op1, *Op2;
4165 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4166 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4167 ParseTypeAndValue(Op1, PFS) ||
4168 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4169 ParseTypeAndValue(Op2, PFS))
4170 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004171
Chris Lattnerac161bf2009-01-02 07:01:27 +00004172 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004173 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004174
Chris Lattnerac161bf2009-01-02 07:01:27 +00004175 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4176 return false;
4177}
4178
4179/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004180/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004181int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004182 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004183 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004184
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004185 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004186 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4187 ParseValue(Ty, Op0, PFS) ||
4188 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004189 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004190 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4191 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004192
Chris Lattnerf4f03422009-12-30 05:27:33 +00004193 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004194 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4195 while (1) {
4196 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004197
Chris Lattner3822f632009-01-02 08:05:26 +00004198 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004199 break;
4200
Chris Lattnerf4f03422009-12-30 05:27:33 +00004201 if (Lex.getKind() == lltok::MetadataVar) {
4202 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004203 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004204 }
Devang Patel8f842d32009-10-16 18:45:49 +00004205
Chris Lattner3822f632009-01-02 08:05:26 +00004206 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004207 ParseValue(Ty, Op0, PFS) ||
4208 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004209 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4211 return true;
4212 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004213
Chris Lattnerac161bf2009-01-02 07:01:27 +00004214 if (!Ty->isFirstClassType())
4215 return Error(TypeLoc, "phi node must have first class type");
4216
Jay Foad52131342011-03-30 11:28:46 +00004217 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004218 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4219 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4220 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004221 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222}
4223
Bill Wendlingfae14752011-08-12 20:24:12 +00004224/// ParseLandingPad
4225/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4226/// Clause
4227/// ::= 'catch' TypeAndValue
4228/// ::= 'filter'
4229/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4230bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004231 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004232 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004233
4234 if (ParseType(Ty, TyLoc) ||
4235 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4236 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4237 return true;
4238
4239 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4240 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4241
4242 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4243 LandingPadInst::ClauseType CT;
4244 if (EatIfPresent(lltok::kw_catch))
4245 CT = LandingPadInst::Catch;
4246 else if (EatIfPresent(lltok::kw_filter))
4247 CT = LandingPadInst::Filter;
4248 else
4249 return TokError("expected 'catch' or 'filter' clause type");
4250
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004251 Value *V;
4252 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004253 if (ParseTypeAndValue(V, VLoc, PFS)) {
4254 delete LP;
4255 return true;
4256 }
4257
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004258 // A 'catch' type expects a non-array constant. A filter clause expects an
4259 // array constant.
4260 if (CT == LandingPadInst::Catch) {
4261 if (isa<ArrayType>(V->getType()))
4262 Error(VLoc, "'catch' clause has an invalid type");
4263 } else {
4264 if (!isa<ArrayType>(V->getType()))
4265 Error(VLoc, "'filter' clause has an invalid type");
4266 }
4267
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004268 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004269 }
4270
4271 Inst = LP;
4272 return false;
4273}
4274
Chris Lattnerac161bf2009-01-02 07:01:27 +00004275/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004276/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4277/// ParameterList OptionalAttrs
4278/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4279/// ParameterList OptionalAttrs
4280/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004281/// ParameterList OptionalAttrs
4282bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004283 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004284 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004285 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004286 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004287 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004288 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004289 LocTy RetTypeLoc;
4290 ValID CalleeID;
4291 SmallVector<ParamInfo, 16> ArgList;
4292 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004293
Reid Kleckner5772b772014-04-24 20:14:34 +00004294 if ((TCK != CallInst::TCK_None &&
4295 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004296 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004297 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004298 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004299 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004300 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4301 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004302 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004303 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004305
Chris Lattnerac161bf2009-01-02 07:01:27 +00004306 // If RetType is a non-function pointer type, then this is the short syntax
4307 // for the call, which means that RetType is just the return type. Infer the
4308 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004309 PointerType *PFTy = nullptr;
4310 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004311 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4312 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4313 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004314 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004315 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4316 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004317
Chris Lattnerac161bf2009-01-02 07:01:27 +00004318 if (!FunctionType::isValidReturnType(RetType))
4319 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004320
Owen Anderson4056ca92009-07-29 22:17:13 +00004321 Ty = FunctionType::get(RetType, ParamTypes, false);
4322 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004324
Chris Lattnerac161bf2009-01-02 07:01:27 +00004325 // Look up the callee.
4326 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004327 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004328
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004329 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004330 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004331 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004332 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4333 AttributeSet::ReturnIndex,
4334 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004335
Chris Lattnerac161bf2009-01-02 07:01:27 +00004336 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004337
Chris Lattnerac161bf2009-01-02 07:01:27 +00004338 // Loop through FunctionType's arguments and ensure they are specified
4339 // correctly. Also, gather any parameter attributes.
4340 FunctionType::param_iterator I = Ty->param_begin();
4341 FunctionType::param_iterator E = Ty->param_end();
4342 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004343 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004344 if (I != E) {
4345 ExpectedTy = *I++;
4346 } else if (!Ty->isVarArg()) {
4347 return Error(ArgList[i].Loc, "too many arguments specified");
4348 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004349
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4351 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004352 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004353 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004354 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4355 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004356 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4357 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004358 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004359
Chris Lattnerac161bf2009-01-02 07:01:27 +00004360 if (I != E)
4361 return Error(CallLoc, "not enough parameters specified for call");
4362
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004363 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004364 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4365 AttributeSet::FunctionIndex,
4366 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004367
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004368 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004369 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004370
Jay Foad5bd375a2011-07-15 08:37:34 +00004371 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004372 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004373 CI->setCallingConv(CC);
4374 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004375 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 Inst = CI;
4377 return false;
4378}
4379
4380//===----------------------------------------------------------------------===//
4381// Memory Instructions.
4382//===----------------------------------------------------------------------===//
4383
4384/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004385/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004386int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004387 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004388 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004389 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004390 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004391
4392 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4393
Chris Lattner3822f632009-01-02 08:05:26 +00004394 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004395
Chris Lattnerb2f39502009-12-30 05:44:30 +00004396 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004397 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004398 if (Lex.getKind() == lltok::kw_align) {
4399 if (ParseOptionalAlignment(Alignment)) return true;
4400 } else if (Lex.getKind() == lltok::MetadataVar) {
4401 AteExtraComma = true;
4402 } else {
4403 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4404 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4405 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004406 }
4407 }
4408
Dan Gohman2140a742010-05-28 01:14:11 +00004409 if (Size && !Size->getType()->isIntegerTy())
4410 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004411
Reid Kleckner436c42e2014-01-17 23:58:17 +00004412 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4413 AI->setUsedWithInAlloca(IsInAlloca);
4414 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004415 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004416}
4417
4418/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004419/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004420/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004421/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004422int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004423 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004424 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004425 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004426 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004427 AtomicOrdering Ordering = NotAtomic;
4428 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004429
4430 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004431 isAtomic = true;
4432 Lex.Lex();
4433 }
4434
Chris Lattnerbc639292011-11-27 06:56:53 +00004435 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004436 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004437 isVolatile = true;
4438 Lex.Lex();
4439 }
4440
Chris Lattnerb2f39502009-12-30 05:44:30 +00004441 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004442 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004443 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4444 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004445
Duncan Sands19d0b472010-02-16 11:11:14 +00004446 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004447 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4448 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004449 if (isAtomic && !Alignment)
4450 return Error(Loc, "atomic load must have explicit non-zero alignment");
4451 if (Ordering == Release || Ordering == AcquireRelease)
4452 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004453
Eli Friedman59b66882011-08-09 23:02:53 +00004454 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004455 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004456}
4457
4458/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004459
4460/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4461/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004462/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004463int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004464 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004465 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004466 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004467 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004468 AtomicOrdering Ordering = NotAtomic;
4469 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004470
4471 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004472 isAtomic = true;
4473 Lex.Lex();
4474 }
4475
Chris Lattnerbc639292011-11-27 06:56:53 +00004476 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004477 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004478 isVolatile = true;
4479 Lex.Lex();
4480 }
4481
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 if (ParseTypeAndValue(Val, Loc, PFS) ||
4483 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004484 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004485 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004486 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004488
Duncan Sands19d0b472010-02-16 11:11:14 +00004489 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 return Error(PtrLoc, "store operand must be a pointer");
4491 if (!Val->getType()->isFirstClassType())
4492 return Error(Loc, "store operand must be a first class value");
4493 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4494 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004495 if (isAtomic && !Alignment)
4496 return Error(Loc, "atomic store must have explicit non-zero alignment");
4497 if (Ordering == Acquire || Ordering == AcquireRelease)
4498 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004499
Eli Friedman59b66882011-08-09 23:02:53 +00004500 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004501 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004502}
4503
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004504/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004505/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4506/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004507int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004508 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4509 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004510 AtomicOrdering SuccessOrdering = NotAtomic;
4511 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004512 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004513 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004514 bool isWeak = false;
4515
4516 if (EatIfPresent(lltok::kw_weak))
4517 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004518
4519 if (EatIfPresent(lltok::kw_volatile))
4520 isVolatile = true;
4521
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004522 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4523 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4524 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4525 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4526 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004527 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4528 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004529 return true;
4530
Tim Northovere94a5182014-03-11 10:48:52 +00004531 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004532 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004533 if (SuccessOrdering < FailureOrdering)
4534 return TokError("cmpxchg must be at least as ordered on success as failure");
4535 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4536 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004537 if (!Ptr->getType()->isPointerTy())
4538 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4539 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4540 return Error(CmpLoc, "compare value and pointer type do not match");
4541 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4542 return Error(NewLoc, "new value and pointer type do not match");
4543 if (!New->getType()->isIntegerTy())
4544 return Error(NewLoc, "cmpxchg operand must be an integer");
4545 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4546 if (Size < 8 || (Size & (Size - 1)))
4547 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4548 " integer");
4549
Tim Northover420a2162014-06-13 14:24:07 +00004550 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4551 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004552 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004553 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004554 Inst = CXI;
4555 return AteExtraComma ? InstExtraComma : InstNormal;
4556}
4557
4558/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004559/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4560/// 'singlethread'? AtomicOrdering
4561int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004562 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4563 bool AteExtraComma = false;
4564 AtomicOrdering Ordering = NotAtomic;
4565 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004566 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004567 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004568
4569 if (EatIfPresent(lltok::kw_volatile))
4570 isVolatile = true;
4571
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004572 switch (Lex.getKind()) {
4573 default: return TokError("expected binary operation in atomicrmw");
4574 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4575 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4576 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4577 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4578 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4579 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4580 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4581 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4582 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4583 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4584 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4585 }
4586 Lex.Lex(); // Eat the operation.
4587
4588 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4589 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4590 ParseTypeAndValue(Val, ValLoc, PFS) ||
4591 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4592 return true;
4593
4594 if (Ordering == Unordered)
4595 return TokError("atomicrmw cannot be unordered");
4596 if (!Ptr->getType()->isPointerTy())
4597 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4598 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4599 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4600 if (!Val->getType()->isIntegerTy())
4601 return Error(ValLoc, "atomicrmw operand must be an integer");
4602 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4603 if (Size < 8 || (Size & (Size - 1)))
4604 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4605 " integer");
4606
4607 AtomicRMWInst *RMWI =
4608 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4609 RMWI->setVolatile(isVolatile);
4610 Inst = RMWI;
4611 return AteExtraComma ? InstExtraComma : InstNormal;
4612}
4613
Eli Friedmanfee02c62011-07-25 23:16:38 +00004614/// ParseFence
4615/// ::= 'fence' 'singlethread'? AtomicOrdering
4616int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4617 AtomicOrdering Ordering = NotAtomic;
4618 SynchronizationScope Scope = CrossThread;
4619 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4620 return true;
4621
4622 if (Ordering == Unordered)
4623 return TokError("fence cannot be unordered");
4624 if (Ordering == Monotonic)
4625 return TokError("fence cannot be monotonic");
4626
4627 Inst = new FenceInst(Context, Ordering, Scope);
4628 return InstNormal;
4629}
4630
Chris Lattnerac161bf2009-01-02 07:01:27 +00004631/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004632/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004633int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004634 Value *Ptr = nullptr;
4635 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004636 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004637
Dan Gohman16cbbe42009-07-29 15:58:36 +00004638 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004639
Chris Lattner3822f632009-01-02 08:05:26 +00004640 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004641
Eli Benderskyd9806682013-04-22 17:03:42 +00004642 Type *BaseType = Ptr->getType();
4643 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4644 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004646
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004648 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004649 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004650 if (Lex.getKind() == lltok::MetadataVar) {
4651 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004652 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004653 }
Chris Lattner3822f632009-01-02 08:05:26 +00004654 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004655 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004657 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4658 return Error(EltLoc, "getelementptr index type missmatch");
4659 if (Val->getType()->isVectorTy()) {
4660 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4661 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4662 if (ValNumEl != PtrNumEl)
4663 return Error(EltLoc,
4664 "getelementptr vector index has a wrong number of elements");
4665 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004666 Indices.push_back(Val);
4667 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668
Eli Benderskyd9806682013-04-22 17:03:42 +00004669 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4670 return Error(Loc, "base element of getelementptr must be sized");
4671
4672 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004673 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004674 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004675 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004676 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004677 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004678}
4679
4680/// ParseExtractValue
4681/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004682int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004683 Value *Val; LocTy Loc;
4684 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004685 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004686 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004687 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004688 return true;
4689
Chris Lattner392be582010-02-12 20:49:41 +00004690 if (!Val->getType()->isAggregateType())
4691 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004692
Jay Foad57aa6362011-07-13 10:26:04 +00004693 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004694 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004695 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004696 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004697}
4698
4699/// ParseInsertValue
4700/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004701int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004702 Value *Val0, *Val1; LocTy Loc0, Loc1;
4703 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004704 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4706 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4707 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004708 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004709 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004710
Chris Lattner392be582010-02-12 20:49:41 +00004711 if (!Val0->getType()->isAggregateType())
4712 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004713
Jay Foad57aa6362011-07-13 10:26:04 +00004714 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004715 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004716 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004717 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718}
Nick Lewycky49f89192009-04-04 07:22:01 +00004719
4720//===----------------------------------------------------------------------===//
4721// Embedded metadata.
4722//===----------------------------------------------------------------------===//
4723
4724/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004725/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004726/// Element
4727/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004728bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00004729 if (ParseToken(lltok::lbrace, "expected '{' here"))
4730 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004731
Dan Gohman1e0213a2010-07-13 19:33:27 +00004732 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004733 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004734 return false;
4735
Nick Lewycky49f89192009-04-04 07:22:01 +00004736 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004737 // Null is a special case since it is typeless.
4738 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004739 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004740 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004741 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004742
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004743 Metadata *MD;
4744 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004745 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004746 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00004747 } while (EatIfPresent(lltok::comma));
4748
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004749 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004750}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004751
4752//===----------------------------------------------------------------------===//
4753// Use-list order directives.
4754//===----------------------------------------------------------------------===//
4755bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4756 SMLoc Loc) {
4757 if (V->use_empty())
4758 return Error(Loc, "value has no uses");
4759
4760 unsigned NumUses = 0;
4761 SmallDenseMap<const Use *, unsigned, 16> Order;
4762 for (const Use &U : V->uses()) {
4763 if (++NumUses > Indexes.size())
4764 break;
4765 Order[&U] = Indexes[NumUses - 1];
4766 }
4767 if (NumUses < 2)
4768 return Error(Loc, "value only has one use");
4769 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4770 return Error(Loc, "wrong number of indexes, expected " +
4771 Twine(std::distance(V->use_begin(), V->use_end())));
4772
4773 V->sortUseList([&](const Use &L, const Use &R) {
4774 return Order.lookup(&L) < Order.lookup(&R);
4775 });
4776 return false;
4777}
4778
4779/// ParseUseListOrderIndexes
4780/// ::= '{' uint32 (',' uint32)+ '}'
4781bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4782 SMLoc Loc = Lex.getLoc();
4783 if (ParseToken(lltok::lbrace, "expected '{' here"))
4784 return true;
4785 if (Lex.getKind() == lltok::rbrace)
4786 return Lex.Error("expected non-empty list of uselistorder indexes");
4787
4788 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4789 // indexes should be distinct numbers in the range [0, size-1], and should
4790 // not be in order.
4791 unsigned Offset = 0;
4792 unsigned Max = 0;
4793 bool IsOrdered = true;
4794 assert(Indexes.empty() && "Expected empty order vector");
4795 do {
4796 unsigned Index;
4797 if (ParseUInt32(Index))
4798 return true;
4799
4800 // Update consistency checks.
4801 Offset += Index - Indexes.size();
4802 Max = std::max(Max, Index);
4803 IsOrdered &= Index == Indexes.size();
4804
4805 Indexes.push_back(Index);
4806 } while (EatIfPresent(lltok::comma));
4807
4808 if (ParseToken(lltok::rbrace, "expected '}' here"))
4809 return true;
4810
4811 if (Indexes.size() < 2)
4812 return Error(Loc, "expected >= 2 uselistorder indexes");
4813 if (Offset != 0 || Max >= Indexes.size())
4814 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4815 if (IsOrdered)
4816 return Error(Loc, "expected uselistorder indexes to change the order");
4817
4818 return false;
4819}
4820
4821/// ParseUseListOrder
4822/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4823bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4824 SMLoc Loc = Lex.getLoc();
4825 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4826 return true;
4827
4828 Value *V;
4829 SmallVector<unsigned, 16> Indexes;
4830 if (ParseTypeAndValue(V, PFS) ||
4831 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4832 ParseUseListOrderIndexes(Indexes))
4833 return true;
4834
4835 return sortUseListOrder(V, Indexes, Loc);
4836}
4837
4838/// ParseUseListOrderBB
4839/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4840bool LLParser::ParseUseListOrderBB() {
4841 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4842 SMLoc Loc = Lex.getLoc();
4843 Lex.Lex();
4844
4845 ValID Fn, Label;
4846 SmallVector<unsigned, 16> Indexes;
4847 if (ParseValID(Fn) ||
4848 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4849 ParseValID(Label) ||
4850 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4851 ParseUseListOrderIndexes(Indexes))
4852 return true;
4853
4854 // Check the function.
4855 GlobalValue *GV;
4856 if (Fn.Kind == ValID::t_GlobalName)
4857 GV = M->getNamedValue(Fn.StrVal);
4858 else if (Fn.Kind == ValID::t_GlobalID)
4859 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4860 else
4861 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4862 if (!GV)
4863 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4864 auto *F = dyn_cast<Function>(GV);
4865 if (!F)
4866 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4867 if (F->isDeclaration())
4868 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4869
4870 // Check the basic block.
4871 if (Label.Kind == ValID::t_LocalID)
4872 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4873 if (Label.Kind != ValID::t_LocalName)
4874 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4875 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4876 if (!V)
4877 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4878 if (!isa<BasicBlock>(V))
4879 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4880
4881 return sortUseListOrder(V, Indexes, Loc);
4882}