blob: ca4ba6e07f3580530563eba6583859e66d2bba08 [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)
172 if (auto *G = cast_or_null<GenericMDNode>(N))
173 G->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
612 LocTy TyLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +0000613 Type *Ty = nullptr;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000614 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000615 if (ParseUInt32(MetadataID) ||
616 ParseToken(lltok::equal, "expected '=' here") ||
617 ParseType(Ty, TyLoc) ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000618 ParseToken(lltok::exclaim, "Expected '!' here") ||
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000619 ParseMDNode(Init))
Devang Patele059ba6e2009-07-23 01:07:34 +0000620 return true;
621
Chris Lattnerfc58af22009-12-30 04:51:58 +0000622 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000623 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000624 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000625 auto *Temp = FI->second.first;
Dan Gohman16a5d982010-08-20 22:02:26 +0000626 Temp->replaceAllUsesWith(Init);
627 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000628 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000629
Chris Lattnerfc58af22009-12-30 04:51:58 +0000630 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
631 } else {
632 if (MetadataID >= NumberedMetadata.size())
633 NumberedMetadata.resize(MetadataID+1);
634
Craig Topper2617dcc2014-04-15 06:32:26 +0000635 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000636 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000637 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000638 }
639
Devang Patel39e64d42009-07-01 19:21:12 +0000640 return false;
641}
642
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000643static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
644 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
645 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
646}
647
Chris Lattnerac161bf2009-01-02 07:01:27 +0000648/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000649/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
650/// OptionalDLLStorageClass OptionalThreadLocal
651/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000652///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000653/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000654/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000655///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000656/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000657///
Rafael Espindola464fe022014-07-30 22:51:54 +0000658bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000659 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000660 GlobalVariable::ThreadLocalMode TLM,
661 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000662 assert(Lex.getKind() == lltok::kw_alias);
663 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000664
Rafael Espindola78527052013-10-06 15:10:43 +0000665 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
666
Rafael Espindolacaa43562013-10-09 16:07:32 +0000667 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000668 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000669
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000670 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000671 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000672 "symbol with local linkage must have default visibility");
673
Rafael Espindola64c1e182014-06-03 02:41:57 +0000674 Constant *Aliasee;
675 LocTy AliaseeLoc = Lex.getLoc();
676 if (Lex.getKind() != lltok::kw_bitcast &&
677 Lex.getKind() != lltok::kw_getelementptr &&
678 Lex.getKind() != lltok::kw_addrspacecast &&
679 Lex.getKind() != lltok::kw_inttoptr) {
680 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000681 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000682 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000683 // The bitcast dest type is not present, it is implied by the dest type.
684 ValID ID;
685 if (ParseValID(ID))
686 return true;
687 if (ID.Kind != ValID::t_Constant)
688 return Error(AliaseeLoc, "invalid aliasee");
689 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000690 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
Rafael Espindola64c1e182014-06-03 02:41:57 +0000692 Type *AliaseeType = Aliasee->getType();
693 auto *PTy = dyn_cast<PointerType>(AliaseeType);
694 if (!PTy)
695 return Error(AliaseeLoc, "An alias must have pointer type");
696 Type *Ty = PTy->getElementType();
697 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000698
699 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000700 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000701 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
702 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000703 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000704 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000705 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000706 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000707
Chris Lattnerac161bf2009-01-02 07:01:27 +0000708 // See if this value already exists in the symbol table. If so, it is either
709 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000710 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711 // See if this was a redefinition. If so, there is no entry in
712 // ForwardRefVals.
713 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
714 I = ForwardRefVals.find(Name);
715 if (I == ForwardRefVals.end())
716 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
717
718 // Otherwise, this was a definition of forward ref. Verify that types
719 // agree.
720 if (Val->getType() != GA->getType())
721 return Error(NameLoc,
722 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724 // If they agree, just RAUW the old value with the alias and remove the
725 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000726 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000727 Val->eraseFromParent();
728 ForwardRefVals.erase(I);
729 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000730
Chris Lattnerac161bf2009-01-02 07:01:27 +0000731 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000732 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000733 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Rafael Espindolaaa273822014-05-09 21:49:17 +0000735 // The module owns this now
736 GA.release();
737
Chris Lattnerac161bf2009-01-02 07:01:27 +0000738 return false;
739}
740
741/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000742/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000743/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000744/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000745/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000746/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000747/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000749/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000750/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000751///
752bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
753 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000754 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000755 GlobalVariable::ThreadLocalMode TLM,
756 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000757 if (!isValidVisibilityForLinkage(Visibility, Linkage))
758 return Error(NameLoc,
759 "symbol with local linkage must have default visibility");
760
Chris Lattnerac161bf2009-01-02 07:01:27 +0000761 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000762 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000763 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000765
Craig Topper2617dcc2014-04-15 06:32:26 +0000766 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000767 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000768 ParseOptionalToken(lltok::kw_externally_initialized,
769 IsExternallyInitialized,
770 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000771 ParseGlobalType(IsConstant) ||
772 ParseType(Ty, TyLoc))
773 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
Chris Lattnerac161bf2009-01-02 07:01:27 +0000775 // If the linkage is specified and is external, then no initializer is
776 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000777 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000778 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 Linkage != GlobalValue::ExternalLinkage)) {
780 if (ParseGlobalValue(Ty, Init))
781 return true;
782 }
783
Duncan Sands19d0b472010-02-16 11:11:14 +0000784 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000785 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000786
David Majnemer598bd052014-12-09 05:56:09 +0000787 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000788
789 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000790 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000791 GVal = M->getNamedValue(Name);
792 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000793 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
794 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000795 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000796 } else {
797 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
798 I = ForwardRefValIDs.find(NumberedVals.size());
799 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000800 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000801 ForwardRefValIDs.erase(I);
802 }
803 }
804
David Majnemer598bd052014-12-09 05:56:09 +0000805 GlobalVariable *GV;
806 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000807 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
808 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000809 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000810 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000811 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 return Error(TyLoc,
813 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000814
David Majnemer598bd052014-12-09 05:56:09 +0000815 GV = cast<GlobalVariable>(GVal);
816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 // Move the forward-reference to the correct spot in the module.
818 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
819 }
820
821 if (Name.empty())
822 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000823
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 // Set the parsed properties on the global.
825 if (Init)
826 GV->setInitializer(Init);
827 GV->setConstant(IsConstant);
828 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
829 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000830 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000831 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000832 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000833 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000834
Chris Lattnerac161bf2009-01-02 07:01:27 +0000835 // Parse attributes on the global.
836 while (Lex.getKind() == lltok::comma) {
837 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000838
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839 if (Lex.getKind() == lltok::kw_section) {
840 Lex.Lex();
841 GV->setSection(Lex.getStrVal());
842 if (ParseToken(lltok::StringConstant, "expected global section string"))
843 return true;
844 } else if (Lex.getKind() == lltok::kw_align) {
845 unsigned Alignment;
846 if (ParseOptionalAlignment(Alignment)) return true;
847 GV->setAlignment(Alignment);
848 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000849 Comdat *C;
850 if (parseOptionalComdat(C))
851 return true;
852 if (C)
853 GV->setComdat(C);
854 else
855 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 }
857 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000858
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 return false;
860}
861
Bill Wendling63b88192013-02-06 06:52:58 +0000862/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000863/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000864bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000865 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000866 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000867 Lex.Lex();
868
David Majnemerb39e22b2014-12-09 18:33:57 +0000869 if (Lex.getKind() != lltok::AttrGrpID)
870 return TokError("expected attribute group id");
871
Bill Wendling63b88192013-02-06 06:52:58 +0000872 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000873 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000874 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000875 Lex.Lex();
876
877 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000878 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000879 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000880 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000881 ParseToken(lltok::rbrace, "expected end of attribute group"))
882 return true;
883
Bill Wendlingb32b0412013-02-08 06:32:06 +0000884 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000885 return Error(AttrGrpLoc, "attribute group has no attributes");
886
887 return false;
888}
889
Bill Wendling8b0321d2013-02-08 00:52:31 +0000890/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000891/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000892bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
893 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000894 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000895 bool HaveError = false;
896
897 B.clear();
898
Bill Wendling63b88192013-02-06 06:52:58 +0000899 while (true) {
900 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000901 if (Token == lltok::kw_builtin)
902 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000903 switch (Token) {
904 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000905 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000906 return Error(Lex.getLoc(), "unterminated attribute group");
907 case lltok::rbrace:
908 // Finished.
909 return false;
910
Bill Wendlingb32b0412013-02-08 06:32:06 +0000911 case lltok::AttrGrpID: {
912 // Allow a function to reference an attribute group:
913 //
914 // define void @foo() #1 { ... }
915 if (inAttrGrp)
916 HaveError |=
917 Error(Lex.getLoc(),
918 "cannot have an attribute group reference in an attribute group");
919
920 unsigned AttrGrpNum = Lex.getUIntVal();
921 if (inAttrGrp) break;
922
923 // Save the reference to the attribute group. We'll fill it in later.
924 FwdRefAttrGrps.push_back(AttrGrpNum);
925 break;
926 }
Bill Wendling63b88192013-02-06 06:52:58 +0000927 // Target-dependent attributes:
928 case lltok::StringConstant: {
929 std::string Attr = Lex.getStrVal();
930 Lex.Lex();
931 std::string Val;
932 if (EatIfPresent(lltok::equal) &&
933 ParseStringConstant(Val))
934 return true;
935
936 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000937 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000938 }
939
940 // Target-independent attributes:
941 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000942 // As a hack, we allow function alignment to be initially parsed as an
943 // attribute on a function declaration/definition or added to an attribute
944 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000945 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000946 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000947 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000948 if (ParseToken(lltok::equal, "expected '=' here") ||
949 ParseUInt32(Alignment))
950 return true;
951 } else {
952 if (ParseOptionalAlignment(Alignment))
953 return true;
954 }
Bill Wendling63b88192013-02-06 06:52:58 +0000955 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000956 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000957 }
958 case lltok::kw_alignstack: {
959 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000960 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000961 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000962 if (ParseToken(lltok::equal, "expected '=' here") ||
963 ParseUInt32(Alignment))
964 return true;
965 } else {
966 if (ParseOptionalStackAlignment(Alignment))
967 return true;
968 }
Bill Wendling63b88192013-02-06 06:52:58 +0000969 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000970 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000971 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000972 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000973 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000974 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000975 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000976 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000977 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
978 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
979 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
980 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
981 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
982 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
983 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
984 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
985 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
986 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000987 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000988 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
989 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
990 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
991 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
992 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
993 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
994 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
995 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
996 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
997 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
998 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000999
1000 // Error handling.
1001 case lltok::kw_inreg:
1002 case lltok::kw_signext:
1003 case lltok::kw_zeroext:
1004 HaveError |=
1005 Error(Lex.getLoc(),
1006 "invalid use of attribute on a function");
1007 break;
1008 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001009 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +00001010 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001011 case lltok::kw_nest:
1012 case lltok::kw_noalias:
1013 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001014 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001015 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001016 case lltok::kw_sret:
1017 HaveError |=
1018 Error(Lex.getLoc(),
1019 "invalid use of parameter-only attribute on a function");
1020 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001021 }
1022
1023 Lex.Lex();
1024 }
1025}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001026
1027//===----------------------------------------------------------------------===//
1028// GlobalValue Reference/Resolution Routines.
1029//===----------------------------------------------------------------------===//
1030
1031/// GetGlobalVal - Get a value with the specified name or ID, creating a
1032/// forward reference record if needed. This can return null if the value
1033/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001034GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001035 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001036 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001037 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001039 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001040 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001041
Chris Lattnerac161bf2009-01-02 07:01:27 +00001042 // Look this name up in the normal function symbol table.
1043 GlobalValue *Val =
1044 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattnerac161bf2009-01-02 07:01:27 +00001046 // If this is a forward reference for the value, see if we already created a
1047 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001048 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001049 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1050 I = ForwardRefVals.find(Name);
1051 if (I != ForwardRefVals.end())
1052 Val = I->second.first;
1053 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001054
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 // If we have the value in the symbol table or fwd-ref table, return it.
1056 if (Val) {
1057 if (Val->getType() == Ty) return Val;
1058 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001059 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001060 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001061 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001062
Chris Lattnerac161bf2009-01-02 07:01:27 +00001063 // Otherwise, create a new forward reference for this value and remember it.
1064 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001065 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001066 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001067 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001068 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001069 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1070 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001071 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001072
Chris Lattnerac161bf2009-01-02 07:01:27 +00001073 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1074 return FwdVal;
1075}
1076
Chris Lattner229907c2011-07-18 04:54:35 +00001077GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1078 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001079 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001080 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001081 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001082 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001083
Craig Topper2617dcc2014-04-15 06:32:26 +00001084 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001085
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 // If this is a forward reference for the value, see if we already created a
1087 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001088 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001089 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1090 I = ForwardRefValIDs.find(ID);
1091 if (I != ForwardRefValIDs.end())
1092 Val = I->second.first;
1093 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001094
Chris Lattnerac161bf2009-01-02 07:01:27 +00001095 // If we have the value in the symbol table or fwd-ref table, return it.
1096 if (Val) {
1097 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001098 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001099 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001100 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001101 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001102
Chris Lattnerac161bf2009-01-02 07:01:27 +00001103 // Otherwise, create a new forward reference for this value and remember it.
1104 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001105 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001106 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001107 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001108 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001109 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001110
Chris Lattnerac161bf2009-01-02 07:01:27 +00001111 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1112 return FwdVal;
1113}
1114
1115
1116//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001117// Comdat Reference/Resolution Routines.
1118//===----------------------------------------------------------------------===//
1119
1120Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1121 // Look this name up in the comdat symbol table.
1122 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1123 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1124 if (I != ComdatSymTab.end())
1125 return &I->second;
1126
1127 // Otherwise, create a new forward reference for this value and remember it.
1128 Comdat *C = M->getOrInsertComdat(Name);
1129 ForwardRefComdats[Name] = Loc;
1130 return C;
1131}
1132
1133
1134//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135// Helper Routines.
1136//===----------------------------------------------------------------------===//
1137
1138/// ParseToken - If the current token has the specified kind, eat it and return
1139/// success. Otherwise, emit the specified error and return failure.
1140bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1141 if (Lex.getKind() != T)
1142 return TokError(ErrMsg);
1143 Lex.Lex();
1144 return false;
1145}
1146
Chris Lattner3822f632009-01-02 08:05:26 +00001147/// ParseStringConstant
1148/// ::= StringConstant
1149bool LLParser::ParseStringConstant(std::string &Result) {
1150 if (Lex.getKind() != lltok::StringConstant)
1151 return TokError("expected string constant");
1152 Result = Lex.getStrVal();
1153 Lex.Lex();
1154 return false;
1155}
1156
1157/// ParseUInt32
1158/// ::= uint32
1159bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1161 return TokError("expected integer");
1162 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1163 if (Val64 != unsigned(Val64))
1164 return TokError("expected 32-bit integer (too large)");
1165 Val = Val64;
1166 Lex.Lex();
1167 return false;
1168}
1169
Hal Finkelb0407ba2014-07-18 15:51:28 +00001170/// ParseUInt64
1171/// ::= uint64
1172bool LLParser::ParseUInt64(uint64_t &Val) {
1173 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1174 return TokError("expected integer");
1175 Val = Lex.getAPSIntVal().getLimitedValue();
1176 Lex.Lex();
1177 return false;
1178}
1179
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001180/// ParseTLSModel
1181/// := 'localdynamic'
1182/// := 'initialexec'
1183/// := 'localexec'
1184bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1185 switch (Lex.getKind()) {
1186 default:
1187 return TokError("expected localdynamic, initialexec or localexec");
1188 case lltok::kw_localdynamic:
1189 TLM = GlobalVariable::LocalDynamicTLSModel;
1190 break;
1191 case lltok::kw_initialexec:
1192 TLM = GlobalVariable::InitialExecTLSModel;
1193 break;
1194 case lltok::kw_localexec:
1195 TLM = GlobalVariable::LocalExecTLSModel;
1196 break;
1197 }
1198
1199 Lex.Lex();
1200 return false;
1201}
1202
1203/// ParseOptionalThreadLocal
1204/// := /*empty*/
1205/// := 'thread_local'
1206/// := 'thread_local' '(' tlsmodel ')'
1207bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1208 TLM = GlobalVariable::NotThreadLocal;
1209 if (!EatIfPresent(lltok::kw_thread_local))
1210 return false;
1211
1212 TLM = GlobalVariable::GeneralDynamicTLSModel;
1213 if (Lex.getKind() == lltok::lparen) {
1214 Lex.Lex();
1215 return ParseTLSModel(TLM) ||
1216 ParseToken(lltok::rparen, "expected ')' after thread local model");
1217 }
1218 return false;
1219}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001220
1221/// ParseOptionalAddrSpace
1222/// := /*empty*/
1223/// := 'addrspace' '(' uint32 ')'
1224bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1225 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001226 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001229 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001230 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001231}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232
Bill Wendling34c2eb22012-12-04 23:40:58 +00001233/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1234bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1235 bool HaveError = false;
1236
1237 B.clear();
1238
1239 while (1) {
1240 lltok::Kind Token = Lex.getKind();
1241 switch (Token) {
1242 default: // End of attributes.
1243 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001244 case lltok::kw_align: {
1245 unsigned Alignment;
1246 if (ParseOptionalAlignment(Alignment))
1247 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001248 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001249 continue;
1250 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001251 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001252 case lltok::kw_dereferenceable: {
1253 uint64_t Bytes;
1254 if (ParseOptionalDereferenceableBytes(Bytes))
1255 return true;
1256 B.addDereferenceableAttr(Bytes);
1257 continue;
1258 }
Reid Klecknera534a382013-12-19 02:14:12 +00001259 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001260 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1261 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1262 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1263 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001264 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001265 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1266 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001267 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001268 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1269 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1270 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001271
Stephen Lin7577ed52013-04-20 13:16:13 +00001272 case lltok::kw_alignstack:
1273 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001274 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001275 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001276 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001277 case lltok::kw_minsize:
1278 case lltok::kw_naked:
1279 case lltok::kw_nobuiltin:
1280 case lltok::kw_noduplicate:
1281 case lltok::kw_noimplicitfloat:
1282 case lltok::kw_noinline:
1283 case lltok::kw_nonlazybind:
1284 case lltok::kw_noredzone:
1285 case lltok::kw_noreturn:
1286 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001287 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001288 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001289 case lltok::kw_returns_twice:
1290 case lltok::kw_sanitize_address:
1291 case lltok::kw_sanitize_memory:
1292 case lltok::kw_sanitize_thread:
1293 case lltok::kw_ssp:
1294 case lltok::kw_sspreq:
1295 case lltok::kw_sspstrong:
1296 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001297 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1298 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001299 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001300
Bill Wendling34c2eb22012-12-04 23:40:58 +00001301 Lex.Lex();
1302 }
1303}
1304
1305/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1306bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1307 bool HaveError = false;
1308
1309 B.clear();
1310
1311 while (1) {
1312 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001313 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001314 default: // End of attributes.
1315 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001316 case lltok::kw_dereferenceable: {
1317 uint64_t Bytes;
1318 if (ParseOptionalDereferenceableBytes(Bytes))
1319 return true;
1320 B.addDereferenceableAttr(Bytes);
1321 continue;
1322 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001323 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1324 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001325 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001326 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1327 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001328
Bill Wendling34c2eb22012-12-04 23:40:58 +00001329 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001330 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001331 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001332 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001333 case lltok::kw_nest:
1334 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001335 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001336 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001337 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001338 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001339
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001340 case lltok::kw_alignstack:
1341 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001342 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001343 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001344 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001345 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001346 case lltok::kw_minsize:
1347 case lltok::kw_naked:
1348 case lltok::kw_nobuiltin:
1349 case lltok::kw_noduplicate:
1350 case lltok::kw_noimplicitfloat:
1351 case lltok::kw_noinline:
1352 case lltok::kw_nonlazybind:
1353 case lltok::kw_noredzone:
1354 case lltok::kw_noreturn:
1355 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001356 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001357 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001358 case lltok::kw_returns_twice:
1359 case lltok::kw_sanitize_address:
1360 case lltok::kw_sanitize_memory:
1361 case lltok::kw_sanitize_thread:
1362 case lltok::kw_ssp:
1363 case lltok::kw_sspreq:
1364 case lltok::kw_sspstrong:
1365 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001366 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001367 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001368
1369 case lltok::kw_readnone:
1370 case lltok::kw_readonly:
1371 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001372 }
1373
Chris Lattnerac161bf2009-01-02 07:01:27 +00001374 Lex.Lex();
1375 }
1376}
1377
1378/// ParseOptionalLinkage
1379/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001380/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381/// ::= 'internal'
1382/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001383/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001385/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001386/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001387/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001388/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001389/// ::= 'extern_weak'
1390/// ::= 'external'
1391bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1392 HasLinkage = false;
1393 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001394 default: Res=GlobalValue::ExternalLinkage; return false;
1395 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001396 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1397 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1398 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1399 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1400 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001401 case lltok::kw_available_externally:
1402 Res = GlobalValue::AvailableExternallyLinkage;
1403 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001404 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001405 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001406 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1407 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001408 }
1409 Lex.Lex();
1410 HasLinkage = true;
1411 return false;
1412}
1413
1414/// ParseOptionalVisibility
1415/// ::= /*empty*/
1416/// ::= 'default'
1417/// ::= 'hidden'
1418/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001419///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1421 switch (Lex.getKind()) {
1422 default: Res = GlobalValue::DefaultVisibility; return false;
1423 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1424 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1425 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1426 }
1427 Lex.Lex();
1428 return false;
1429}
1430
Nico Rieck7157bb72014-01-14 15:22:47 +00001431/// ParseOptionalDLLStorageClass
1432/// ::= /*empty*/
1433/// ::= 'dllimport'
1434/// ::= 'dllexport'
1435///
1436bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1437 switch (Lex.getKind()) {
1438 default: Res = GlobalValue::DefaultStorageClass; return false;
1439 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1440 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1441 }
1442 Lex.Lex();
1443 return false;
1444}
1445
Chris Lattnerac161bf2009-01-02 07:01:27 +00001446/// ParseOptionalCallingConv
1447/// ::= /*empty*/
1448/// ::= 'ccc'
1449/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001450/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001451/// ::= 'coldcc'
1452/// ::= 'x86_stdcallcc'
1453/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001454/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001455/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001456/// ::= 'arm_apcscc'
1457/// ::= 'arm_aapcscc'
1458/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001459/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001460/// ::= 'ptx_kernel'
1461/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001462/// ::= 'spir_func'
1463/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001464/// ::= 'x86_64_sysvcc'
1465/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001466/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001467/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001468/// ::= 'preserve_mostcc'
1469/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001470/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001471/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001472///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001473bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001474 switch (Lex.getKind()) {
1475 default: CC = CallingConv::C; return false;
1476 case lltok::kw_ccc: CC = CallingConv::C; break;
1477 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1478 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1479 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1480 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001481 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001482 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001483 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1484 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1485 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001486 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001487 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1488 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001489 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1490 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001491 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001492 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1493 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001494 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001495 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001496 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1497 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001498 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001499 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001500 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001501 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001502 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001504
Chris Lattnerac161bf2009-01-02 07:01:27 +00001505 Lex.Lex();
1506 return false;
1507}
1508
Chris Lattner5c427632009-12-30 05:31:19 +00001509/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001510/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001511bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1512 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001513 do {
1514 if (Lex.getKind() != lltok::MetadataVar)
1515 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001516
Chris Lattner596760d2009-12-29 21:25:40 +00001517 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001518 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001519 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001520
Chris Lattner1797fc72009-12-29 21:53:55 +00001521 MDNode *Node;
Chris Lattner8eff0152010-04-01 05:14:45 +00001522 SMLoc Loc = Lex.getLoc();
Dan Gohmanc828c542010-08-24 02:24:03 +00001523
1524 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001525 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001526
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001527 // This code is similar to that of ParseMetadata, however it needs to
Dan Gohmanf0715b12010-08-24 14:35:45 +00001528 // have special-case code for a forward reference; see the comments on
1529 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1530 // at the top level here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001531 if (Lex.getKind() == lltok::lbrace) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001532 MDNode *N;
1533 if (ParseMDNode(N))
Dan Gohmanc828c542010-08-24 02:24:03 +00001534 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001535 Inst->setMetadata(MDK, N);
Chris Lattner8eff0152010-04-01 05:14:45 +00001536 } else {
Nick Lewycky912888f2010-09-30 21:04:13 +00001537 unsigned NodeID = 0;
Dan Gohmanc828c542010-08-24 02:24:03 +00001538 if (ParseMDNodeID(Node, NodeID))
1539 return true;
1540 if (Node) {
1541 // If we got the node, add it to the instruction.
1542 Inst->setMetadata(MDK, Node);
1543 } else {
1544 MDRef R = { Loc, MDK, NodeID };
1545 // Otherwise, remember that this should be resolved later.
1546 ForwardRefInstMetadata[Inst].push_back(R);
1547 }
Chris Lattner8eff0152010-04-01 05:14:45 +00001548 }
Chris Lattner596760d2009-12-29 21:25:40 +00001549
Manman Ren209b17c2013-09-28 00:22:27 +00001550 if (MDK == LLVMContext::MD_tbaa)
1551 InstsWithTBAATag.push_back(Inst);
1552
Chris Lattner596760d2009-12-29 21:25:40 +00001553 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001554 } while (EatIfPresent(lltok::comma));
1555 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001556}
1557
Chris Lattnerac161bf2009-01-02 07:01:27 +00001558/// ParseOptionalAlignment
1559/// ::= /* empty */
1560/// ::= 'align' 4
1561bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1562 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001563 if (!EatIfPresent(lltok::kw_align))
1564 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001565 LocTy AlignLoc = Lex.getLoc();
1566 if (ParseUInt32(Alignment)) return true;
1567 if (!isPowerOf2_32(Alignment))
1568 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001569 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001570 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001571 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001572}
1573
Hal Finkelb0407ba2014-07-18 15:51:28 +00001574/// ParseOptionalDereferenceableBytes
1575/// ::= /* empty */
1576/// ::= 'dereferenceable' '(' 4 ')'
1577bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1578 Bytes = 0;
1579 if (!EatIfPresent(lltok::kw_dereferenceable))
1580 return false;
1581 LocTy ParenLoc = Lex.getLoc();
1582 if (!EatIfPresent(lltok::lparen))
1583 return Error(ParenLoc, "expected '('");
1584 LocTy DerefLoc = Lex.getLoc();
1585 if (ParseUInt64(Bytes)) return true;
1586 ParenLoc = Lex.getLoc();
1587 if (!EatIfPresent(lltok::rparen))
1588 return Error(ParenLoc, "expected ')'");
1589 if (!Bytes)
1590 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1591 return false;
1592}
1593
Chris Lattnerb2f39502009-12-30 05:44:30 +00001594/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001595/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001596/// ::= ',' align 4
1597///
1598/// This returns with AteExtraComma set to true if it ate an excess comma at the
1599/// end.
1600bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1601 bool &AteExtraComma) {
1602 AteExtraComma = false;
1603 while (EatIfPresent(lltok::comma)) {
1604 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001605 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001606 AteExtraComma = true;
1607 return false;
1608 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001609
Chris Lattner95b0ff42010-04-23 00:50:50 +00001610 if (Lex.getKind() != lltok::kw_align)
1611 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001612
Chris Lattner95b0ff42010-04-23 00:50:50 +00001613 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001614 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001615
Devang Patelea8a4b92009-09-17 23:04:48 +00001616 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001617}
1618
Eli Friedmanfee02c62011-07-25 23:16:38 +00001619/// ParseScopeAndOrdering
1620/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1621/// else: ::=
1622///
1623/// This sets Scope and Ordering to the parsed values.
1624bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1625 AtomicOrdering &Ordering) {
1626 if (!isAtomic)
1627 return false;
1628
1629 Scope = CrossThread;
1630 if (EatIfPresent(lltok::kw_singlethread))
1631 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001632
1633 return ParseOrdering(Ordering);
1634}
1635
1636/// ParseOrdering
1637/// ::= AtomicOrdering
1638///
1639/// This sets Ordering to the parsed value.
1640bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001641 switch (Lex.getKind()) {
1642 default: return TokError("Expected ordering on atomic instruction");
1643 case lltok::kw_unordered: Ordering = Unordered; break;
1644 case lltok::kw_monotonic: Ordering = Monotonic; break;
1645 case lltok::kw_acquire: Ordering = Acquire; break;
1646 case lltok::kw_release: Ordering = Release; break;
1647 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1648 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1649 }
1650 Lex.Lex();
1651 return false;
1652}
1653
Charles Davisbe5557e2010-02-12 00:31:15 +00001654/// ParseOptionalStackAlignment
1655/// ::= /* empty */
1656/// ::= 'alignstack' '(' 4 ')'
1657bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1658 Alignment = 0;
1659 if (!EatIfPresent(lltok::kw_alignstack))
1660 return false;
1661 LocTy ParenLoc = Lex.getLoc();
1662 if (!EatIfPresent(lltok::lparen))
1663 return Error(ParenLoc, "expected '('");
1664 LocTy AlignLoc = Lex.getLoc();
1665 if (ParseUInt32(Alignment)) return true;
1666 ParenLoc = Lex.getLoc();
1667 if (!EatIfPresent(lltok::rparen))
1668 return Error(ParenLoc, "expected ')'");
1669 if (!isPowerOf2_32(Alignment))
1670 return Error(AlignLoc, "stack alignment is not a power of two");
1671 return false;
1672}
Devang Patelea8a4b92009-09-17 23:04:48 +00001673
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001674/// ParseIndexList - This parses the index list for an insert/extractvalue
1675/// instruction. This sets AteExtraComma in the case where we eat an extra
1676/// comma at the end of the line and find that it is followed by metadata.
1677/// Clients that don't allow metadata can call the version of this function that
1678/// only takes one argument.
1679///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001680/// ParseIndexList
1681/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001682///
1683bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1684 bool &AteExtraComma) {
1685 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001686
Chris Lattnerac161bf2009-01-02 07:01:27 +00001687 if (Lex.getKind() != lltok::comma)
1688 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001689
Chris Lattner3822f632009-01-02 08:05:26 +00001690 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001691 if (Lex.getKind() == lltok::MetadataVar) {
1692 AteExtraComma = true;
1693 return false;
1694 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001695 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001696 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001697 Indices.push_back(Idx);
1698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001699
Chris Lattnerac161bf2009-01-02 07:01:27 +00001700 return false;
1701}
1702
1703//===----------------------------------------------------------------------===//
1704// Type Parsing.
1705//===----------------------------------------------------------------------===//
1706
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001707/// ParseType - Parse a type.
1708bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1709 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001710 switch (Lex.getKind()) {
1711 default:
1712 return TokError("expected type");
1713 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001714 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001715 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001716 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001717 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001718 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001719 // Type ::= StructType
1720 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001721 return true;
1722 break;
1723 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 Lex.Lex(); // eat the lsquare.
1726 if (ParseArrayVectorType(Result, false))
1727 return true;
1728 break;
1729 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001730 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001731 Lex.Lex();
1732 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001733 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001734 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001735 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 } else if (ParseArrayVectorType(Result, true))
1737 return true;
1738 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001739 case lltok::LocalVar: {
1740 // Type ::= %foo
1741 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001742
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 // If the type hasn't been defined yet, create a forward definition and
1744 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001745 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001746 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001747 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001748 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001749 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001750 Lex.Lex();
1751 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001752 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001753
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001754 case lltok::LocalVarID: {
1755 // Type ::= %4
1756 if (Lex.getUIntVal() >= NumberedTypes.size())
1757 NumberedTypes.resize(Lex.getUIntVal()+1);
1758 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001759
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001760 // If the type hasn't been defined yet, create a forward definition and
1761 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001762 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001763 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001764 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001765 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001766 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001767 Lex.Lex();
1768 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001769 }
1770 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001771
1772 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 while (1) {
1774 switch (Lex.getKind()) {
1775 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001776 default:
1777 if (!AllowVoid && Result->isVoidTy())
1778 return Error(TypeLoc, "void type only allowed for function results");
1779 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001780
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001781 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001783 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001785 if (Result->isVoidTy())
1786 return TokError("pointers to void are invalid - use i8* instead");
1787 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001788 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001789 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001790 Lex.Lex();
1791 break;
1792
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001794 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001795 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001798 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001799 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001800 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801 unsigned AddrSpace;
1802 if (ParseOptionalAddrSpace(AddrSpace) ||
1803 ParseToken(lltok::star, "expected '*' in address space"))
1804 return true;
1805
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001806 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001807 break;
1808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1811 case lltok::lparen:
1812 if (ParseFunctionType(Result))
1813 return true;
1814 break;
1815 }
1816 }
1817}
1818
1819/// ParseParameterList
1820/// ::= '(' ')'
1821/// ::= '(' Arg (',' Arg)* ')'
1822/// Arg
1823/// ::= Type OptionalAttributes Value OptionalAttributes
1824bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001825 PerFunctionState &PFS, bool IsMustTailCall,
1826 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 if (ParseToken(lltok::lparen, "expected '(' in call"))
1828 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001829
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001830 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 while (Lex.getKind() != lltok::rparen) {
1832 // If this isn't the first argument, we need a comma.
1833 if (!ArgList.empty() &&
1834 ParseToken(lltok::comma, "expected ',' in argument list"))
1835 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001836
Reid Kleckner83498642014-08-26 00:33:28 +00001837 // Parse an ellipsis if this is a musttail call in a variadic function.
1838 if (Lex.getKind() == lltok::dotdotdot) {
1839 const char *Msg = "unexpected ellipsis in argument list for ";
1840 if (!IsMustTailCall)
1841 return TokError(Twine(Msg) + "non-musttail call");
1842 if (!InVarArgsFunc)
1843 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1844 Lex.Lex(); // Lex the '...', it is purely for readability.
1845 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1846 }
1847
Chris Lattnerac161bf2009-01-02 07:01:27 +00001848 // Parse the argument.
1849 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001850 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001851 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001852 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001853 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001855
Chris Lattner5b4a9622009-12-30 02:11:14 +00001856 // Otherwise, handle normal operands.
Bill Wendling34c2eb22012-12-04 23:40:58 +00001857 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner5b4a9622009-12-30 02:11:14 +00001858 return true;
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001859 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1860 AttrIndex++,
1861 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001862 }
1863
Reid Kleckner83498642014-08-26 00:33:28 +00001864 if (IsMustTailCall && InVarArgsFunc)
1865 return TokError("expected '...' at end of argument list for musttail call "
1866 "in varargs function");
1867
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868 Lex.Lex(); // Lex the ')'.
1869 return false;
1870}
1871
1872
1873
Chris Lattner2ed06b42009-01-05 18:34:07 +00001874/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001875/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876/// ::= '(' ArgTypeListI ')'
1877/// ArgTypeListI
1878/// ::= /*empty*/
1879/// ::= '...'
1880/// ::= ArgTypeList ',' '...'
1881/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001882///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001883bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1884 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885 isVarArg = false;
1886 assert(Lex.getKind() == lltok::lparen);
1887 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001888
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 if (Lex.getKind() == lltok::rparen) {
1890 // empty
1891 } else if (Lex.getKind() == lltok::dotdotdot) {
1892 isVarArg = true;
1893 Lex.Lex();
1894 } else {
1895 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001896 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001897 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001898 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001899
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001900 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001901 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001902
Chris Lattnerfdd87902009-10-05 05:54:46 +00001903 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001904 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Chris Lattnerdef19492011-06-17 06:36:20 +00001906 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907 Name = Lex.getStrVal();
1908 Lex.Lex();
1909 }
Chris Lattner3822f632009-01-02 08:05:26 +00001910
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001911 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001912 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001913
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001914 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001915 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001916 AttributeSet::get(ArgTy->getContext(),
1917 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
Chris Lattner3822f632009-01-02 08:05:26 +00001919 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001921 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923 break;
1924 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001925
Chris Lattnerac161bf2009-01-02 07:01:27 +00001926 // Otherwise must be an argument type.
1927 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001928 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001929
Chris Lattnerfdd87902009-10-05 05:54:46 +00001930 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001931 return Error(TypeLoc, "argument can not have void type");
1932
Chris Lattnerdef19492011-06-17 06:36:20 +00001933 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001934 Name = Lex.getStrVal();
1935 Lex.Lex();
1936 } else {
1937 Name = "";
1938 }
Chris Lattner3822f632009-01-02 08:05:26 +00001939
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001940 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001941 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001942
Bill Wendlingd079a442012-10-15 04:46:55 +00001943 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001944 AttributeSet::get(ArgTy->getContext(),
1945 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001946 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001947 }
1948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949
Chris Lattner3822f632009-01-02 08:05:26 +00001950 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001951}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001952
Chris Lattnerac161bf2009-01-02 07:01:27 +00001953/// ParseFunctionType
1954/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 assert(Lex.getKind() == lltok::lparen);
1957
Chris Lattnerce473c72009-01-05 08:04:33 +00001958 if (!FunctionType::isValidReturnType(Result))
1959 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001960
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001961 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001962 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001965
Chris Lattnerac161bf2009-01-02 07:01:27 +00001966 // Reject names on the arguments lists.
1967 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1968 if (!ArgList[i].Name.empty())
1969 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001970 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001971 return Error(ArgList[i].Loc,
1972 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001974
Jay Foadb804a2b2011-07-12 14:06:48 +00001975 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001976 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001977 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001979 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001980 return false;
1981}
1982
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001983/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1984/// other structs.
1985bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1986 SmallVector<Type*, 8> Elts;
1987 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001988
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 Result = StructType::get(Context, Elts, Packed);
1990 return false;
1991}
1992
1993/// ParseStructDefinition - Parse a struct in a 'type' definition.
1994bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1995 std::pair<Type*, LocTy> &Entry,
1996 Type *&ResultTy) {
1997 // If the type was already defined, diagnose the redefinition.
1998 if (Entry.first && !Entry.second.isValid())
1999 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002000
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 // If we have opaque, just return without filling in the definition for the
2002 // struct. This counts as a definition as far as the .ll file goes.
2003 if (EatIfPresent(lltok::kw_opaque)) {
2004 // This type is being defined, so clear the location to indicate this.
2005 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002006
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002008 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002009 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 ResultTy = Entry.first;
2011 return false;
2012 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 // If the type starts with '<', then it is either a packed struct or a vector.
2015 bool isPacked = EatIfPresent(lltok::less);
2016
2017 // If we don't have a struct, then we have a random type alias, which we
2018 // accept for compatibility with old files. These types are not allowed to be
2019 // forward referenced and not allowed to be recursive.
2020 if (Lex.getKind() != lltok::lbrace) {
2021 if (Entry.first)
2022 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002023
Craig Topper2617dcc2014-04-15 06:32:26 +00002024 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 if (isPacked)
2026 return ParseArrayVectorType(ResultTy, true);
2027 return ParseType(ResultTy);
2028 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 // This type is being defined, so clear the location to indicate this.
2031 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002033 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002034 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002035 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002036
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002038
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002039 SmallVector<Type*, 8> Body;
2040 if (ParseStructBody(Body) ||
2041 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2042 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002043
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002044 STy->setBody(Body, isPacked);
2045 ResultTy = STy;
2046 return false;
2047}
2048
2049
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002052/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002055/// ::= '<' '{' Type (',' Type)* '}' '>'
2056bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 assert(Lex.getKind() == lltok::lbrace);
2058 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002059
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060 // Handle the empty struct.
2061 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002063
Chris Lattnerf880ca22009-03-09 04:49:14 +00002064 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002065 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002066 if (ParseType(Ty)) return true;
2067 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002068
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002070 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002071
Chris Lattner3822f632009-01-02 08:05:26 +00002072 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002073 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002076 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002077 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002078
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002079 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002081
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002082 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083}
2084
2085/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2086/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002087/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088/// ::= '[' APSINTVAL 'x' Types ']'
2089/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002090bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002091 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2092 Lex.getAPSIntVal().getBitWidth() > 64)
2093 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002094
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 LocTy SizeLoc = Lex.getLoc();
2096 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002097 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
Chris Lattner3822f632009-01-02 08:05:26 +00002099 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2100 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101
2102 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002103 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002105
Chris Lattner3822f632009-01-02 08:05:26 +00002106 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2107 "expected end of sequential type"))
2108 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002109
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002111 if (Size == 0)
2112 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 if ((unsigned)Size != Size)
2114 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002115 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002116 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002117 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002119 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002121 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 }
2123 return false;
2124}
2125
2126//===----------------------------------------------------------------------===//
2127// Function Semantic Analysis.
2128//===----------------------------------------------------------------------===//
2129
Chris Lattner3432c622009-10-28 03:39:23 +00002130LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2131 int functionNumber)
2132 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002133
2134 // Insert unnamed arguments into the NumberedVals list.
2135 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2136 AI != E; ++AI)
2137 if (!AI->hasName())
2138 NumberedVals.push_back(AI);
2139}
2140
2141LLParser::PerFunctionState::~PerFunctionState() {
2142 // If there were any forward referenced non-basicblock values, delete them.
2143 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2144 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2145 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002146 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002147 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002149 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2153 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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 }
2160}
2161
Chris Lattner3432c622009-10-28 03:39:23 +00002162bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 if (!ForwardRefVals.empty())
2164 return P.Error(ForwardRefVals.begin()->second.second,
2165 "use of undefined value '%" + ForwardRefVals.begin()->first +
2166 "'");
2167 if (!ForwardRefValIDs.empty())
2168 return P.Error(ForwardRefValIDs.begin()->second.second,
2169 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002170 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 return false;
2172}
2173
2174
2175/// GetVal - Get a value with the specified name or ID, creating a
2176/// forward reference record if needed. This can return null if the value
2177/// exists but does not have the right type.
2178Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002179 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 // Look this name up in the normal function symbol table.
2181 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002182
Chris Lattnerac161bf2009-01-02 07:01:27 +00002183 // If this is a forward reference for the value, see if we already created a
2184 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002185 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002186 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2187 I = ForwardRefVals.find(Name);
2188 if (I != ForwardRefVals.end())
2189 Val = I->second.first;
2190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002191
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 // If we have the value in the symbol table or fwd-ref table, return it.
2193 if (Val) {
2194 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002195 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 P.Error(Loc, "'%" + Name + "' is not a basic block");
2197 else
2198 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002199 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002200 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002202
Chris Lattnerac161bf2009-01-02 07:01:27 +00002203 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002204 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002206 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 // Otherwise, create a new forward reference for this value and remember it.
2210 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002211 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002212 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 else
2214 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002215
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2217 return FwdVal;
2218}
2219
Chris Lattner229907c2011-07-18 04:54:35 +00002220Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002221 LocTy Loc) {
2222 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002223 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 // If this is a forward reference for the value, see if we already created a
2226 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002227 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2229 I = ForwardRefValIDs.find(ID);
2230 if (I != ForwardRefValIDs.end())
2231 Val = I->second.first;
2232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 // If we have the value in the symbol table or fwd-ref table, return it.
2235 if (Val) {
2236 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002237 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002238 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002240 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002241 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002242 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002245 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002247 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 // Otherwise, create a new forward reference for this value and remember it.
2251 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002252 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002253 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 else
2255 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002256
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2258 return FwdVal;
2259}
2260
2261/// SetInstName - After an instruction is parsed and inserted into its
2262/// basic block, this installs its name.
2263bool LLParser::PerFunctionState::SetInstName(int NameID,
2264 const std::string &NameStr,
2265 LocTy NameLoc, Instruction *Inst) {
2266 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002267 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 if (NameID != -1 || !NameStr.empty())
2269 return P.Error(NameLoc, "instructions returning void cannot have a name");
2270 return false;
2271 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002272
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 // If this was a numbered instruction, verify that the instruction is the
2274 // expected value and resolve any forward references.
2275 if (NameStr.empty()) {
2276 // If neither a name nor an ID was specified, just use the next ID.
2277 if (NameID == -1)
2278 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002279
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280 if (unsigned(NameID) != NumberedVals.size())
2281 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002282 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002283
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2285 ForwardRefValIDs.find(NameID);
2286 if (FI != ForwardRefValIDs.end()) {
2287 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002288 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002289 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002291 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292 ForwardRefValIDs.erase(FI);
2293 }
2294
2295 NumberedVals.push_back(Inst);
2296 return false;
2297 }
2298
2299 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2300 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2301 FI = ForwardRefVals.find(NameStr);
2302 if (FI != ForwardRefVals.end()) {
2303 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002305 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002307 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 ForwardRefVals.erase(FI);
2309 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311 // Set the name on the instruction.
2312 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002313
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002314 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 NameStr + "'");
2317 return false;
2318}
2319
2320/// GetBB - Get a basic block with the specified name or ID, creating a
2321/// forward reference record if needed.
2322BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2323 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002324 return cast_or_null<BasicBlock>(GetVal(Name,
2325 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326}
2327
2328BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002329 return cast_or_null<BasicBlock>(GetVal(ID,
2330 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331}
2332
2333/// DefineBB - Define the specified basic block, which is either named or
2334/// unnamed. If there is an error, this returns null otherwise it returns
2335/// the block being defined.
2336BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2337 LocTy Loc) {
2338 BasicBlock *BB;
2339 if (Name.empty())
2340 BB = GetBB(NumberedVals.size(), Loc);
2341 else
2342 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002343 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002344
Chris Lattnerac161bf2009-01-02 07:01:27 +00002345 // Move the block to the end of the function. Forward ref'd blocks are
2346 // inserted wherever they happen to be referenced.
2347 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 // Remove the block from forward ref sets.
2350 if (Name.empty()) {
2351 ForwardRefValIDs.erase(NumberedVals.size());
2352 NumberedVals.push_back(BB);
2353 } else {
2354 // BB forward references are already in the function symbol table.
2355 ForwardRefVals.erase(Name);
2356 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002357
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 return BB;
2359}
2360
2361//===----------------------------------------------------------------------===//
2362// Constants.
2363//===----------------------------------------------------------------------===//
2364
2365/// ParseValID - Parse an abstract value that doesn't necessarily have a
2366/// type implied. For example, if we parse "4" we don't know what integer type
2367/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002368/// sanity. PFS is used to convert function-local operands of metadata (since
2369/// metadata operands are not just parsed here but also converted to values).
2370/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002371bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 ID.Loc = Lex.getLoc();
2373 switch (Lex.getKind()) {
2374 default: return TokError("expected value token");
2375 case lltok::GlobalID: // @42
2376 ID.UIntVal = Lex.getUIntVal();
2377 ID.Kind = ValID::t_GlobalID;
2378 break;
2379 case lltok::GlobalVar: // @foo
2380 ID.StrVal = Lex.getStrVal();
2381 ID.Kind = ValID::t_GlobalName;
2382 break;
2383 case lltok::LocalVarID: // %42
2384 ID.UIntVal = Lex.getUIntVal();
2385 ID.Kind = ValID::t_LocalID;
2386 break;
2387 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002388 ID.StrVal = Lex.getStrVal();
2389 ID.Kind = ValID::t_LocalName;
2390 break;
Dan Gohman8939ba332010-07-14 18:26:50 +00002391 case lltok::exclaim: // !42, !{...}, or !"foo"
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002392 return ParseMetadataAsValue(ID, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 ID.Kind = ValID::t_APSInt;
2396 break;
2397 case lltok::APFloat:
2398 ID.APFloatVal = Lex.getAPFloatVal();
2399 ID.Kind = ValID::t_APFloat;
2400 break;
2401 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002402 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 ID.Kind = ValID::t_Constant;
2404 break;
2405 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002406 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 ID.Kind = ValID::t_Constant;
2408 break;
2409 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2410 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2411 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002412
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 case lltok::lbrace: {
2414 // ValID ::= '{' ConstVector '}'
2415 Lex.Lex();
2416 SmallVector<Constant*, 16> Elts;
2417 if (ParseGlobalValueVector(Elts) ||
2418 ParseToken(lltok::rbrace, "expected end of struct constant"))
2419 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002421 ID.ConstantStructElts = new Constant*[Elts.size()];
2422 ID.UIntVal = Elts.size();
2423 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2424 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002425 return false;
2426 }
2427 case lltok::less: {
2428 // ValID ::= '<' ConstVector '>' --> Vector.
2429 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2430 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002431 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002432
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433 SmallVector<Constant*, 16> Elts;
2434 LocTy FirstEltLoc = Lex.getLoc();
2435 if (ParseGlobalValueVector(Elts) ||
2436 (isPackedStruct &&
2437 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2438 ParseToken(lltok::greater, "expected end of constant"))
2439 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002440
Chris Lattnerac161bf2009-01-02 07:01:27 +00002441 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002442 ID.ConstantStructElts = new Constant*[Elts.size()];
2443 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2444 ID.UIntVal = Elts.size();
2445 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 return false;
2447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002448
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 if (Elts.empty())
2450 return Error(ID.Loc, "constant vector must not be empty");
2451
Duncan Sands9dff9be2010-02-15 16:12:20 +00002452 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002453 !Elts[0]->getType()->isFloatingPointTy() &&
2454 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002456 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 // Verify that all the vector elements have the same type.
2459 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2460 if (Elts[i]->getType() != Elts[0]->getType())
2461 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002462 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002463 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002464
Chris Lattner69229312011-02-15 00:14:00 +00002465 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002466 ID.Kind = ValID::t_Constant;
2467 return false;
2468 }
2469 case lltok::lsquare: { // Array Constant
2470 Lex.Lex();
2471 SmallVector<Constant*, 16> Elts;
2472 LocTy FirstEltLoc = Lex.getLoc();
2473 if (ParseGlobalValueVector(Elts) ||
2474 ParseToken(lltok::rsquare, "expected end of array constant"))
2475 return true;
2476
2477 // Handle empty element.
2478 if (Elts.empty()) {
2479 // Use undef instead of an array because it's inconvenient to determine
2480 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002481 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002482 return false;
2483 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002484
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002486 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002487 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Owen Anderson4056ca92009-07-29 22:17:13 +00002489 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002490
Chris Lattnerac161bf2009-01-02 07:01:27 +00002491 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002492 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002493 if (Elts[i]->getType() != Elts[0]->getType())
2494 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002495 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002496 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498
Jay Foad83be3612011-06-22 09:24:39 +00002499 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 ID.Kind = ValID::t_Constant;
2501 return false;
2502 }
2503 case lltok::kw_c: // c "foo"
2504 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002505 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2506 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2508 ID.Kind = ValID::t_Constant;
2509 return false;
2510
2511 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002512 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2513 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002514 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 Lex.Lex();
2516 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002517 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002518 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002519 ParseStringConstant(ID.StrVal) ||
2520 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 ParseToken(lltok::StringConstant, "expected constraint string"))
2522 return true;
2523 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002524 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002525 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 ID.Kind = ValID::t_InlineAsm;
2527 return false;
2528 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002529
Chris Lattner3432c622009-10-28 03:39:23 +00002530 case lltok::kw_blockaddress: {
2531 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2532 Lex.Lex();
2533
2534 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002535
Chris Lattner3432c622009-10-28 03:39:23 +00002536 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2537 ParseValID(Fn) ||
2538 ParseToken(lltok::comma, "expected comma in block address expression")||
2539 ParseValID(Label) ||
2540 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2541 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002542
Chris Lattner3432c622009-10-28 03:39:23 +00002543 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2544 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002545 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002546 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002547
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002548 // Try to find the function (but skip it if it's forward-referenced).
2549 GlobalValue *GV = nullptr;
2550 if (Fn.Kind == ValID::t_GlobalID) {
2551 if (Fn.UIntVal < NumberedVals.size())
2552 GV = NumberedVals[Fn.UIntVal];
2553 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2554 GV = M->getNamedValue(Fn.StrVal);
2555 }
2556 Function *F = nullptr;
2557 if (GV) {
2558 // Confirm that it's actually a function with a definition.
2559 if (!isa<Function>(GV))
2560 return Error(Fn.Loc, "expected function name in blockaddress");
2561 F = cast<Function>(GV);
2562 if (F->isDeclaration())
2563 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2564 }
2565
2566 if (!F) {
2567 // Make a global variable as a placeholder for this reference.
2568 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2569 if (!FwdRef)
2570 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2571 GlobalValue::InternalLinkage, nullptr, "");
2572 ID.ConstantVal = FwdRef;
2573 ID.Kind = ValID::t_Constant;
2574 return false;
2575 }
2576
2577 // We found the function; now find the basic block. Don't use PFS, since we
2578 // might be inside a constant expression.
2579 BasicBlock *BB;
2580 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2581 if (Label.Kind == ValID::t_LocalID)
2582 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2583 else
2584 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2585 if (!BB)
2586 return Error(Label.Loc, "referenced value is not a basic block");
2587 } else {
2588 if (Label.Kind == ValID::t_LocalID)
2589 return Error(Label.Loc, "cannot take address of numeric label after "
2590 "the function is defined");
2591 BB = dyn_cast_or_null<BasicBlock>(
2592 F->getValueSymbolTable().lookup(Label.StrVal));
2593 if (!BB)
2594 return Error(Label.Loc, "referenced value is not a basic block");
2595 }
2596
2597 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002598 ID.Kind = ValID::t_Constant;
2599 return false;
2600 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002601
Chris Lattnerac161bf2009-01-02 07:01:27 +00002602 case lltok::kw_trunc:
2603 case lltok::kw_zext:
2604 case lltok::kw_sext:
2605 case lltok::kw_fptrunc:
2606 case lltok::kw_fpext:
2607 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002608 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002609 case lltok::kw_uitofp:
2610 case lltok::kw_sitofp:
2611 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002612 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002614 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002615 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002616 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 Constant *SrcVal;
2618 Lex.Lex();
2619 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2620 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002621 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 ParseType(DestTy) ||
2623 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2624 return true;
2625 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2626 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002627 getTypeString(SrcVal->getType()) + "' to '" +
2628 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002629 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002630 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002631 ID.Kind = ValID::t_Constant;
2632 return false;
2633 }
2634 case lltok::kw_extractvalue: {
2635 Lex.Lex();
2636 Constant *Val;
2637 SmallVector<unsigned, 4> Indices;
2638 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2639 ParseGlobalTypeAndValue(Val) ||
2640 ParseIndexList(Indices) ||
2641 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2642 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002643
Chris Lattner392be582010-02-12 20:49:41 +00002644 if (!Val->getType()->isAggregateType())
2645 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002646 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002648 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 ID.Kind = ValID::t_Constant;
2650 return false;
2651 }
2652 case lltok::kw_insertvalue: {
2653 Lex.Lex();
2654 Constant *Val0, *Val1;
2655 SmallVector<unsigned, 4> Indices;
2656 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2657 ParseGlobalTypeAndValue(Val0) ||
2658 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2659 ParseGlobalTypeAndValue(Val1) ||
2660 ParseIndexList(Indices) ||
2661 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2662 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002663 if (!Val0->getType()->isAggregateType())
2664 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002665 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002667 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 ID.Kind = ValID::t_Constant;
2669 return false;
2670 }
2671 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002672 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002673 unsigned PredVal, Opc = Lex.getUIntVal();
2674 Constant *Val0, *Val1;
2675 Lex.Lex();
2676 if (ParseCmpPredicate(PredVal, Opc) ||
2677 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2678 ParseGlobalTypeAndValue(Val0) ||
2679 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2680 ParseGlobalTypeAndValue(Val1) ||
2681 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2682 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002683
Chris Lattnerac161bf2009-01-02 07:01:27 +00002684 if (Val0->getType() != Val1->getType())
2685 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002686
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002688
Chris Lattnerac161bf2009-01-02 07:01:27 +00002689 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002690 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002692 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002693 } else {
2694 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002695 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002696 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002697 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002698 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 }
2700 ID.Kind = ValID::t_Constant;
2701 return false;
2702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002703
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 // Binary Operators.
2705 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002706 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002708 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002710 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 case lltok::kw_udiv:
2712 case lltok::kw_sdiv:
2713 case lltok::kw_fdiv:
2714 case lltok::kw_urem:
2715 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002716 case lltok::kw_frem:
2717 case lltok::kw_shl:
2718 case lltok::kw_lshr:
2719 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002720 bool NUW = false;
2721 bool NSW = false;
2722 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723 unsigned Opc = Lex.getUIntVal();
2724 Constant *Val0, *Val1;
2725 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002726 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002727 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2728 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002729 if (EatIfPresent(lltok::kw_nuw))
2730 NUW = true;
2731 if (EatIfPresent(lltok::kw_nsw)) {
2732 NSW = true;
2733 if (EatIfPresent(lltok::kw_nuw))
2734 NUW = true;
2735 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002736 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2737 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002738 if (EatIfPresent(lltok::kw_exact))
2739 Exact = true;
2740 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2742 ParseGlobalTypeAndValue(Val0) ||
2743 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2744 ParseGlobalTypeAndValue(Val1) ||
2745 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2746 return true;
2747 if (Val0->getType() != Val1->getType())
2748 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002749 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002750 if (NUW)
2751 return Error(ModifierLoc, "nuw only applies to integer operations");
2752 if (NSW)
2753 return Error(ModifierLoc, "nsw only applies to integer operations");
2754 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002755 // Check that the type is valid for the operator.
2756 switch (Opc) {
2757 case Instruction::Add:
2758 case Instruction::Sub:
2759 case Instruction::Mul:
2760 case Instruction::UDiv:
2761 case Instruction::SDiv:
2762 case Instruction::URem:
2763 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002764 case Instruction::Shl:
2765 case Instruction::AShr:
2766 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002767 if (!Val0->getType()->isIntOrIntVectorTy())
2768 return Error(ID.Loc, "constexpr requires integer operands");
2769 break;
2770 case Instruction::FAdd:
2771 case Instruction::FSub:
2772 case Instruction::FMul:
2773 case Instruction::FDiv:
2774 case Instruction::FRem:
2775 if (!Val0->getType()->isFPOrFPVectorTy())
2776 return Error(ID.Loc, "constexpr requires fp operands");
2777 break;
2778 default: llvm_unreachable("Unknown binary operator!");
2779 }
Dan Gohman1b849082009-09-07 23:54:19 +00002780 unsigned Flags = 0;
2781 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2782 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002783 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002784 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002785 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002786 ID.Kind = ValID::t_Constant;
2787 return false;
2788 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002789
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 case lltok::kw_and:
2792 case lltok::kw_or:
2793 case lltok::kw_xor: {
2794 unsigned Opc = Lex.getUIntVal();
2795 Constant *Val0, *Val1;
2796 Lex.Lex();
2797 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2798 ParseGlobalTypeAndValue(Val0) ||
2799 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2800 ParseGlobalTypeAndValue(Val1) ||
2801 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2802 return true;
2803 if (Val0->getType() != Val1->getType())
2804 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002805 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 return Error(ID.Loc,
2807 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002808 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 ID.Kind = ValID::t_Constant;
2810 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811 }
2812
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 case lltok::kw_getelementptr:
2814 case lltok::kw_shufflevector:
2815 case lltok::kw_insertelement:
2816 case lltok::kw_extractelement:
2817 case lltok::kw_select: {
2818 unsigned Opc = Lex.getUIntVal();
2819 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002820 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002822 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002823 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2825 ParseGlobalValueVector(Elts) ||
2826 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2827 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002828
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002830 if (Elts.size() == 0 ||
2831 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002833
Jay Foaded8db7d2011-07-21 14:31:17 +00002834 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002835 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002836 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002837 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2838 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002839 } else if (Opc == Instruction::Select) {
2840 if (Elts.size() != 3)
2841 return Error(ID.Loc, "expected three operands to select");
2842 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2843 Elts[2]))
2844 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002845 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002846 } else if (Opc == Instruction::ShuffleVector) {
2847 if (Elts.size() != 3)
2848 return Error(ID.Loc, "expected three operands to shufflevector");
2849 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2850 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002851 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002852 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 } else if (Opc == Instruction::ExtractElement) {
2854 if (Elts.size() != 2)
2855 return Error(ID.Loc, "expected two operands to extractelement");
2856 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2857 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002858 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002859 } else {
2860 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2861 if (Elts.size() != 3)
2862 return Error(ID.Loc, "expected three operands to insertelement");
2863 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2864 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002865 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002866 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002867 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 ID.Kind = ValID::t_Constant;
2870 return false;
2871 }
2872 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002873
Chris Lattnerac161bf2009-01-02 07:01:27 +00002874 Lex.Lex();
2875 return false;
2876}
2877
2878/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002879bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002880 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002881 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002882 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002883 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002884 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002885 if (V && !(C = dyn_cast<Constant>(V)))
2886 return Error(ID.Loc, "global values must be constants");
2887 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002888}
2889
Victor Hernandez9d75c962010-01-11 22:31:58 +00002890bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002891 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002892 return ParseType(Ty) ||
2893 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002894}
2895
David Majnemerdad0a642014-06-27 18:19:56 +00002896bool LLParser::parseOptionalComdat(Comdat *&C) {
2897 C = nullptr;
2898 if (!EatIfPresent(lltok::kw_comdat))
2899 return false;
2900 if (Lex.getKind() != lltok::ComdatVar)
2901 return TokError("expected comdat variable");
2902 LocTy Loc = Lex.getLoc();
2903 StringRef Name = Lex.getStrVal();
2904 C = getComdat(Name, Loc);
2905 Lex.Lex();
2906 return false;
2907}
2908
Victor Hernandez9d75c962010-01-11 22:31:58 +00002909/// ParseGlobalValueVector
2910/// ::= /*empty*/
2911/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002912bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002913 // Empty list.
2914 if (Lex.getKind() == lltok::rbrace ||
2915 Lex.getKind() == lltok::rsquare ||
2916 Lex.getKind() == lltok::greater ||
2917 Lex.getKind() == lltok::rparen)
2918 return false;
2919
2920 Constant *C;
2921 if (ParseGlobalTypeAndValue(C)) return true;
2922 Elts.push_back(C);
2923
2924 while (EatIfPresent(lltok::comma)) {
2925 if (ParseGlobalTypeAndValue(C)) return true;
2926 Elts.push_back(C);
2927 }
2928
2929 return false;
2930}
2931
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002932bool LLParser::ParseMDNode(MDNode *&MD) {
2933 SmallVector<Metadata *, 16> Elts;
2934 if (ParseMDNodeVector(Elts, nullptr))
Dan Gohmanc828c542010-08-24 02:24:03 +00002935 return true;
2936
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002937 MD = MDNode::get(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002938 return false;
2939}
2940
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002941bool LLParser::ParseMDNodeOrLocal(Metadata *&MD, PerFunctionState *PFS) {
2942 SmallVector<Metadata *, 16> Elts;
2943 if (ParseMDNodeVector(Elts, PFS))
2944 return true;
2945
2946 // Check for function-local metadata masquerading as an MDNode.
2947 if (PFS && Elts.size() == 1 && Elts[0] && isa<LocalAsMetadata>(Elts[0])) {
2948 MD = Elts[0];
2949 return false;
2950 }
2951
2952 MD = MDNode::get(Context, Elts);
2953 return false;
2954}
2955
2956bool LLParser::ParseMetadataAsValue(ValID &ID, PerFunctionState *PFS) {
2957 Metadata *MD;
2958 if (ParseMetadata(MD, PFS))
2959 return true;
2960
2961 ID.Kind = ValID::t_Metadata;
2962 ID.MetadataVal = MetadataAsValue::get(Context, MD);
2963 return false;
2964}
2965
2966/// ParseMetadata
Dan Gohman8939ba332010-07-14 18:26:50 +00002967/// ::= !42
2968/// ::= !{...}
2969/// ::= !"string"
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002970bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Dan Gohman8939ba332010-07-14 18:26:50 +00002971 assert(Lex.getKind() == lltok::exclaim);
2972 Lex.Lex();
2973
2974 // MDNode:
2975 // !{ ... }
Dan Gohmanc828c542010-08-24 02:24:03 +00002976 if (Lex.getKind() == lltok::lbrace)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002977 return ParseMDNodeOrLocal(MD, PFS);
Dan Gohman8939ba332010-07-14 18:26:50 +00002978
2979 // Standalone metadata reference
2980 // !42
2981 if (Lex.getKind() == lltok::APSInt) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002982 MDNode *N;
2983 if (ParseMDNodeID(N))
2984 return true;
2985 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00002986 return false;
2987 }
2988
2989 // MDString:
2990 // ::= '!' STRINGCONSTANT
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002991 MDString *S;
2992 if (ParseMDString(S))
2993 return true;
2994 MD = S;
Dan Gohman8939ba332010-07-14 18:26:50 +00002995 return false;
2996}
2997
Victor Hernandez9d75c962010-01-11 22:31:58 +00002998
2999//===----------------------------------------------------------------------===//
3000// Function Parsing.
3001//===----------------------------------------------------------------------===//
3002
Chris Lattner229907c2011-07-18 04:54:35 +00003003bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003004 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003005 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003007
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003009 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003010 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3011 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003012 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003014 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3015 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003016 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003017 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003018 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003019 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003020 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003021 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3022 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003023 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003024 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003025 return false;
3026 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003027 case ValID::t_Metadata:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003028 if (!Ty->isMetadataTy())
3029 return Error(ID.Loc, "metadata value must have metadata type");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003030 V = ID.MetadataVal;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003031 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 case ValID::t_GlobalName:
3033 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003034 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 case ValID::t_GlobalID:
3036 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003037 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003039 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003040 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003041 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003042 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 return false;
3044 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003045 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3047 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003048
Dan Gohman518cda42011-12-17 00:04:22 +00003049 // The lexer has no type info, so builds all half, float, and double FP
3050 // constants as double. Fix this here. Long double does not need this.
3051 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003053 if (Ty->isHalfTy())
3054 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3055 &Ignored);
3056 else if (Ty->isFloatTy())
3057 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3058 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003060 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003061
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003062 if (V->getType() != Ty)
3063 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003064 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003065
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 return false;
3067 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003068 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003069 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003070 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003071 return false;
3072 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003073 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003074 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003075 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003076 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003078 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003079 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003080 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003081 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003082 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003084 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003085 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003087 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003088 return false;
3089 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003090 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003091 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003092
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 V = ID.ConstantVal;
3094 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003095 case ValID::t_ConstantStruct:
3096 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003097 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003098 if (ST->getNumElements() != ID.UIntVal)
3099 return Error(ID.Loc,
3100 "initializer with struct type has wrong # elements");
3101 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3102 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003104 // Verify that the elements are compatible with the structtype.
3105 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3106 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3107 return Error(ID.Loc, "element " + Twine(i) +
3108 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003109
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003110 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3111 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003112 } else
3113 return Error(ID.Loc, "constant expression type mismatch");
3114 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003115 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003116 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003117}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003118
Chris Lattner229907c2011-07-18 04:54:35 +00003119bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003120 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003121 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003122 return ParseValID(ID, PFS) ||
3123 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124}
3125
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003126bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003127 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003128 return ParseType(Ty) ||
3129 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003130}
3131
Chris Lattner3ed871f2009-10-27 19:13:16 +00003132bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3133 PerFunctionState &PFS) {
3134 Value *V;
3135 Loc = Lex.getLoc();
3136 if (ParseTypeAndValue(V, PFS)) return true;
3137 if (!isa<BasicBlock>(V))
3138 return Error(Loc, "expected a basic block");
3139 BB = cast<BasicBlock>(V);
3140 return false;
3141}
3142
3143
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144/// FunctionHeader
3145/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003146/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003147/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003148bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3149 // Parse the linkage.
3150 LocTy LinkageLoc = Lex.getLoc();
3151 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003152
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003153 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003154 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003155 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003156 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003157 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 LocTy RetTypeLoc = Lex.getLoc();
3159 if (ParseOptionalLinkage(Linkage) ||
3160 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003161 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003162 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003163 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003164 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 return true;
3166
3167 // Verify that the linkage is ok.
3168 switch ((GlobalValue::LinkageTypes)Linkage) {
3169 case GlobalValue::ExternalLinkage:
3170 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003171 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 if (isDefine)
3173 return Error(LinkageLoc, "invalid linkage for function definition");
3174 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003175 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003177 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003178 case GlobalValue::LinkOnceAnyLinkage:
3179 case GlobalValue::LinkOnceODRLinkage:
3180 case GlobalValue::WeakAnyLinkage:
3181 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003182 if (!isDefine)
3183 return Error(LinkageLoc, "invalid linkage for function declaration");
3184 break;
3185 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003186 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003187 return Error(LinkageLoc, "invalid function linkage type");
3188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003189
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003190 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3191 return Error(LinkageLoc,
3192 "symbol with local linkage must have default visibility");
3193
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003194 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003195 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003196
Chris Lattnerac161bf2009-01-02 07:01:27 +00003197 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003198
3199 std::string FunctionName;
3200 if (Lex.getKind() == lltok::GlobalVar) {
3201 FunctionName = Lex.getStrVal();
3202 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3203 unsigned NameID = Lex.getUIntVal();
3204
3205 if (NameID != NumberedVals.size())
3206 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003207 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003208 } else {
3209 return TokError("expected function name");
3210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003211
Chris Lattner3822f632009-01-02 08:05:26 +00003212 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003213
Chris Lattner3822f632009-01-02 08:05:26 +00003214 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003215 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003217 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003219 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003220 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003221 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003222 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003224 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003225 bool UnnamedAddr;
3226 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003227 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003228 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003229 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003230
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003231 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003232 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3233 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003234 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003235 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003236 (EatIfPresent(lltok::kw_section) &&
3237 ParseStringConstant(Section)) ||
David Majnemerdad0a642014-06-27 18:19:56 +00003238 parseOptionalComdat(C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003239 ParseOptionalAlignment(Alignment) ||
3240 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003241 ParseStringConstant(GC)) ||
3242 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003243 ParseGlobalTypeAndValue(Prefix)) ||
3244 (EatIfPresent(lltok::kw_prologue) &&
3245 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003246 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247
Michael Gottesman41748d72013-06-27 00:25:01 +00003248 if (FuncAttrs.contains(Attribute::Builtin))
3249 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003250
Chris Lattnerac161bf2009-01-02 07:01:27 +00003251 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003252 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003253 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003254 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003256
Chris Lattnerac161bf2009-01-02 07:01:27 +00003257 // Okay, if we got here, the function is syntactically valid. Convert types
3258 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003259 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003260 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003261
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003262 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003263 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3264 AttributeSet::ReturnIndex,
3265 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003266
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003268 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003269 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3270 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003271 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3272 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 }
3274
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003275 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003276 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3277 AttributeSet::FunctionIndex,
3278 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003279
Bill Wendlinge94d8432012-12-07 23:16:57 +00003280 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003281
Bill Wendling749a43d2012-12-30 13:50:49 +00003282 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003283 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3284
Chris Lattner229907c2011-07-18 04:54:35 +00003285 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003286 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003287 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288
Craig Topper2617dcc2014-04-15 06:32:26 +00003289 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 if (!FunctionName.empty()) {
3291 // If this was a definition of a forward reference, remove the definition
3292 // from the forward reference table and fill in the forward ref.
3293 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3294 ForwardRefVals.find(FunctionName);
3295 if (FRVI != ForwardRefVals.end()) {
3296 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003297 if (!Fn)
3298 return Error(FRVI->second.second, "invalid forward reference to "
3299 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003300 if (Fn->getType() != PFT)
3301 return Error(FRVI->second.second, "invalid forward reference to "
3302 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003303
Chris Lattnerac161bf2009-01-02 07:01:27 +00003304 ForwardRefVals.erase(FRVI);
3305 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003306 // Reject redefinitions.
3307 return Error(NameLoc, "invalid redefinition of function '" +
3308 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003309 } else if (M->getNamedValue(FunctionName)) {
3310 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003311 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003312
Dan Gohman399d6ae2009-08-29 23:37:49 +00003313 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003314 // If this is a definition of a forward referenced function, make sure the
3315 // types agree.
3316 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3317 = ForwardRefValIDs.find(NumberedVals.size());
3318 if (I != ForwardRefValIDs.end()) {
3319 Fn = cast<Function>(I->second.first);
3320 if (Fn->getType() != PFT)
3321 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003322 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 ForwardRefValIDs.erase(I);
3324 }
3325 }
3326
Craig Topper2617dcc2014-04-15 06:32:26 +00003327 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003328 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3329 else // Move the forward-reference to the correct spot in the module.
3330 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3331
3332 if (FunctionName.empty())
3333 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003334
Chris Lattnerac161bf2009-01-02 07:01:27 +00003335 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3336 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003337 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003338 Fn->setCallingConv(CC);
3339 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003340 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003341 Fn->setAlignment(Alignment);
3342 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003343 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003344 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003345 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003346 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003347 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003348
Chris Lattnerac161bf2009-01-02 07:01:27 +00003349 // Add all of the arguments we parsed to the function.
3350 Function::arg_iterator ArgIt = Fn->arg_begin();
3351 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3352 // If the argument has a name, insert it into the argument symbol table.
3353 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003354
Chris Lattnerac161bf2009-01-02 07:01:27 +00003355 // Set the name, if it conflicted, it will be auto-renamed.
3356 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003357
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003358 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003359 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3360 ArgList[i].Name + "'");
3361 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003362
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003363 if (isDefine)
3364 return false;
3365
Robin Morisset039781e2014-08-29 21:53:01 +00003366 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003367 ValID ID;
3368 if (FunctionName.empty()) {
3369 ID.Kind = ValID::t_GlobalID;
3370 ID.UIntVal = NumberedVals.size() - 1;
3371 } else {
3372 ID.Kind = ValID::t_GlobalName;
3373 ID.StrVal = FunctionName;
3374 }
3375 auto Blocks = ForwardRefBlockAddresses.find(ID);
3376 if (Blocks != ForwardRefBlockAddresses.end())
3377 return Error(Blocks->first.Loc,
3378 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003379 return false;
3380}
3381
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003382bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3383 ValID ID;
3384 if (FunctionNumber == -1) {
3385 ID.Kind = ValID::t_GlobalName;
3386 ID.StrVal = F.getName();
3387 } else {
3388 ID.Kind = ValID::t_GlobalID;
3389 ID.UIntVal = FunctionNumber;
3390 }
3391
3392 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3393 if (Blocks == P.ForwardRefBlockAddresses.end())
3394 return false;
3395
3396 for (const auto &I : Blocks->second) {
3397 const ValID &BBID = I.first;
3398 GlobalValue *GV = I.second;
3399
3400 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3401 "Expected local id or name");
3402 BasicBlock *BB;
3403 if (BBID.Kind == ValID::t_LocalName)
3404 BB = GetBB(BBID.StrVal, BBID.Loc);
3405 else
3406 BB = GetBB(BBID.UIntVal, BBID.Loc);
3407 if (!BB)
3408 return P.Error(BBID.Loc, "referenced value is not a basic block");
3409
3410 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3411 GV->eraseFromParent();
3412 }
3413
3414 P.ForwardRefBlockAddresses.erase(Blocks);
3415 return false;
3416}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003417
3418/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003419/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003420bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003421 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003422 return TokError("expected '{' in function body");
3423 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003424
Chris Lattner3432c622009-10-28 03:39:23 +00003425 int FunctionNumber = -1;
3426 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003427
Chris Lattner3432c622009-10-28 03:39:23 +00003428 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003429
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003430 // Resolve block addresses and allow basic blocks to be forward-declared
3431 // within this function.
3432 if (PFS.resolveForwardRefBlockAddresses())
3433 return true;
3434 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3435
Chris Lattnerbbddd962010-01-09 19:20:07 +00003436 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003437 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003438 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003439
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003440 while (Lex.getKind() != lltok::rbrace &&
3441 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003442 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003443
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003444 while (Lex.getKind() != lltok::rbrace)
3445 if (ParseUseListOrder(&PFS))
3446 return true;
3447
Chris Lattnerac161bf2009-01-02 07:01:27 +00003448 // Eat the }.
3449 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003450
Chris Lattnerac161bf2009-01-02 07:01:27 +00003451 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003452 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003453}
3454
3455/// ParseBasicBlock
3456/// ::= LabelStr? Instruction*
3457bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3458 // If this basic block starts out with a name, remember it.
3459 std::string Name;
3460 LocTy NameLoc = Lex.getLoc();
3461 if (Lex.getKind() == lltok::LabelStr) {
3462 Name = Lex.getStrVal();
3463 Lex.Lex();
3464 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003465
Chris Lattnerac161bf2009-01-02 07:01:27 +00003466 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003467 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003468
Chris Lattnerac161bf2009-01-02 07:01:27 +00003469 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003470
Chris Lattnerac161bf2009-01-02 07:01:27 +00003471 // Parse the instructions in this block until we get a terminator.
3472 Instruction *Inst;
3473 do {
3474 // This instruction may have three possibilities for a name: a) none
3475 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3476 LocTy NameLoc = Lex.getLoc();
3477 int NameID = -1;
3478 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003479
Chris Lattnerac161bf2009-01-02 07:01:27 +00003480 if (Lex.getKind() == lltok::LocalVarID) {
3481 NameID = Lex.getUIntVal();
3482 Lex.Lex();
3483 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3484 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003485 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003486 NameStr = Lex.getStrVal();
3487 Lex.Lex();
3488 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3489 return true;
3490 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003491
Chris Lattner77b89dc2009-12-30 05:23:43 +00003492 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003493 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003494 case InstError: return true;
3495 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003496 BB->getInstList().push_back(Inst);
3497
Chris Lattner77b89dc2009-12-30 05:23:43 +00003498 // With a normal result, we check to see if the instruction is followed by
3499 // a comma and metadata.
3500 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003501 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003502 return true;
3503 break;
3504 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003505 BB->getInstList().push_back(Inst);
3506
Chris Lattner77b89dc2009-12-30 05:23:43 +00003507 // If the instruction parser ate an extra comma at the end of it, it
3508 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003509 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003510 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003511 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003512 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003513
Chris Lattnerac161bf2009-01-02 07:01:27 +00003514 // Set the name on the instruction.
3515 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3516 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003517
Chris Lattnerac161bf2009-01-02 07:01:27 +00003518 return false;
3519}
3520
3521//===----------------------------------------------------------------------===//
3522// Instruction Parsing.
3523//===----------------------------------------------------------------------===//
3524
3525/// ParseInstruction - Parse one of the many different instructions.
3526///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003527int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3528 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 lltok::Kind Token = Lex.getKind();
3530 if (Token == lltok::Eof)
3531 return TokError("found end of file when expecting more instructions");
3532 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003533 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003534 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003535
Chris Lattnerac161bf2009-01-02 07:01:27 +00003536 switch (Token) {
3537 default: return Error(Loc, "expected instruction opcode");
3538 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003539 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003540 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3541 case lltok::kw_br: return ParseBr(Inst, PFS);
3542 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003543 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003544 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003545 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003546 // Binary Operators.
3547 case lltok::kw_add:
3548 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003549 case lltok::kw_mul:
3550 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003551 bool NUW = EatIfPresent(lltok::kw_nuw);
3552 bool NSW = EatIfPresent(lltok::kw_nsw);
3553 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003554
Chris Lattnera676c0f2011-02-07 16:40:21 +00003555 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003556
Chris Lattnera676c0f2011-02-07 16:40:21 +00003557 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3558 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3559 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003560 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003561 case lltok::kw_fadd:
3562 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003563 case lltok::kw_fmul:
3564 case lltok::kw_fdiv:
3565 case lltok::kw_frem: {
3566 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3567 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3568 if (Res != 0)
3569 return Res;
3570 if (FMF.any())
3571 Inst->setFastMathFlags(FMF);
3572 return 0;
3573 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003574
Chris Lattner35315d02011-02-06 21:44:57 +00003575 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003576 case lltok::kw_udiv:
3577 case lltok::kw_lshr:
3578 case lltok::kw_ashr: {
3579 bool Exact = EatIfPresent(lltok::kw_exact);
3580
3581 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3582 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3583 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003584 }
3585
Chris Lattnerac161bf2009-01-02 07:01:27 +00003586 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003587 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003588 case lltok::kw_and:
3589 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003590 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003591 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003592 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003593 // Casts.
3594 case lltok::kw_trunc:
3595 case lltok::kw_zext:
3596 case lltok::kw_sext:
3597 case lltok::kw_fptrunc:
3598 case lltok::kw_fpext:
3599 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003600 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003601 case lltok::kw_uitofp:
3602 case lltok::kw_sitofp:
3603 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003604 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003605 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003606 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003607 // Other.
3608 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003609 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003610 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3611 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3612 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3613 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003614 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003615 // Call.
3616 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3617 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3618 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003619 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003620 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003621 case lltok::kw_load: return ParseLoad(Inst, PFS);
3622 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003623 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3624 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003625 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003626 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3627 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3628 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3629 }
3630}
3631
3632/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3633bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003634 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003635 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003636 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003637 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3638 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3639 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3640 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3641 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3642 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3643 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3644 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3645 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3646 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3647 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3648 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3649 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3650 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3651 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3652 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3653 }
3654 } else {
3655 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003656 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003657 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3658 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3659 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3660 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3661 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3662 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3663 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3664 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3665 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3666 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3667 }
3668 }
3669 Lex.Lex();
3670 return false;
3671}
3672
3673//===----------------------------------------------------------------------===//
3674// Terminator Instructions.
3675//===----------------------------------------------------------------------===//
3676
3677/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003678/// ::= 'ret' void (',' !dbg, !1)*
3679/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003680bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003681 PerFunctionState &PFS) {
3682 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003683 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003684 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003685
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003686 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003687
Chris Lattnerfdd87902009-10-05 05:54:46 +00003688 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003689 if (!ResType->isVoidTy())
3690 return Error(TypeLoc, "value doesn't match function result type '" +
3691 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003692
Owen Anderson55f1c092009-08-13 21:58:54 +00003693 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003694 return false;
3695 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003696
Chris Lattnerac161bf2009-01-02 07:01:27 +00003697 Value *RV;
3698 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003699
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003700 if (ResType != RV->getType())
3701 return Error(TypeLoc, "value doesn't match function result type '" +
3702 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003703
Owen Anderson55f1c092009-08-13 21:58:54 +00003704 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003705 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003706}
3707
3708
3709/// ParseBr
3710/// ::= 'br' TypeAndValue
3711/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3712bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3713 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003714 Value *Op0;
3715 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003716 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003717
Chris Lattnerac161bf2009-01-02 07:01:27 +00003718 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3719 Inst = BranchInst::Create(BB);
3720 return false;
3721 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003722
Owen Anderson55f1c092009-08-13 21:58:54 +00003723 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003724 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003725
Chris Lattnerac161bf2009-01-02 07:01:27 +00003726 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003727 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003728 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003729 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003730 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003731
Chris Lattner3ed871f2009-10-27 19:13:16 +00003732 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003733 return false;
3734}
3735
3736/// ParseSwitch
3737/// Instruction
3738/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3739/// JumpTable
3740/// ::= (TypeAndValue ',' TypeAndValue)*
3741bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3742 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003743 Value *Cond;
3744 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003745 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3746 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003747 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003748 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3749 return true;
3750
Duncan Sands19d0b472010-02-16 11:11:14 +00003751 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003752 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003753
Chris Lattnerac161bf2009-01-02 07:01:27 +00003754 // Parse the jump table pairs.
3755 SmallPtrSet<Value*, 32> SeenCases;
3756 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3757 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003758 Value *Constant;
3759 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003760
Chris Lattnerac161bf2009-01-02 07:01:27 +00003761 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3762 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003763 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003764 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003765
David Blaikie70573dc2014-11-19 07:49:26 +00003766 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003767 return Error(CondLoc, "duplicate case value in switch");
3768 if (!isa<ConstantInt>(Constant))
3769 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003770
Chris Lattner3ed871f2009-10-27 19:13:16 +00003771 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003772 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003773
Chris Lattnerac161bf2009-01-02 07:01:27 +00003774 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003775
Chris Lattner3ed871f2009-10-27 19:13:16 +00003776 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003777 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3778 SI->addCase(Table[i].first, Table[i].second);
3779 Inst = SI;
3780 return false;
3781}
3782
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003783/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003784/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003785/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3786bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003787 LocTy AddrLoc;
3788 Value *Address;
3789 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003790 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3791 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003792 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003793
Duncan Sands19d0b472010-02-16 11:11:14 +00003794 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003795 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003796
Chris Lattner3ed871f2009-10-27 19:13:16 +00003797 // Parse the destination list.
3798 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003799
Chris Lattner3ed871f2009-10-27 19:13:16 +00003800 if (Lex.getKind() != lltok::rsquare) {
3801 BasicBlock *DestBB;
3802 if (ParseTypeAndBasicBlock(DestBB, PFS))
3803 return true;
3804 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003805
Chris Lattner3ed871f2009-10-27 19:13:16 +00003806 while (EatIfPresent(lltok::comma)) {
3807 if (ParseTypeAndBasicBlock(DestBB, PFS))
3808 return true;
3809 DestList.push_back(DestBB);
3810 }
3811 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003812
Chris Lattner3ed871f2009-10-27 19:13:16 +00003813 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3814 return true;
3815
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003816 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003817 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3818 IBI->addDestination(DestList[i]);
3819 Inst = IBI;
3820 return false;
3821}
3822
3823
Chris Lattnerac161bf2009-01-02 07:01:27 +00003824/// ParseInvoke
3825/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3826/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3827bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3828 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003829 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003830 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003831 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003832 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003833 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003834 LocTy RetTypeLoc;
3835 ValID CalleeID;
3836 SmallVector<ParamInfo, 16> ArgList;
3837
Chris Lattner3ed871f2009-10-27 19:13:16 +00003838 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003839 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003840 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003841 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003842 ParseValID(CalleeID) ||
3843 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003844 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3845 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003846 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003847 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003848 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003849 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003850 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003851
Chris Lattnerac161bf2009-01-02 07:01:27 +00003852 // If RetType is a non-function pointer type, then this is the short syntax
3853 // for the call, which means that RetType is just the return type. Infer the
3854 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003855 PointerType *PFTy = nullptr;
3856 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003857 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3858 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3859 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003860 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003861 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3862 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003863
Chris Lattnerac161bf2009-01-02 07:01:27 +00003864 if (!FunctionType::isValidReturnType(RetType))
3865 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003866
Owen Anderson4056ca92009-07-29 22:17:13 +00003867 Ty = FunctionType::get(RetType, ParamTypes, false);
3868 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003869 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003870
Chris Lattnerac161bf2009-01-02 07:01:27 +00003871 // Look up the callee.
3872 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003873 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003874
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003875 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003876 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003877 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003878 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3879 AttributeSet::ReturnIndex,
3880 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003881
Chris Lattnerac161bf2009-01-02 07:01:27 +00003882 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003883
Chris Lattnerac161bf2009-01-02 07:01:27 +00003884 // Loop through FunctionType's arguments and ensure they are specified
3885 // correctly. Also, gather any parameter attributes.
3886 FunctionType::param_iterator I = Ty->param_begin();
3887 FunctionType::param_iterator E = Ty->param_end();
3888 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003889 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003890 if (I != E) {
3891 ExpectedTy = *I++;
3892 } else if (!Ty->isVarArg()) {
3893 return Error(ArgList[i].Loc, "too many arguments specified");
3894 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003895
Chris Lattnerac161bf2009-01-02 07:01:27 +00003896 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3897 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003898 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003899 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003900 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3901 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003902 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3903 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003904 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003905
Chris Lattnerac161bf2009-01-02 07:01:27 +00003906 if (I != E)
3907 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003908
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003909 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003910 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3911 AttributeSet::FunctionIndex,
3912 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003913
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003914 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003915 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003916
Jay Foad5bd375a2011-07-15 08:37:34 +00003917 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003918 II->setCallingConv(CC);
3919 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003920 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003921 Inst = II;
3922 return false;
3923}
3924
Bill Wendlingf891bf82011-07-31 06:30:59 +00003925/// ParseResume
3926/// ::= 'resume' TypeAndValue
3927bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3928 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003929 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3930 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931
Bill Wendlingf891bf82011-07-31 06:30:59 +00003932 ResumeInst *RI = ResumeInst::Create(Exn);
3933 Inst = RI;
3934 return false;
3935}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003936
3937//===----------------------------------------------------------------------===//
3938// Binary Operators.
3939//===----------------------------------------------------------------------===//
3940
3941/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003942/// ::= ArithmeticOps TypeAndValue ',' Value
3943///
3944/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3945/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003946bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003947 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003948 LocTy Loc; Value *LHS, *RHS;
3949 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3950 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3951 ParseValue(LHS->getType(), RHS, PFS))
3952 return true;
3953
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003954 bool Valid;
3955 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003956 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003957 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003958 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3959 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003960 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003961 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3962 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003963 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003964
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003965 if (!Valid)
3966 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003967
Chris Lattnerac161bf2009-01-02 07:01:27 +00003968 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3969 return false;
3970}
3971
3972/// ParseLogical
3973/// ::= ArithmeticOps TypeAndValue ',' Value {
3974bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3975 unsigned Opc) {
3976 LocTy Loc; Value *LHS, *RHS;
3977 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3978 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3979 ParseValue(LHS->getType(), RHS, PFS))
3980 return true;
3981
Duncan Sands9dff9be2010-02-15 16:12:20 +00003982 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003983 return Error(Loc,"instruction requires integer or integer vector operands");
3984
3985 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3986 return false;
3987}
3988
3989
3990/// ParseCompare
3991/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3992/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003993bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3994 unsigned Opc) {
3995 // Parse the integer/fp comparison predicate.
3996 LocTy Loc;
3997 unsigned Pred;
3998 Value *LHS, *RHS;
3999 if (ParseCmpPredicate(Pred, Opc) ||
4000 ParseTypeAndValue(LHS, Loc, PFS) ||
4001 ParseToken(lltok::comma, "expected ',' after compare value") ||
4002 ParseValue(LHS->getType(), RHS, PFS))
4003 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004004
Chris Lattnerac161bf2009-01-02 07:01:27 +00004005 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004006 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004007 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004008 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004009 } else {
4010 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004011 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004012 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004014 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004015 }
4016 return false;
4017}
4018
4019//===----------------------------------------------------------------------===//
4020// Other Instructions.
4021//===----------------------------------------------------------------------===//
4022
4023
4024/// ParseCast
4025/// ::= CastOpc TypeAndValue 'to' Type
4026bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4027 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004028 LocTy Loc;
4029 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004030 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004031 if (ParseTypeAndValue(Op, Loc, PFS) ||
4032 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4033 ParseType(DestTy))
4034 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004035
Chris Lattner89d856e2009-03-01 00:53:13 +00004036 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4037 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004038 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004039 getTypeString(Op->getType()) + "' to '" +
4040 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004041 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004042 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4043 return false;
4044}
4045
4046/// ParseSelect
4047/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4048bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4049 LocTy Loc;
4050 Value *Op0, *Op1, *Op2;
4051 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4052 ParseToken(lltok::comma, "expected ',' after select condition") ||
4053 ParseTypeAndValue(Op1, PFS) ||
4054 ParseToken(lltok::comma, "expected ',' after select value") ||
4055 ParseTypeAndValue(Op2, PFS))
4056 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004057
Chris Lattnerac161bf2009-01-02 07:01:27 +00004058 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4059 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004060
Chris Lattnerac161bf2009-01-02 07:01:27 +00004061 Inst = SelectInst::Create(Op0, Op1, Op2);
4062 return false;
4063}
4064
Chris Lattnerb55ab542009-01-05 08:18:44 +00004065/// ParseVA_Arg
4066/// ::= 'va_arg' TypeAndValue ',' Type
4067bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004068 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004069 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004070 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004071 if (ParseTypeAndValue(Op, PFS) ||
4072 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004073 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004074 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004075
Chris Lattnerb55ab542009-01-05 08:18:44 +00004076 if (!EltTy->isFirstClassType())
4077 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004078
4079 Inst = new VAArgInst(Op, EltTy);
4080 return false;
4081}
4082
4083/// ParseExtractElement
4084/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4085bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4086 LocTy Loc;
4087 Value *Op0, *Op1;
4088 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4089 ParseToken(lltok::comma, "expected ',' after extract value") ||
4090 ParseTypeAndValue(Op1, PFS))
4091 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004092
Chris Lattnerac161bf2009-01-02 07:01:27 +00004093 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4094 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004095
Eric Christopherc9742252009-07-25 02:28:41 +00004096 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004097 return false;
4098}
4099
4100/// ParseInsertElement
4101/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4102bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4103 LocTy Loc;
4104 Value *Op0, *Op1, *Op2;
4105 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4106 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4107 ParseTypeAndValue(Op1, PFS) ||
4108 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4109 ParseTypeAndValue(Op2, PFS))
4110 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004111
Chris Lattnerac161bf2009-01-02 07:01:27 +00004112 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004113 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004114
Chris Lattnerac161bf2009-01-02 07:01:27 +00004115 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4116 return false;
4117}
4118
4119/// ParseShuffleVector
4120/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4121bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4122 LocTy Loc;
4123 Value *Op0, *Op1, *Op2;
4124 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4125 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4126 ParseTypeAndValue(Op1, PFS) ||
4127 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4128 ParseTypeAndValue(Op2, PFS))
4129 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004130
Chris Lattnerac161bf2009-01-02 07:01:27 +00004131 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004132 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004133
Chris Lattnerac161bf2009-01-02 07:01:27 +00004134 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4135 return false;
4136}
4137
4138/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004139/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004140int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004141 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004142 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004143
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004144 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004145 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4146 ParseValue(Ty, Op0, PFS) ||
4147 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004148 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004149 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4150 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004151
Chris Lattnerf4f03422009-12-30 05:27:33 +00004152 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004153 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4154 while (1) {
4155 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004156
Chris Lattner3822f632009-01-02 08:05:26 +00004157 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004158 break;
4159
Chris Lattnerf4f03422009-12-30 05:27:33 +00004160 if (Lex.getKind() == lltok::MetadataVar) {
4161 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004162 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004163 }
Devang Patel8f842d32009-10-16 18:45:49 +00004164
Chris Lattner3822f632009-01-02 08:05:26 +00004165 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004166 ParseValue(Ty, Op0, PFS) ||
4167 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004168 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004169 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4170 return true;
4171 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004172
Chris Lattnerac161bf2009-01-02 07:01:27 +00004173 if (!Ty->isFirstClassType())
4174 return Error(TypeLoc, "phi node must have first class type");
4175
Jay Foad52131342011-03-30 11:28:46 +00004176 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004177 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4178 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4179 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004180 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004181}
4182
Bill Wendlingfae14752011-08-12 20:24:12 +00004183/// ParseLandingPad
4184/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4185/// Clause
4186/// ::= 'catch' TypeAndValue
4187/// ::= 'filter'
4188/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4189bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004190 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004191 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004192
4193 if (ParseType(Ty, TyLoc) ||
4194 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4195 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4196 return true;
4197
4198 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4199 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4200
4201 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4202 LandingPadInst::ClauseType CT;
4203 if (EatIfPresent(lltok::kw_catch))
4204 CT = LandingPadInst::Catch;
4205 else if (EatIfPresent(lltok::kw_filter))
4206 CT = LandingPadInst::Filter;
4207 else
4208 return TokError("expected 'catch' or 'filter' clause type");
4209
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004210 Value *V;
4211 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004212 if (ParseTypeAndValue(V, VLoc, PFS)) {
4213 delete LP;
4214 return true;
4215 }
4216
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004217 // A 'catch' type expects a non-array constant. A filter clause expects an
4218 // array constant.
4219 if (CT == LandingPadInst::Catch) {
4220 if (isa<ArrayType>(V->getType()))
4221 Error(VLoc, "'catch' clause has an invalid type");
4222 } else {
4223 if (!isa<ArrayType>(V->getType()))
4224 Error(VLoc, "'filter' clause has an invalid type");
4225 }
4226
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004227 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004228 }
4229
4230 Inst = LP;
4231 return false;
4232}
4233
Chris Lattnerac161bf2009-01-02 07:01:27 +00004234/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004235/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4236/// ParameterList OptionalAttrs
4237/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4238/// ParameterList OptionalAttrs
4239/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004240/// ParameterList OptionalAttrs
4241bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004242 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004243 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004244 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004245 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004246 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004247 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004248 LocTy RetTypeLoc;
4249 ValID CalleeID;
4250 SmallVector<ParamInfo, 16> ArgList;
4251 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004252
Reid Kleckner5772b772014-04-24 20:14:34 +00004253 if ((TCK != CallInst::TCK_None &&
4254 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004255 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004256 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004257 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004258 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004259 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4260 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004261 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004262 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004263 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004264
Chris Lattnerac161bf2009-01-02 07:01:27 +00004265 // If RetType is a non-function pointer type, then this is the short syntax
4266 // for the call, which means that RetType is just the return type. Infer the
4267 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004268 PointerType *PFTy = nullptr;
4269 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004270 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4271 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4272 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004273 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004274 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4275 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004276
Chris Lattnerac161bf2009-01-02 07:01:27 +00004277 if (!FunctionType::isValidReturnType(RetType))
4278 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004279
Owen Anderson4056ca92009-07-29 22:17:13 +00004280 Ty = FunctionType::get(RetType, ParamTypes, false);
4281 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004282 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004283
Chris Lattnerac161bf2009-01-02 07:01:27 +00004284 // Look up the callee.
4285 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004286 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004287
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004288 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004289 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004290 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004291 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4292 AttributeSet::ReturnIndex,
4293 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004294
Chris Lattnerac161bf2009-01-02 07:01:27 +00004295 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004296
Chris Lattnerac161bf2009-01-02 07:01:27 +00004297 // Loop through FunctionType's arguments and ensure they are specified
4298 // correctly. Also, gather any parameter attributes.
4299 FunctionType::param_iterator I = Ty->param_begin();
4300 FunctionType::param_iterator E = Ty->param_end();
4301 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004302 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004303 if (I != E) {
4304 ExpectedTy = *I++;
4305 } else if (!Ty->isVarArg()) {
4306 return Error(ArgList[i].Loc, "too many arguments specified");
4307 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004308
Chris Lattnerac161bf2009-01-02 07:01:27 +00004309 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4310 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004311 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004313 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4314 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004315 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4316 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004317 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004318
Chris Lattnerac161bf2009-01-02 07:01:27 +00004319 if (I != E)
4320 return Error(CallLoc, "not enough parameters specified for call");
4321
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004322 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004323 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4324 AttributeSet::FunctionIndex,
4325 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004326
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004327 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004328 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004329
Jay Foad5bd375a2011-07-15 08:37:34 +00004330 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004331 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004332 CI->setCallingConv(CC);
4333 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004334 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335 Inst = CI;
4336 return false;
4337}
4338
4339//===----------------------------------------------------------------------===//
4340// Memory Instructions.
4341//===----------------------------------------------------------------------===//
4342
4343/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004344/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004345int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004346 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004347 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004349 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004350
4351 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4352
Chris Lattner3822f632009-01-02 08:05:26 +00004353 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004354
Chris Lattnerb2f39502009-12-30 05:44:30 +00004355 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004356 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004357 if (Lex.getKind() == lltok::kw_align) {
4358 if (ParseOptionalAlignment(Alignment)) return true;
4359 } else if (Lex.getKind() == lltok::MetadataVar) {
4360 AteExtraComma = true;
4361 } else {
4362 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4363 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4364 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004365 }
4366 }
4367
Dan Gohman2140a742010-05-28 01:14:11 +00004368 if (Size && !Size->getType()->isIntegerTy())
4369 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004370
Reid Kleckner436c42e2014-01-17 23:58:17 +00004371 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4372 AI->setUsedWithInAlloca(IsInAlloca);
4373 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004374 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004375}
4376
4377/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004378/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004379/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004380/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004381int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004383 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004384 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004385 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004386 AtomicOrdering Ordering = NotAtomic;
4387 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004388
4389 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004390 isAtomic = true;
4391 Lex.Lex();
4392 }
4393
Chris Lattnerbc639292011-11-27 06:56:53 +00004394 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004395 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004396 isVolatile = true;
4397 Lex.Lex();
4398 }
4399
Chris Lattnerb2f39502009-12-30 05:44:30 +00004400 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004401 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004402 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4403 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004404
Duncan Sands19d0b472010-02-16 11:11:14 +00004405 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004406 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4407 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004408 if (isAtomic && !Alignment)
4409 return Error(Loc, "atomic load must have explicit non-zero alignment");
4410 if (Ordering == Release || Ordering == AcquireRelease)
4411 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004412
Eli Friedman59b66882011-08-09 23:02:53 +00004413 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004414 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004415}
4416
4417/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004418
4419/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4420/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004421/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004422int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004423 Value *Val, *Ptr; LocTy Loc, PtrLoc;
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 Lattnerac161bf2009-01-02 07:01:27 +00004441 if (ParseTypeAndValue(Val, Loc, PFS) ||
4442 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004443 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004444 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004445 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004446 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004447
Duncan Sands19d0b472010-02-16 11:11:14 +00004448 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449 return Error(PtrLoc, "store operand must be a pointer");
4450 if (!Val->getType()->isFirstClassType())
4451 return Error(Loc, "store operand must be a first class value");
4452 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4453 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004454 if (isAtomic && !Alignment)
4455 return Error(Loc, "atomic store must have explicit non-zero alignment");
4456 if (Ordering == Acquire || Ordering == AcquireRelease)
4457 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004458
Eli Friedman59b66882011-08-09 23:02:53 +00004459 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004460 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461}
4462
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004463/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004464/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4465/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004466int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004467 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4468 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004469 AtomicOrdering SuccessOrdering = NotAtomic;
4470 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004471 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004472 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004473 bool isWeak = false;
4474
4475 if (EatIfPresent(lltok::kw_weak))
4476 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004477
4478 if (EatIfPresent(lltok::kw_volatile))
4479 isVolatile = true;
4480
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004481 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4482 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4483 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4484 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4485 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004486 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4487 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004488 return true;
4489
Tim Northovere94a5182014-03-11 10:48:52 +00004490 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004491 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004492 if (SuccessOrdering < FailureOrdering)
4493 return TokError("cmpxchg must be at least as ordered on success as failure");
4494 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4495 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004496 if (!Ptr->getType()->isPointerTy())
4497 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4498 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4499 return Error(CmpLoc, "compare value and pointer type do not match");
4500 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4501 return Error(NewLoc, "new value and pointer type do not match");
4502 if (!New->getType()->isIntegerTy())
4503 return Error(NewLoc, "cmpxchg operand must be an integer");
4504 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4505 if (Size < 8 || (Size & (Size - 1)))
4506 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4507 " integer");
4508
Tim Northover420a2162014-06-13 14:24:07 +00004509 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4510 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004511 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004512 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004513 Inst = CXI;
4514 return AteExtraComma ? InstExtraComma : InstNormal;
4515}
4516
4517/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004518/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4519/// 'singlethread'? AtomicOrdering
4520int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004521 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4522 bool AteExtraComma = false;
4523 AtomicOrdering Ordering = NotAtomic;
4524 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004525 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004526 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004527
4528 if (EatIfPresent(lltok::kw_volatile))
4529 isVolatile = true;
4530
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004531 switch (Lex.getKind()) {
4532 default: return TokError("expected binary operation in atomicrmw");
4533 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4534 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4535 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4536 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4537 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4538 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4539 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4540 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4541 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4542 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4543 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4544 }
4545 Lex.Lex(); // Eat the operation.
4546
4547 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4548 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4549 ParseTypeAndValue(Val, ValLoc, PFS) ||
4550 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4551 return true;
4552
4553 if (Ordering == Unordered)
4554 return TokError("atomicrmw cannot be unordered");
4555 if (!Ptr->getType()->isPointerTy())
4556 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4557 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4558 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4559 if (!Val->getType()->isIntegerTy())
4560 return Error(ValLoc, "atomicrmw operand must be an integer");
4561 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4562 if (Size < 8 || (Size & (Size - 1)))
4563 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4564 " integer");
4565
4566 AtomicRMWInst *RMWI =
4567 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4568 RMWI->setVolatile(isVolatile);
4569 Inst = RMWI;
4570 return AteExtraComma ? InstExtraComma : InstNormal;
4571}
4572
Eli Friedmanfee02c62011-07-25 23:16:38 +00004573/// ParseFence
4574/// ::= 'fence' 'singlethread'? AtomicOrdering
4575int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4576 AtomicOrdering Ordering = NotAtomic;
4577 SynchronizationScope Scope = CrossThread;
4578 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4579 return true;
4580
4581 if (Ordering == Unordered)
4582 return TokError("fence cannot be unordered");
4583 if (Ordering == Monotonic)
4584 return TokError("fence cannot be monotonic");
4585
4586 Inst = new FenceInst(Context, Ordering, Scope);
4587 return InstNormal;
4588}
4589
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004591/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004592int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004593 Value *Ptr = nullptr;
4594 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004595 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004596
Dan Gohman16cbbe42009-07-29 15:58:36 +00004597 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004598
Chris Lattner3822f632009-01-02 08:05:26 +00004599 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004600
Eli Benderskyd9806682013-04-22 17:03:42 +00004601 Type *BaseType = Ptr->getType();
4602 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4603 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004604 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004605
Chris Lattnerac161bf2009-01-02 07:01:27 +00004606 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004607 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004608 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004609 if (Lex.getKind() == lltok::MetadataVar) {
4610 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004611 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004612 }
Chris Lattner3822f632009-01-02 08:05:26 +00004613 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004614 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004616 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4617 return Error(EltLoc, "getelementptr index type missmatch");
4618 if (Val->getType()->isVectorTy()) {
4619 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4620 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4621 if (ValNumEl != PtrNumEl)
4622 return Error(EltLoc,
4623 "getelementptr vector index has a wrong number of elements");
4624 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004625 Indices.push_back(Val);
4626 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004627
Eli Benderskyd9806682013-04-22 17:03:42 +00004628 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4629 return Error(Loc, "base element of getelementptr must be sized");
4630
4631 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004633 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004634 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004635 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004636 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637}
4638
4639/// ParseExtractValue
4640/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004641int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642 Value *Val; LocTy Loc;
4643 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004644 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004646 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 return true;
4648
Chris Lattner392be582010-02-12 20:49:41 +00004649 if (!Val->getType()->isAggregateType())
4650 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004651
Jay Foad57aa6362011-07-13 10:26:04 +00004652 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004653 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004654 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004655 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656}
4657
4658/// ParseInsertValue
4659/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004660int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 Value *Val0, *Val1; LocTy Loc0, Loc1;
4662 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004663 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4665 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4666 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004667 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004668 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004669
Chris Lattner392be582010-02-12 20:49:41 +00004670 if (!Val0->getType()->isAggregateType())
4671 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004672
Jay Foad57aa6362011-07-13 10:26:04 +00004673 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004675 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004676 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004677}
Nick Lewycky49f89192009-04-04 07:22:01 +00004678
4679//===----------------------------------------------------------------------===//
4680// Embedded metadata.
4681//===----------------------------------------------------------------------===//
4682
4683/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004684/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004685/// Element
4686/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004687bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts,
Victor Hernandezb8fd1522010-01-10 07:14:18 +00004688 PerFunctionState *PFS) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004689 assert(Lex.getKind() == lltok::lbrace);
4690 Lex.Lex();
4691
Dan Gohman1e0213a2010-07-13 19:33:27 +00004692 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004693 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004694 return false;
4695
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004696 bool IsLocal = false;
Nick Lewycky49f89192009-04-04 07:22:01 +00004697 do {
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004698 if (IsLocal)
4699 return TokError("unexpected operand after function-local metadata");
4700
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004701 // Null is a special case since it is typeless.
4702 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004703 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004704 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004705 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004706
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004707 Type *Ty = nullptr;
4708 if (ParseType(Ty))
4709 return true;
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004710
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004711 if (Ty->isMetadataTy()) {
4712 // No function-local metadata here.
4713 Metadata *MD = nullptr;
4714 if (ParseMetadata(MD, nullptr))
4715 return true;
4716 Elts.push_back(MD);
4717 continue;
4718 }
4719
4720 Value *V = nullptr;
4721 if (ParseValue(Ty, V, PFS))
4722 return true;
4723 assert(V && "Expected valid value");
4724 Elts.push_back(ValueAsMetadata::get(V));
4725
4726 if (isa<LocalAsMetadata>(Elts.back())) {
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00004727 assert(PFS && "Unexpected function-local metadata without PFS");
4728 if (Elts.size() > 1)
4729 return TokError("unexpected function-local metadata");
4730 IsLocal = true;
4731 }
Nick Lewycky49f89192009-04-04 07:22:01 +00004732 } while (EatIfPresent(lltok::comma));
4733
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004734 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004735}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004736
4737//===----------------------------------------------------------------------===//
4738// Use-list order directives.
4739//===----------------------------------------------------------------------===//
4740bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4741 SMLoc Loc) {
4742 if (V->use_empty())
4743 return Error(Loc, "value has no uses");
4744
4745 unsigned NumUses = 0;
4746 SmallDenseMap<const Use *, unsigned, 16> Order;
4747 for (const Use &U : V->uses()) {
4748 if (++NumUses > Indexes.size())
4749 break;
4750 Order[&U] = Indexes[NumUses - 1];
4751 }
4752 if (NumUses < 2)
4753 return Error(Loc, "value only has one use");
4754 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4755 return Error(Loc, "wrong number of indexes, expected " +
4756 Twine(std::distance(V->use_begin(), V->use_end())));
4757
4758 V->sortUseList([&](const Use &L, const Use &R) {
4759 return Order.lookup(&L) < Order.lookup(&R);
4760 });
4761 return false;
4762}
4763
4764/// ParseUseListOrderIndexes
4765/// ::= '{' uint32 (',' uint32)+ '}'
4766bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4767 SMLoc Loc = Lex.getLoc();
4768 if (ParseToken(lltok::lbrace, "expected '{' here"))
4769 return true;
4770 if (Lex.getKind() == lltok::rbrace)
4771 return Lex.Error("expected non-empty list of uselistorder indexes");
4772
4773 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4774 // indexes should be distinct numbers in the range [0, size-1], and should
4775 // not be in order.
4776 unsigned Offset = 0;
4777 unsigned Max = 0;
4778 bool IsOrdered = true;
4779 assert(Indexes.empty() && "Expected empty order vector");
4780 do {
4781 unsigned Index;
4782 if (ParseUInt32(Index))
4783 return true;
4784
4785 // Update consistency checks.
4786 Offset += Index - Indexes.size();
4787 Max = std::max(Max, Index);
4788 IsOrdered &= Index == Indexes.size();
4789
4790 Indexes.push_back(Index);
4791 } while (EatIfPresent(lltok::comma));
4792
4793 if (ParseToken(lltok::rbrace, "expected '}' here"))
4794 return true;
4795
4796 if (Indexes.size() < 2)
4797 return Error(Loc, "expected >= 2 uselistorder indexes");
4798 if (Offset != 0 || Max >= Indexes.size())
4799 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4800 if (IsOrdered)
4801 return Error(Loc, "expected uselistorder indexes to change the order");
4802
4803 return false;
4804}
4805
4806/// ParseUseListOrder
4807/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4808bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4809 SMLoc Loc = Lex.getLoc();
4810 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4811 return true;
4812
4813 Value *V;
4814 SmallVector<unsigned, 16> Indexes;
4815 if (ParseTypeAndValue(V, PFS) ||
4816 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4817 ParseUseListOrderIndexes(Indexes))
4818 return true;
4819
4820 return sortUseListOrder(V, Indexes, Loc);
4821}
4822
4823/// ParseUseListOrderBB
4824/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4825bool LLParser::ParseUseListOrderBB() {
4826 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4827 SMLoc Loc = Lex.getLoc();
4828 Lex.Lex();
4829
4830 ValID Fn, Label;
4831 SmallVector<unsigned, 16> Indexes;
4832 if (ParseValID(Fn) ||
4833 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4834 ParseValID(Label) ||
4835 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4836 ParseUseListOrderIndexes(Indexes))
4837 return true;
4838
4839 // Check the function.
4840 GlobalValue *GV;
4841 if (Fn.Kind == ValID::t_GlobalName)
4842 GV = M->getNamedValue(Fn.StrVal);
4843 else if (Fn.Kind == ValID::t_GlobalID)
4844 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4845 else
4846 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4847 if (!GV)
4848 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4849 auto *F = dyn_cast<Function>(GV);
4850 if (!F)
4851 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4852 if (F->isDeclaration())
4853 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4854
4855 // Check the basic block.
4856 if (Label.Kind == ValID::t_LocalID)
4857 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4858 if (Label.Kind != ValID::t_LocalName)
4859 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4860 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4861 if (!V)
4862 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4863 if (!isa<BasicBlock>(V))
4864 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4865
4866 return sortUseListOrder(V, Indexes, Loc);
4867}