blob: c5216a2ad6d7ee68b00792895d482951cf9ae6db [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"
David Blaikieadbda4b2015-08-03 20:08:41 +000016#include "llvm/ADT/STLExtras.h"
George Burgess IV278199f2016-04-12 01:05:35 +000017#include "llvm/ADT/StringExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000018#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000019#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/CallingConv.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000023#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000024#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/InlineAsm.h"
27#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000028#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
31#include "llvm/IR/Operator.h"
32#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000033#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000034#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000035#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000036#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000037#include "llvm/Support/raw_ostream.h"
38using namespace llvm;
39
Chris Lattner229907c2011-07-18 04:54:35 +000040static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000041 std::string Result;
42 raw_string_ostream Tmp(Result);
43 Tmp << *T;
44 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000045}
46
Chris Lattner3822f632009-01-02 08:05:26 +000047/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000048bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000049 // Prime the lexer.
50 Lex.Lex();
51
Mehdi Amini50af49f2016-04-02 03:46:17 +000052 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000053 return Error(
54 Lex.getLoc(),
55 "Can't read textual IR with a Context that discards named Values");
56
Chris Lattnerad6f3352009-01-04 20:44:11 +000057 return ParseTopLevelEntities() ||
58 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000059}
60
Alex Lorenz1de2acd2015-08-21 21:32:39 +000061bool LLParser::parseStandaloneConstantValue(Constant *&C,
62 const SlotMapping *Slots) {
63 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000064 Lex.Lex();
65
66 Type *Ty = nullptr;
67 if (ParseType(Ty) || parseConstantValue(Ty, C))
68 return true;
69 if (Lex.getKind() != lltok::Eof)
70 return Error(Lex.getLoc(), "expected end of string");
71 return false;
72}
73
Quentin Colombetdafed5d2016-03-08 00:37:07 +000074bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
75 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000076 restoreParsingState(Slots);
77 Lex.Lex();
78
Quentin Colombetdafed5d2016-03-08 00:37:07 +000079 Read = 0;
80 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000081 Ty = nullptr;
82 if (ParseType(Ty))
83 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000084 SMLoc End = Lex.getLoc();
85 Read = End.getPointer() - Start.getPointer();
86
Quentin Colombet81e72b42016-03-07 22:09:05 +000087 return false;
88}
89
Alex Lorenz1de2acd2015-08-21 21:32:39 +000090void LLParser::restoreParsingState(const SlotMapping *Slots) {
91 if (!Slots)
92 return;
93 NumberedVals = Slots->GlobalValues;
94 NumberedMetadata = Slots->MetadataNodes;
95 for (const auto &I : Slots->NamedTypes)
96 NamedTypes.insert(
97 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
98 for (const auto &I : Slots->Types)
99 NumberedTypes.insert(
100 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
101}
102
Chris Lattnerac161bf2009-01-02 07:01:27 +0000103/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
104/// module.
105bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000106 // Handle any function attribute group forward references.
107 for (std::map<Value*, std::vector<unsigned> >::iterator
108 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
109 I != E; ++I) {
110 Value *V = I->first;
111 std::vector<unsigned> &Vec = I->second;
112 AttrBuilder B;
113
114 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
115 VI != VE; ++VI)
116 B.merge(NumberedAttrBuilders[*VI]);
117
118 if (Function *Fn = dyn_cast<Function>(V)) {
119 AttributeSet AS = Fn->getAttributes();
120 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
121 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
122 AS.getFnAttributes());
123
124 FnAttrs.merge(B);
125
126 // If the alignment was parsed as an attribute, move to the alignment
127 // field.
128 if (FnAttrs.hasAlignmentAttr()) {
129 Fn->setAlignment(FnAttrs.getAlignment());
130 FnAttrs.removeAttribute(Attribute::Alignment);
131 }
132
133 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134 AttributeSet::get(Context,
135 AttributeSet::FunctionIndex,
136 FnAttrs));
137 Fn->setAttributes(AS);
138 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
139 AttributeSet AS = CI->getAttributes();
140 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
141 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
142 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000143 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000144 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
145 AttributeSet::get(Context,
146 AttributeSet::FunctionIndex,
147 FnAttrs));
148 CI->setAttributes(AS);
149 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
150 AttributeSet AS = II->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
152 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
153 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000155 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
156 AttributeSet::get(Context,
157 AttributeSet::FunctionIndex,
158 FnAttrs));
159 II->setAttributes(AS);
160 } else {
161 llvm_unreachable("invalid object with forward attribute group reference");
162 }
163 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000164
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000165 // If there are entries in ForwardRefBlockAddresses at this point, the
166 // function was never defined.
167 if (!ForwardRefBlockAddresses.empty())
168 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
169 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000170
David Majnemer19b51052015-02-11 07:43:56 +0000171 for (const auto &NT : NumberedTypes)
172 if (NT.second.second.isValid())
173 return Error(NT.second.second,
174 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000175
176 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
177 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
178 if (I->second.second.isValid())
179 return Error(I->second.second,
180 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000181
David Majnemerdad0a642014-06-27 18:19:56 +0000182 if (!ForwardRefComdats.empty())
183 return Error(ForwardRefComdats.begin()->second,
184 "use of undefined comdat '$" +
185 ForwardRefComdats.begin()->first + "'");
186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 if (!ForwardRefVals.empty())
188 return Error(ForwardRefVals.begin()->second.second,
189 "use of undefined value '@" + ForwardRefVals.begin()->first +
190 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000191
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 if (!ForwardRefValIDs.empty())
193 return Error(ForwardRefValIDs.begin()->second.second,
194 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000195 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000196
Devang Pateld2541152009-07-08 19:23:54 +0000197 if (!ForwardRefMDNodes.empty())
198 return Error(ForwardRefMDNodes.begin()->second.second,
199 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000200 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000201
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000203 for (auto &N : NumberedMetadata) {
204 if (N.second && !N.second->isResolved())
205 N.second->resolveCycles();
206 }
Devang Pateld2541152009-07-08 19:23:54 +0000207
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000208 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
209 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
210
Chris Lattnerac161bf2009-01-02 07:01:27 +0000211 // Look for intrinsic functions and CallInst that need to be upgraded
212 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000213 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000214
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000215 // Some types could be renamed during loading if several modules are
216 // loaded in the same LLVMContext (LTO scenario). In this case we should
217 // remangle intrinsics names as well.
218 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
219 Function *F = &*FI++;
220 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
221 F->replaceAllUsesWith(Remangled.getValue());
222 F->eraseFromParent();
223 }
224 }
225
Manman Ren8b4306c2013-12-02 21:29:56 +0000226 UpgradeDebugInfo(*M);
227
Manman Renb5d7ff42016-05-25 23:14:48 +0000228 UpgradeModuleFlags(*M);
229
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000230 if (!Slots)
231 return false;
232 // Initialize the slot mapping.
233 // Because by this point we've parsed and validated everything, we can "steal"
234 // the mapping from LLParser as it doesn't need it anymore.
235 Slots->GlobalValues = std::move(NumberedVals);
236 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000237 for (const auto &I : NamedTypes)
238 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
239 for (const auto &I : NumberedTypes)
240 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000241
Chris Lattnerac161bf2009-01-02 07:01:27 +0000242 return false;
243}
244
245//===----------------------------------------------------------------------===//
246// Top-Level Entities
247//===----------------------------------------------------------------------===//
248
249bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000250 while (1) {
251 switch (Lex.getKind()) {
252 default: return TokError("expected top-level entity");
253 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000254 case lltok::kw_declare: if (ParseDeclare()) return true; break;
255 case lltok::kw_define: if (ParseDefine()) return true; break;
256 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
257 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000258 case lltok::kw_source_filename:
259 if (ParseSourceFileName())
260 return true;
261 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000262 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000263 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000264 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000265 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000267 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000268 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000269 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000270 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000271 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
272 case lltok::kw_uselistorder_bb:
273 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000274 }
275 }
276}
277
278
279/// toplevelentity
280/// ::= 'module' 'asm' STRINGCONSTANT
281bool LLParser::ParseModuleAsm() {
282 assert(Lex.getKind() == lltok::kw_module);
283 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000284
285 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000286 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
287 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000288
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000289 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return false;
291}
292
293/// toplevelentity
294/// ::= 'target' 'triple' '=' STRINGCONSTANT
295/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
296bool LLParser::ParseTargetDefinition() {
297 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000298 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299 switch (Lex.Lex()) {
300 default: return TokError("unknown target property");
301 case lltok::kw_triple:
302 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000303 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
304 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000306 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000307 return false;
308 case lltok::kw_datalayout:
309 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000310 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
311 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000313 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 return false;
315 }
316}
317
Bill Wendling706d3d62012-11-28 08:41:48 +0000318/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000319/// ::= 'source_filename' '=' STRINGCONSTANT
320bool LLParser::ParseSourceFileName() {
321 assert(Lex.getKind() == lltok::kw_source_filename);
322 std::string Str;
323 Lex.Lex();
324 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
325 ParseStringConstant(Str))
326 return true;
327 M->setSourceFileName(Str);
328 return false;
329}
330
331/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000332/// ::= 'deplibs' '=' '[' ']'
333/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334/// FIXME: Remove in 4.0. Currently parse, but ignore.
335bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
337 Lex.Lex();
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
340 return true;
341
342 if (EatIfPresent(lltok::rsquare))
343 return false;
344
345 do {
346 std::string Str;
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
349
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
351}
352
Dan Gohman466876b2009-08-12 23:32:33 +0000353/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000354/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000355bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000356 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000358 Lex.Lex(); // eat LocalVarID;
359
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
362 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000363
Craig Topper2617dcc2014-04-15 06:32:26 +0000364 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000365 if (ParseStructDefinition(TypeLoc, "",
366 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000368 if (!isa<StructType>(Result)) {
369 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
370 if (Entry.first)
371 return Error(TypeLoc, "non-struct types may not be recursive");
372 Entry.first = Result;
373 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000375
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376 return false;
377}
378
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380/// toplevelentity
381/// ::= LocalVar '=' 'type' type
382bool LLParser::ParseNamedType() {
383 std::string Name = Lex.getStrVal();
384 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000385 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000386
Chris Lattner3822f632009-01-02 08:05:26 +0000387 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000388 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000389 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000390
Craig Topper2617dcc2014-04-15 06:32:26 +0000391 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000392 if (ParseStructDefinition(NameLoc, Name,
393 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000394
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000395 if (!isa<StructType>(Result)) {
396 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
397 if (Entry.first)
398 return Error(NameLoc, "non-struct types may not be recursive");
399 Entry.first = Result;
400 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000401 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404}
405
406
407/// toplevelentity
408/// ::= 'declare' FunctionHeader
409bool LLParser::ParseDeclare() {
410 assert(Lex.getKind() == lltok::kw_declare);
411 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000412
Peter Collingbourne21521892016-06-21 23:42:48 +0000413 std::vector<std::pair<unsigned, MDNode *>> MDs;
414 while (Lex.getKind() == lltok::MetadataVar) {
415 unsigned MDK;
416 MDNode *N;
417 if (ParseMetadataAttachment(MDK, N))
418 return true;
419 MDs.push_back({MDK, N});
420 }
421
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000423 if (ParseFunctionHeader(F, false))
424 return true;
425 for (auto &MD : MDs)
426 F->addMetadata(MD.first, *MD.second);
427 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000428}
429
430/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000431/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000432bool LLParser::ParseDefine() {
433 assert(Lex.getKind() == lltok::kw_define);
434 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000435
Chris Lattnerac161bf2009-01-02 07:01:27 +0000436 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000437 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000438 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000439 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440}
441
Chris Lattner3822f632009-01-02 08:05:26 +0000442/// ParseGlobalType
443/// ::= 'constant'
444/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445bool LLParser::ParseGlobalType(bool &IsConstant) {
446 if (Lex.getKind() == lltok::kw_constant)
447 IsConstant = true;
448 else if (Lex.getKind() == lltok::kw_global)
449 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000450 else {
451 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000453 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454 Lex.Lex();
455 return false;
456}
457
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000458bool LLParser::ParseOptionalUnnamedAddr(
459 GlobalVariable::UnnamedAddr &UnnamedAddr) {
460 if (EatIfPresent(lltok::kw_unnamed_addr))
461 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
462 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
463 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
464 else
465 UnnamedAddr = GlobalValue::UnnamedAddr::None;
466 return false;
467}
468
Dan Gohman466876b2009-08-12 23:32:33 +0000469/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000470/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000471/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000473/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000474/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000476bool LLParser::ParseUnnamedGlobal() {
477 unsigned VarID = NumberedVals.size();
478 std::string Name;
479 LocTy NameLoc = Lex.getLoc();
480
481 // Handle the GlobalID form.
482 if (Lex.getKind() == lltok::GlobalID) {
483 if (Lex.getUIntVal() != VarID)
484 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000485 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000486 Lex.Lex(); // eat GlobalID;
487
488 if (ParseToken(lltok::equal, "expected '=' after name"))
489 return true;
490 }
491
492 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000493 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000494 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000495 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000496 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000497 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000498 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000499
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000500 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000501 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000502 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000503
504 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
505 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000506}
507
Chris Lattnerac161bf2009-01-02 07:01:27 +0000508/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000509/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000510/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
511/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000512bool LLParser::ParseNamedGlobal() {
513 assert(Lex.getKind() == lltok::GlobalVar);
514 LocTy NameLoc = Lex.getLoc();
515 std::string Name = Lex.getStrVal();
516 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000517
Chris Lattnerac161bf2009-01-02 07:01:27 +0000518 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000519 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000520 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000521 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000522 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000523 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000524 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000527 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000528 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000529 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000530
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000531 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
532 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000533}
534
David Majnemerdad0a642014-06-27 18:19:56 +0000535bool LLParser::parseComdat() {
536 assert(Lex.getKind() == lltok::ComdatVar);
537 std::string Name = Lex.getStrVal();
538 LocTy NameLoc = Lex.getLoc();
539 Lex.Lex();
540
541 if (ParseToken(lltok::equal, "expected '=' here"))
542 return true;
543
544 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
545 return TokError("expected comdat type");
546
547 Comdat::SelectionKind SK;
548 switch (Lex.getKind()) {
549 default:
550 return TokError("unknown selection kind");
551 case lltok::kw_any:
552 SK = Comdat::Any;
553 break;
554 case lltok::kw_exactmatch:
555 SK = Comdat::ExactMatch;
556 break;
557 case lltok::kw_largest:
558 SK = Comdat::Largest;
559 break;
560 case lltok::kw_noduplicates:
561 SK = Comdat::NoDuplicates;
562 break;
563 case lltok::kw_samesize:
564 SK = Comdat::SameSize;
565 break;
566 }
567 Lex.Lex();
568
569 // See if the comdat was forward referenced, if so, use the comdat.
570 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
571 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
572 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
573 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
574
575 Comdat *C;
576 if (I != ComdatSymTab.end())
577 C = &I->second;
578 else
579 C = M->getOrInsertComdat(Name);
580 C->setSelectionKind(SK);
581
582 return false;
583}
584
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000585// MDString:
586// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000587bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000588 std::string Str;
589 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000590 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000591 return false;
592}
593
594// MDNode:
595// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000596bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000597 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000598 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000599 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000600 if (ParseUInt32(MID))
601 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000602
Chris Lattner8eff0152010-04-01 05:14:45 +0000603 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000604 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000605 Result = NumberedMetadata[MID];
606 return false;
607 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000608
Chris Lattner8eff0152010-04-01 05:14:45 +0000609 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000610 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000611 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000612
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000613 Result = FwdRef.first.get();
614 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000616}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000617
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000618/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000619/// !foo = !{ !1, !2 }
620bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000621 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000622 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000623 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000624
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000625 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000626 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000627 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000628 return true;
629
Dan Gohman2637cc12010-07-21 23:38:33 +0000630 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000631 if (Lex.getKind() != lltok::rbrace)
632 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000633 if (ParseToken(lltok::exclaim, "Expected '!' here"))
634 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000635
Craig Topper2617dcc2014-04-15 06:32:26 +0000636 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000637 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000638 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000639 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000640
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000641 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000642}
643
Devang Patel39e64d42009-07-01 19:21:12 +0000644/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000645/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000646bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000647 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000648 Lex.Lex();
649 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000650
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000651 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000652 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000653 ParseToken(lltok::equal, "expected '=' here"))
654 return true;
655
656 // Detect common error, from old metadata syntax.
657 if (Lex.getKind() == lltok::Type)
658 return TokError("unexpected type in metadata definition");
659
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000660 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000661 if (Lex.getKind() == lltok::MetadataVar) {
662 if (ParseSpecializedMDNode(Init, IsDistinct))
663 return true;
664 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
665 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000666 return true;
667
Chris Lattnerfc58af22009-12-30 04:51:58 +0000668 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000669 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000670 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000671 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000672 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000673
Chris Lattnerfc58af22009-12-30 04:51:58 +0000674 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
675 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000676 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000677 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000678 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000679 }
680
Devang Patel39e64d42009-07-01 19:21:12 +0000681 return false;
682}
683
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000684static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
685 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
686 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
687}
688
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000689/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000690/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
691/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000692/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000693///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000694/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000695/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696///
Eric Christopher536f0a92015-05-28 23:07:39 +0000697/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000698///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000699bool LLParser::parseIndirectSymbol(
700 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
701 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
702 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000703 bool IsAlias;
704 if (Lex.getKind() == lltok::kw_alias)
705 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000706 else if (Lex.getKind() == lltok::kw_ifunc)
707 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000708 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000709 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000710 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711
Rafael Espindola78527052013-10-06 15:10:43 +0000712 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
713
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000714 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000715 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000716
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000717 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000718 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000719 "symbol with local linkage must have default visibility");
720
David Blaikie2f408302015-09-11 03:22:04 +0000721 Type *Ty;
722 LocTy ExplicitTypeLoc = Lex.getLoc();
723 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000724 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000725 return true;
726
Rafael Espindola64c1e182014-06-03 02:41:57 +0000727 Constant *Aliasee;
728 LocTy AliaseeLoc = Lex.getLoc();
729 if (Lex.getKind() != lltok::kw_bitcast &&
730 Lex.getKind() != lltok::kw_getelementptr &&
731 Lex.getKind() != lltok::kw_addrspacecast &&
732 Lex.getKind() != lltok::kw_inttoptr) {
733 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000734 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000735 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000736 // The bitcast dest type is not present, it is implied by the dest type.
737 ValID ID;
738 if (ParseValID(ID))
739 return true;
740 if (ID.Kind != ValID::t_Constant)
741 return Error(AliaseeLoc, "invalid aliasee");
742 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000743 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000744
Rafael Espindola64c1e182014-06-03 02:41:57 +0000745 Type *AliaseeType = Aliasee->getType();
746 auto *PTy = dyn_cast<PointerType>(AliaseeType);
747 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000748 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000749 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000751 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000752 return Error(
753 ExplicitTypeLoc,
754 "explicit pointee type doesn't match operand's pointee type");
755
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000756 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
757 return Error(
758 ExplicitTypeLoc,
759 "explicit pointee type should be a function type");
760
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000761 GlobalValue *GVal = nullptr;
762
763 // See if the alias was forward referenced, if so, prepare to replace the
764 // forward reference.
765 if (!Name.empty()) {
766 GVal = M->getNamedValue(Name);
767 if (GVal) {
768 if (!ForwardRefVals.erase(Name))
769 return Error(NameLoc, "redefinition of global '@" + Name + "'");
770 }
771 } else {
772 auto I = ForwardRefValIDs.find(NumberedVals.size());
773 if (I != ForwardRefValIDs.end()) {
774 GVal = I->second.first;
775 ForwardRefValIDs.erase(I);
776 }
777 }
778
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000780 std::unique_ptr<GlobalIndirectSymbol> GA;
781 if (IsAlias)
782 GA.reset(GlobalAlias::create(Ty, AddrSpace,
783 (GlobalValue::LinkageTypes)Linkage, Name,
784 Aliasee, /*Parent*/ nullptr));
785 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000786 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
787 (GlobalValue::LinkageTypes)Linkage, Name,
788 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000789 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000790 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000791 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000792 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000793
Rafael Espindola54fc2982015-06-17 17:53:31 +0000794 if (Name.empty())
795 NumberedVals.push_back(GA.get());
796
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000797 if (GVal) {
798 // Verify that types agree.
799 if (GVal->getType() != GA->getType())
800 return Error(
801 ExplicitTypeLoc,
802 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 // If they agree, just RAUW the old value with the alias and remove the
805 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000806 GVal->replaceAllUsesWith(GA.get());
807 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Chris Lattnerac161bf2009-01-02 07:01:27 +0000810 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000811 if (IsAlias)
812 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
813 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000814 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000815 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Rafael Espindolaaa273822014-05-09 21:49:17 +0000817 // The module owns this now
818 GA.release();
819
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 return false;
821}
822
823/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000824/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000825/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000826/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000827/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000828/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000829/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000830///
Eric Christopher536f0a92015-05-28 23:07:39 +0000831/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000832/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833///
834bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
835 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000836 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000837 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000838 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000839 if (!isValidVisibilityForLinkage(Visibility, Linkage))
840 return Error(NameLoc,
841 "symbol with local linkage must have default visibility");
842
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000844 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000845 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000847
Craig Topper2617dcc2014-04-15 06:32:26 +0000848 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000849 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000850 ParseOptionalToken(lltok::kw_externally_initialized,
851 IsExternallyInitialized,
852 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000853 ParseGlobalType(IsConstant) ||
854 ParseType(Ty, TyLoc))
855 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000856
Chris Lattnerac161bf2009-01-02 07:01:27 +0000857 // If the linkage is specified and is external, then no initializer is
858 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000859 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000860 if (!HasLinkage ||
861 !GlobalValue::isValidDeclarationLinkage(
862 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000863 if (ParseGlobalValue(Ty, Init))
864 return true;
865 }
866
David Majnemer49b3d9b2015-02-16 08:41:08 +0000867 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000868 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
David Majnemer598bd052014-12-09 05:56:09 +0000870 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000871
872 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000873 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000874 GVal = M->getNamedValue(Name);
875 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000876 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000877 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000878 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000879 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000880 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000881 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000882 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000883 ForwardRefValIDs.erase(I);
884 }
885 }
886
David Majnemer598bd052014-12-09 05:56:09 +0000887 GlobalVariable *GV;
888 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000889 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
890 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000891 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000893 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 return Error(TyLoc,
895 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000896
David Majnemer598bd052014-12-09 05:56:09 +0000897 GV = cast<GlobalVariable>(GVal);
898
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 // Move the forward-reference to the correct spot in the module.
900 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
901 }
902
903 if (Name.empty())
904 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000905
Chris Lattnerac161bf2009-01-02 07:01:27 +0000906 // Set the parsed properties on the global.
907 if (Init)
908 GV->setInitializer(Init);
909 GV->setConstant(IsConstant);
910 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
911 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000912 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000913 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000914 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000915 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000916
Chris Lattnerac161bf2009-01-02 07:01:27 +0000917 // Parse attributes on the global.
918 while (Lex.getKind() == lltok::comma) {
919 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000920
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 if (Lex.getKind() == lltok::kw_section) {
922 Lex.Lex();
923 GV->setSection(Lex.getStrVal());
924 if (ParseToken(lltok::StringConstant, "expected global section string"))
925 return true;
926 } else if (Lex.getKind() == lltok::kw_align) {
927 unsigned Alignment;
928 if (ParseOptionalAlignment(Alignment)) return true;
929 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000930 } else if (Lex.getKind() == lltok::MetadataVar) {
931 if (ParseGlobalObjectMetadataAttachment(*GV))
932 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000933 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000934 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000935 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000936 return true;
937 if (C)
938 GV->setComdat(C);
939 else
940 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000941 }
942 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000943
Chris Lattnerac161bf2009-01-02 07:01:27 +0000944 return false;
945}
946
Bill Wendling63b88192013-02-06 06:52:58 +0000947/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000948/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000949bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000950 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000951 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000952 Lex.Lex();
953
David Majnemerb39e22b2014-12-09 18:33:57 +0000954 if (Lex.getKind() != lltok::AttrGrpID)
955 return TokError("expected attribute group id");
956
Bill Wendling63b88192013-02-06 06:52:58 +0000957 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000958 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000959 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000960 Lex.Lex();
961
962 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000963 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000964 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000965 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000966 ParseToken(lltok::rbrace, "expected end of attribute group"))
967 return true;
968
Bill Wendlingb32b0412013-02-08 06:32:06 +0000969 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000970 return Error(AttrGrpLoc, "attribute group has no attributes");
971
972 return false;
973}
974
Bill Wendling8b0321d2013-02-08 00:52:31 +0000975/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000976/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000977bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
978 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000979 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000980 bool HaveError = false;
981
982 B.clear();
983
Bill Wendling63b88192013-02-06 06:52:58 +0000984 while (true) {
985 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000986 if (Token == lltok::kw_builtin)
987 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000988 switch (Token) {
989 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000991 return Error(Lex.getLoc(), "unterminated attribute group");
992 case lltok::rbrace:
993 // Finished.
994 return false;
995
Bill Wendlingb32b0412013-02-08 06:32:06 +0000996 case lltok::AttrGrpID: {
997 // Allow a function to reference an attribute group:
998 //
999 // define void @foo() #1 { ... }
1000 if (inAttrGrp)
1001 HaveError |=
1002 Error(Lex.getLoc(),
1003 "cannot have an attribute group reference in an attribute group");
1004
1005 unsigned AttrGrpNum = Lex.getUIntVal();
1006 if (inAttrGrp) break;
1007
1008 // Save the reference to the attribute group. We'll fill it in later.
1009 FwdRefAttrGrps.push_back(AttrGrpNum);
1010 break;
1011 }
Bill Wendling63b88192013-02-06 06:52:58 +00001012 // Target-dependent attributes:
1013 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001014 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001015 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001016 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001017 }
1018
1019 // Target-independent attributes:
1020 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001021 // As a hack, we allow function alignment to be initially parsed as an
1022 // attribute on a function declaration/definition or added to an attribute
1023 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001024 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001025 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001026 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001027 if (ParseToken(lltok::equal, "expected '=' here") ||
1028 ParseUInt32(Alignment))
1029 return true;
1030 } else {
1031 if (ParseOptionalAlignment(Alignment))
1032 return true;
1033 }
Bill Wendling63b88192013-02-06 06:52:58 +00001034 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001035 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001036 }
1037 case lltok::kw_alignstack: {
1038 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001039 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001040 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001041 if (ParseToken(lltok::equal, "expected '=' here") ||
1042 ParseUInt32(Alignment))
1043 return true;
1044 } else {
1045 if (ParseOptionalStackAlignment(Alignment))
1046 return true;
1047 }
Bill Wendling63b88192013-02-06 06:52:58 +00001048 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001049 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001050 }
George Burgess IV278199f2016-04-12 01:05:35 +00001051 case lltok::kw_allocsize: {
1052 unsigned ElemSizeArg;
1053 Optional<unsigned> NumElemsArg;
1054 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1055 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1056 return true;
1057 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1058 continue;
1059 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001060 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1061 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1062 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1063 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1064 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001065 case lltok::kw_inaccessiblememonly:
1066 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1067 case lltok::kw_inaccessiblemem_or_argmemonly:
1068 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001069 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1070 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1071 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1072 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1073 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1074 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1075 case lltok::kw_noimplicitfloat:
1076 B.addAttribute(Attribute::NoImplicitFloat); break;
1077 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1078 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1079 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1080 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001081 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001082 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1083 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1084 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1085 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1086 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1087 case lltok::kw_returns_twice:
1088 B.addAttribute(Attribute::ReturnsTwice); break;
1089 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1090 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1091 case lltok::kw_sspstrong:
1092 B.addAttribute(Attribute::StackProtectStrong); break;
1093 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1094 case lltok::kw_sanitize_address:
1095 B.addAttribute(Attribute::SanitizeAddress); break;
1096 case lltok::kw_sanitize_thread:
1097 B.addAttribute(Attribute::SanitizeThread); break;
1098 case lltok::kw_sanitize_memory:
1099 B.addAttribute(Attribute::SanitizeMemory); break;
1100 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001101
1102 // Error handling.
1103 case lltok::kw_inreg:
1104 case lltok::kw_signext:
1105 case lltok::kw_zeroext:
1106 HaveError |=
1107 Error(Lex.getLoc(),
1108 "invalid use of attribute on a function");
1109 break;
1110 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001111 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001112 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001113 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001114 case lltok::kw_nest:
1115 case lltok::kw_noalias:
1116 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001117 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001118 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001119 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001120 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001121 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001122 HaveError |=
1123 Error(Lex.getLoc(),
1124 "invalid use of parameter-only attribute on a function");
1125 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001126 }
1127
1128 Lex.Lex();
1129 }
1130}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001131
1132//===----------------------------------------------------------------------===//
1133// GlobalValue Reference/Resolution Routines.
1134//===----------------------------------------------------------------------===//
1135
Karl Schimpf77729782015-09-03 18:06:44 +00001136static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1137 const std::string &Name) {
1138 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1139 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1140 else
1141 return new GlobalVariable(*M, PTy->getElementType(), false,
1142 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1143 nullptr, GlobalVariable::NotThreadLocal,
1144 PTy->getAddressSpace());
1145}
1146
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147/// GetGlobalVal - Get a value with the specified name or ID, creating a
1148/// forward reference record if needed. This can return null if the value
1149/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001150GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001151 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001152 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001153 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001154 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001155 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001157
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158 // Look this name up in the normal function symbol table.
1159 GlobalValue *Val =
1160 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001161
Chris Lattnerac161bf2009-01-02 07:01:27 +00001162 // If this is a forward reference for the value, see if we already created a
1163 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001164 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001165 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166 if (I != ForwardRefVals.end())
1167 Val = I->second.first;
1168 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001169
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 // If we have the value in the symbol table or fwd-ref table, return it.
1171 if (Val) {
1172 if (Val->getType() == Ty) return Val;
1173 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001174 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001175 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001176 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001177
Chris Lattnerac161bf2009-01-02 07:01:27 +00001178 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001179 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001180 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1181 return FwdVal;
1182}
1183
Chris Lattner229907c2011-07-18 04:54:35 +00001184GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1185 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001186 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001187 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001188 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001189 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001190
Craig Topper2617dcc2014-04-15 06:32:26 +00001191 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001192
Chris Lattnerac161bf2009-01-02 07:01:27 +00001193 // If this is a forward reference for the value, see if we already created a
1194 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001195 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001196 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 if (I != ForwardRefValIDs.end())
1198 Val = I->second.first;
1199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001200
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 // If we have the value in the symbol table or fwd-ref table, return it.
1202 if (Val) {
1203 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001204 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001205 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001206 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001208
Chris Lattnerac161bf2009-01-02 07:01:27 +00001209 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001210 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001211 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1212 return FwdVal;
1213}
1214
1215
1216//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001217// Comdat Reference/Resolution Routines.
1218//===----------------------------------------------------------------------===//
1219
1220Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1221 // Look this name up in the comdat symbol table.
1222 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1223 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1224 if (I != ComdatSymTab.end())
1225 return &I->second;
1226
1227 // Otherwise, create a new forward reference for this value and remember it.
1228 Comdat *C = M->getOrInsertComdat(Name);
1229 ForwardRefComdats[Name] = Loc;
1230 return C;
1231}
1232
1233
1234//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001235// Helper Routines.
1236//===----------------------------------------------------------------------===//
1237
1238/// ParseToken - If the current token has the specified kind, eat it and return
1239/// success. Otherwise, emit the specified error and return failure.
1240bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1241 if (Lex.getKind() != T)
1242 return TokError(ErrMsg);
1243 Lex.Lex();
1244 return false;
1245}
1246
Chris Lattner3822f632009-01-02 08:05:26 +00001247/// ParseStringConstant
1248/// ::= StringConstant
1249bool LLParser::ParseStringConstant(std::string &Result) {
1250 if (Lex.getKind() != lltok::StringConstant)
1251 return TokError("expected string constant");
1252 Result = Lex.getStrVal();
1253 Lex.Lex();
1254 return false;
1255}
1256
1257/// ParseUInt32
1258/// ::= uint32
1259bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001260 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1261 return TokError("expected integer");
1262 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1263 if (Val64 != unsigned(Val64))
1264 return TokError("expected 32-bit integer (too large)");
1265 Val = Val64;
1266 Lex.Lex();
1267 return false;
1268}
1269
Hal Finkelb0407ba2014-07-18 15:51:28 +00001270/// ParseUInt64
1271/// ::= uint64
1272bool LLParser::ParseUInt64(uint64_t &Val) {
1273 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1274 return TokError("expected integer");
1275 Val = Lex.getAPSIntVal().getLimitedValue();
1276 Lex.Lex();
1277 return false;
1278}
1279
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001280/// ParseTLSModel
1281/// := 'localdynamic'
1282/// := 'initialexec'
1283/// := 'localexec'
1284bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1285 switch (Lex.getKind()) {
1286 default:
1287 return TokError("expected localdynamic, initialexec or localexec");
1288 case lltok::kw_localdynamic:
1289 TLM = GlobalVariable::LocalDynamicTLSModel;
1290 break;
1291 case lltok::kw_initialexec:
1292 TLM = GlobalVariable::InitialExecTLSModel;
1293 break;
1294 case lltok::kw_localexec:
1295 TLM = GlobalVariable::LocalExecTLSModel;
1296 break;
1297 }
1298
1299 Lex.Lex();
1300 return false;
1301}
1302
1303/// ParseOptionalThreadLocal
1304/// := /*empty*/
1305/// := 'thread_local'
1306/// := 'thread_local' '(' tlsmodel ')'
1307bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1308 TLM = GlobalVariable::NotThreadLocal;
1309 if (!EatIfPresent(lltok::kw_thread_local))
1310 return false;
1311
1312 TLM = GlobalVariable::GeneralDynamicTLSModel;
1313 if (Lex.getKind() == lltok::lparen) {
1314 Lex.Lex();
1315 return ParseTLSModel(TLM) ||
1316 ParseToken(lltok::rparen, "expected ')' after thread local model");
1317 }
1318 return false;
1319}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001320
1321/// ParseOptionalAddrSpace
1322/// := /*empty*/
1323/// := 'addrspace' '(' uint32 ')'
1324bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1325 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001326 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001327 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001328 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001329 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001330 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001331}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001332
Artur Pilipenko17376c42015-08-03 14:31:49 +00001333/// ParseStringAttribute
1334/// := StringConstant
1335/// := StringConstant '=' StringConstant
1336bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1337 std::string Attr = Lex.getStrVal();
1338 Lex.Lex();
1339 std::string Val;
1340 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1341 return true;
1342 B.addAttribute(Attr, Val);
1343 return false;
1344}
1345
Bill Wendling34c2eb22012-12-04 23:40:58 +00001346/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1347bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1348 bool HaveError = false;
1349
1350 B.clear();
1351
1352 while (1) {
1353 lltok::Kind Token = Lex.getKind();
1354 switch (Token) {
1355 default: // End of attributes.
1356 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001357 case lltok::StringConstant: {
1358 if (ParseStringAttribute(B))
1359 return true;
1360 continue;
1361 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362 case lltok::kw_align: {
1363 unsigned Alignment;
1364 if (ParseOptionalAlignment(Alignment))
1365 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001366 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001367 continue;
1368 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001369 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001370 case lltok::kw_dereferenceable: {
1371 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001372 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001373 return true;
1374 B.addDereferenceableAttr(Bytes);
1375 continue;
1376 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001377 case lltok::kw_dereferenceable_or_null: {
1378 uint64_t Bytes;
1379 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1380 return true;
1381 B.addDereferenceableOrNullAttr(Bytes);
1382 continue;
1383 }
Reid Klecknera534a382013-12-19 02:14:12 +00001384 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001385 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1386 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1387 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1388 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001389 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001390 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1391 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001392 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001393 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1394 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001395 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001396 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001397 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001398
Stephen Lin7577ed52013-04-20 13:16:13 +00001399 case lltok::kw_alignstack:
1400 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001401 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001402 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001403 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001404 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001405 case lltok::kw_minsize:
1406 case lltok::kw_naked:
1407 case lltok::kw_nobuiltin:
1408 case lltok::kw_noduplicate:
1409 case lltok::kw_noimplicitfloat:
1410 case lltok::kw_noinline:
1411 case lltok::kw_nonlazybind:
1412 case lltok::kw_noredzone:
1413 case lltok::kw_noreturn:
1414 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001415 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001416 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001417 case lltok::kw_returns_twice:
1418 case lltok::kw_sanitize_address:
1419 case lltok::kw_sanitize_memory:
1420 case lltok::kw_sanitize_thread:
1421 case lltok::kw_ssp:
1422 case lltok::kw_sspreq:
1423 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001424 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001425 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001426 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1427 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001428 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001429
Bill Wendling34c2eb22012-12-04 23:40:58 +00001430 Lex.Lex();
1431 }
1432}
1433
1434/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1435bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1436 bool HaveError = false;
1437
1438 B.clear();
1439
1440 while (1) {
1441 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001442 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001443 default: // End of attributes.
1444 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001445 case lltok::StringConstant: {
1446 if (ParseStringAttribute(B))
1447 return true;
1448 continue;
1449 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001450 case lltok::kw_dereferenceable: {
1451 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001452 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001453 return true;
1454 B.addDereferenceableAttr(Bytes);
1455 continue;
1456 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001457 case lltok::kw_dereferenceable_or_null: {
1458 uint64_t Bytes;
1459 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1460 return true;
1461 B.addDereferenceableOrNullAttr(Bytes);
1462 continue;
1463 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001464 case lltok::kw_align: {
1465 unsigned Alignment;
1466 if (ParseOptionalAlignment(Alignment))
1467 return true;
1468 B.addAlignmentAttr(Alignment);
1469 continue;
1470 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001471 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1472 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001473 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001474 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1475 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001476
Bill Wendling34c2eb22012-12-04 23:40:58 +00001477 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001478 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001479 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001480 case lltok::kw_nest:
1481 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001482 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001483 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001484 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001485 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001486 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001487 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001488
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001489 case lltok::kw_alignstack:
1490 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001491 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001492 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001493 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001494 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001495 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001496 case lltok::kw_minsize:
1497 case lltok::kw_naked:
1498 case lltok::kw_nobuiltin:
1499 case lltok::kw_noduplicate:
1500 case lltok::kw_noimplicitfloat:
1501 case lltok::kw_noinline:
1502 case lltok::kw_nonlazybind:
1503 case lltok::kw_noredzone:
1504 case lltok::kw_noreturn:
1505 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001506 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001507 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001508 case lltok::kw_returns_twice:
1509 case lltok::kw_sanitize_address:
1510 case lltok::kw_sanitize_memory:
1511 case lltok::kw_sanitize_thread:
1512 case lltok::kw_ssp:
1513 case lltok::kw_sspreq:
1514 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001515 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001516 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001517 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001518 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001519
1520 case lltok::kw_readnone:
1521 case lltok::kw_readonly:
1522 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001523 }
1524
Chris Lattnerac161bf2009-01-02 07:01:27 +00001525 Lex.Lex();
1526 }
1527}
1528
Rafael Espindolac6269912016-05-10 17:16:45 +00001529static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1530 HasLinkage = true;
1531 switch (Kind) {
1532 default:
1533 HasLinkage = false;
1534 return GlobalValue::ExternalLinkage;
1535 case lltok::kw_private:
1536 return GlobalValue::PrivateLinkage;
1537 case lltok::kw_internal:
1538 return GlobalValue::InternalLinkage;
1539 case lltok::kw_weak:
1540 return GlobalValue::WeakAnyLinkage;
1541 case lltok::kw_weak_odr:
1542 return GlobalValue::WeakODRLinkage;
1543 case lltok::kw_linkonce:
1544 return GlobalValue::LinkOnceAnyLinkage;
1545 case lltok::kw_linkonce_odr:
1546 return GlobalValue::LinkOnceODRLinkage;
1547 case lltok::kw_available_externally:
1548 return GlobalValue::AvailableExternallyLinkage;
1549 case lltok::kw_appending:
1550 return GlobalValue::AppendingLinkage;
1551 case lltok::kw_common:
1552 return GlobalValue::CommonLinkage;
1553 case lltok::kw_extern_weak:
1554 return GlobalValue::ExternalWeakLinkage;
1555 case lltok::kw_external:
1556 return GlobalValue::ExternalLinkage;
1557 }
1558}
1559
Chris Lattnerac161bf2009-01-02 07:01:27 +00001560/// ParseOptionalLinkage
1561/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001562/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001563/// ::= 'internal'
1564/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001565/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001566/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001567/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001568/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001569/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001570/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001571/// ::= 'extern_weak'
1572/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001573bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1574 unsigned &Visibility,
1575 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001576 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1577 if (HasLinkage)
1578 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001579 ParseOptionalVisibility(Visibility);
1580 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581 return false;
1582}
1583
1584/// ParseOptionalVisibility
1585/// ::= /*empty*/
1586/// ::= 'default'
1587/// ::= 'hidden'
1588/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001589///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001590void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001591 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001592 default:
1593 Res = GlobalValue::DefaultVisibility;
1594 return;
1595 case lltok::kw_default:
1596 Res = GlobalValue::DefaultVisibility;
1597 break;
1598 case lltok::kw_hidden:
1599 Res = GlobalValue::HiddenVisibility;
1600 break;
1601 case lltok::kw_protected:
1602 Res = GlobalValue::ProtectedVisibility;
1603 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001604 }
1605 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606}
1607
Nico Rieck7157bb72014-01-14 15:22:47 +00001608/// ParseOptionalDLLStorageClass
1609/// ::= /*empty*/
1610/// ::= 'dllimport'
1611/// ::= 'dllexport'
1612///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001613void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001614 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001615 default:
1616 Res = GlobalValue::DefaultStorageClass;
1617 return;
1618 case lltok::kw_dllimport:
1619 Res = GlobalValue::DLLImportStorageClass;
1620 break;
1621 case lltok::kw_dllexport:
1622 Res = GlobalValue::DLLExportStorageClass;
1623 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001624 }
1625 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001626}
1627
Chris Lattnerac161bf2009-01-02 07:01:27 +00001628/// ParseOptionalCallingConv
1629/// ::= /*empty*/
1630/// ::= 'ccc'
1631/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001632/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001633/// ::= 'coldcc'
1634/// ::= 'x86_stdcallcc'
1635/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001636/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001637/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001638/// ::= 'arm_apcscc'
1639/// ::= 'arm_aapcscc'
1640/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001641/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001642/// ::= 'avr_intrcc'
1643/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001644/// ::= 'ptx_kernel'
1645/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001646/// ::= 'spir_func'
1647/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001648/// ::= 'x86_64_sysvcc'
1649/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001650/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001651/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001652/// ::= 'preserve_mostcc'
1653/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001654/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001655/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001656/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001657/// ::= 'hhvmcc'
1658/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001659/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001660/// ::= 'amdgpu_vs'
1661/// ::= 'amdgpu_tcs'
1662/// ::= 'amdgpu_tes'
1663/// ::= 'amdgpu_gs'
1664/// ::= 'amdgpu_ps'
1665/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001666/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001667/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001668///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001669bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001670 switch (Lex.getKind()) {
1671 default: CC = CallingConv::C; return false;
1672 case lltok::kw_ccc: CC = CallingConv::C; break;
1673 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1674 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1675 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1676 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001677 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001678 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001679 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1680 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1681 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001682 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001683 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1684 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001685 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1686 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001687 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1688 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001689 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001690 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1691 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001692 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001693 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001694 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1695 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001696 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001697 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001698 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001699 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1700 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001701 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001702 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1703 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1704 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1705 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001706 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001707 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001708 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001709 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001710 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001711 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001712
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713 Lex.Lex();
1714 return false;
1715}
1716
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001717/// ParseMetadataAttachment
1718/// ::= !dbg !42
1719bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1720 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1721
1722 std::string Name = Lex.getStrVal();
1723 Kind = M->getMDKindID(Name);
1724 Lex.Lex();
1725
1726 return ParseMDNode(MD);
1727}
1728
Chris Lattner5c427632009-12-30 05:31:19 +00001729/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001730/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001731bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001732 do {
1733 if (Lex.getKind() != lltok::MetadataVar)
1734 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001735
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001736 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001737 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001738 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001739 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001740
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001741 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001742 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001743 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001744
Chris Lattner596760d2009-12-29 21:25:40 +00001745 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001746 } while (EatIfPresent(lltok::comma));
1747 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001748}
1749
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001750/// ParseGlobalObjectMetadataAttachment
1751/// ::= !dbg !57
1752bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1753 unsigned MDK;
1754 MDNode *N;
1755 if (ParseMetadataAttachment(MDK, N))
1756 return true;
1757
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001758 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001759 return false;
1760}
1761
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001762/// ParseOptionalFunctionMetadata
1763/// ::= (!dbg !57)*
1764bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001765 while (Lex.getKind() == lltok::MetadataVar)
1766 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001767 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001768 return false;
1769}
1770
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771/// ParseOptionalAlignment
1772/// ::= /* empty */
1773/// ::= 'align' 4
1774bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1775 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001776 if (!EatIfPresent(lltok::kw_align))
1777 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001778 LocTy AlignLoc = Lex.getLoc();
1779 if (ParseUInt32(Alignment)) return true;
1780 if (!isPowerOf2_32(Alignment))
1781 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001782 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001783 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001784 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785}
1786
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001787/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001788/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001789/// ::= AttrKind '(' 4 ')'
1790///
1791/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1792bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1793 uint64_t &Bytes) {
1794 assert((AttrKind == lltok::kw_dereferenceable ||
1795 AttrKind == lltok::kw_dereferenceable_or_null) &&
1796 "contract!");
1797
Hal Finkelb0407ba2014-07-18 15:51:28 +00001798 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001799 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001800 return false;
1801 LocTy ParenLoc = Lex.getLoc();
1802 if (!EatIfPresent(lltok::lparen))
1803 return Error(ParenLoc, "expected '('");
1804 LocTy DerefLoc = Lex.getLoc();
1805 if (ParseUInt64(Bytes)) return true;
1806 ParenLoc = Lex.getLoc();
1807 if (!EatIfPresent(lltok::rparen))
1808 return Error(ParenLoc, "expected ')'");
1809 if (!Bytes)
1810 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1811 return false;
1812}
1813
Chris Lattnerb2f39502009-12-30 05:44:30 +00001814/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001815/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001816/// ::= ',' align 4
1817///
1818/// This returns with AteExtraComma set to true if it ate an excess comma at the
1819/// end.
1820bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1821 bool &AteExtraComma) {
1822 AteExtraComma = false;
1823 while (EatIfPresent(lltok::comma)) {
1824 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001825 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001826 AteExtraComma = true;
1827 return false;
1828 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001829
Chris Lattner95b0ff42010-04-23 00:50:50 +00001830 if (Lex.getKind() != lltok::kw_align)
1831 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001832
Chris Lattner95b0ff42010-04-23 00:50:50 +00001833 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001834 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001835
Devang Patelea8a4b92009-09-17 23:04:48 +00001836 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001837}
1838
George Burgess IV278199f2016-04-12 01:05:35 +00001839bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1840 Optional<unsigned> &HowManyArg) {
1841 Lex.Lex();
1842
1843 auto StartParen = Lex.getLoc();
1844 if (!EatIfPresent(lltok::lparen))
1845 return Error(StartParen, "expected '('");
1846
1847 if (ParseUInt32(BaseSizeArg))
1848 return true;
1849
1850 if (EatIfPresent(lltok::comma)) {
1851 auto HowManyAt = Lex.getLoc();
1852 unsigned HowMany;
1853 if (ParseUInt32(HowMany))
1854 return true;
1855 if (HowMany == BaseSizeArg)
1856 return Error(HowManyAt,
1857 "'allocsize' indices can't refer to the same parameter");
1858 HowManyArg = HowMany;
1859 } else
1860 HowManyArg = None;
1861
1862 auto EndParen = Lex.getLoc();
1863 if (!EatIfPresent(lltok::rparen))
1864 return Error(EndParen, "expected ')'");
1865 return false;
1866}
1867
Eli Friedmanfee02c62011-07-25 23:16:38 +00001868/// ParseScopeAndOrdering
1869/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1870/// else: ::=
1871///
1872/// This sets Scope and Ordering to the parsed values.
1873bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1874 AtomicOrdering &Ordering) {
1875 if (!isAtomic)
1876 return false;
1877
1878 Scope = CrossThread;
1879 if (EatIfPresent(lltok::kw_singlethread))
1880 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001881
1882 return ParseOrdering(Ordering);
1883}
1884
1885/// ParseOrdering
1886/// ::= AtomicOrdering
1887///
1888/// This sets Ordering to the parsed value.
1889bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001890 switch (Lex.getKind()) {
1891 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001892 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1893 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1894 // Not specified yet:
1895 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1896 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1897 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1898 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1899 case lltok::kw_seq_cst:
1900 Ordering = AtomicOrdering::SequentiallyConsistent;
1901 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001902 }
1903 Lex.Lex();
1904 return false;
1905}
1906
Charles Davisbe5557e2010-02-12 00:31:15 +00001907/// ParseOptionalStackAlignment
1908/// ::= /* empty */
1909/// ::= 'alignstack' '(' 4 ')'
1910bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1911 Alignment = 0;
1912 if (!EatIfPresent(lltok::kw_alignstack))
1913 return false;
1914 LocTy ParenLoc = Lex.getLoc();
1915 if (!EatIfPresent(lltok::lparen))
1916 return Error(ParenLoc, "expected '('");
1917 LocTy AlignLoc = Lex.getLoc();
1918 if (ParseUInt32(Alignment)) return true;
1919 ParenLoc = Lex.getLoc();
1920 if (!EatIfPresent(lltok::rparen))
1921 return Error(ParenLoc, "expected ')'");
1922 if (!isPowerOf2_32(Alignment))
1923 return Error(AlignLoc, "stack alignment is not a power of two");
1924 return false;
1925}
Devang Patelea8a4b92009-09-17 23:04:48 +00001926
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001927/// ParseIndexList - This parses the index list for an insert/extractvalue
1928/// instruction. This sets AteExtraComma in the case where we eat an extra
1929/// comma at the end of the line and find that it is followed by metadata.
1930/// Clients that don't allow metadata can call the version of this function that
1931/// only takes one argument.
1932///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933/// ParseIndexList
1934/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001935///
1936bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1937 bool &AteExtraComma) {
1938 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001939
Chris Lattnerac161bf2009-01-02 07:01:27 +00001940 if (Lex.getKind() != lltok::comma)
1941 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001942
Chris Lattner3822f632009-01-02 08:05:26 +00001943 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001944 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001945 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001946 AteExtraComma = true;
1947 return false;
1948 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001949 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001950 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001951 Indices.push_back(Idx);
1952 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954 return false;
1955}
1956
1957//===----------------------------------------------------------------------===//
1958// Type Parsing.
1959//===----------------------------------------------------------------------===//
1960
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001961/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001962bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 switch (Lex.getKind()) {
1965 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001966 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001968 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001969 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001970 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001972 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001973 // Type ::= StructType
1974 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001975 return true;
1976 break;
1977 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001979 Lex.Lex(); // eat the lsquare.
1980 if (ParseArrayVectorType(Result, false))
1981 return true;
1982 break;
1983 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001985 Lex.Lex();
1986 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001988 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 } else if (ParseArrayVectorType(Result, true))
1991 return true;
1992 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 case lltok::LocalVar: {
1994 // Type ::= %foo
1995 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001996
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001997 // If the type hasn't been defined yet, create a forward definition and
1998 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001999 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002000 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002002 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 Lex.Lex();
2005 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002006 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002007
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008 case lltok::LocalVarID: {
2009 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002011
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002012 // If the type hasn't been defined yet, create a forward definition and
2013 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002014 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002015 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002016 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002017 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002018 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002019 Lex.Lex();
2020 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002021 }
2022 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023
2024 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002025 while (1) {
2026 switch (Lex.getKind()) {
2027 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 default:
2029 if (!AllowVoid && Result->isVoidTy())
2030 return Error(TypeLoc, "void type only allowed for function results");
2031 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002032
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002033 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002034 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002036 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 if (Result->isVoidTy())
2038 return TokError("pointers to void are invalid - use i8* instead");
2039 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002040 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002041 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 Lex.Lex();
2043 break;
2044
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002050 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002052 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002053 unsigned AddrSpace;
2054 if (ParseOptionalAddrSpace(AddrSpace) ||
2055 ParseToken(lltok::star, "expected '*' in address space"))
2056 return true;
2057
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059 break;
2060 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002061
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2063 case lltok::lparen:
2064 if (ParseFunctionType(Result))
2065 return true;
2066 break;
2067 }
2068 }
2069}
2070
2071/// ParseParameterList
2072/// ::= '(' ')'
2073/// ::= '(' Arg (',' Arg)* ')'
2074/// Arg
2075/// ::= Type OptionalAttributes Value OptionalAttributes
2076bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002077 PerFunctionState &PFS, bool IsMustTailCall,
2078 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079 if (ParseToken(lltok::lparen, "expected '(' in call"))
2080 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002081
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002082 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083 while (Lex.getKind() != lltok::rparen) {
2084 // If this isn't the first argument, we need a comma.
2085 if (!ArgList.empty() &&
2086 ParseToken(lltok::comma, "expected ',' in argument list"))
2087 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002088
Reid Kleckner83498642014-08-26 00:33:28 +00002089 // Parse an ellipsis if this is a musttail call in a variadic function.
2090 if (Lex.getKind() == lltok::dotdotdot) {
2091 const char *Msg = "unexpected ellipsis in argument list for ";
2092 if (!IsMustTailCall)
2093 return TokError(Twine(Msg) + "non-musttail call");
2094 if (!InVarArgsFunc)
2095 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2096 Lex.Lex(); // Lex the '...', it is purely for readability.
2097 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2098 }
2099
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 // Parse the argument.
2101 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002102 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002103 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002105 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002107
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002108 if (ArgTy->isMetadataTy()) {
2109 if (ParseMetadataAsValue(V, PFS))
2110 return true;
2111 } else {
2112 // Otherwise, handle normal operands.
2113 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2114 return true;
2115 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002116 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2117 AttrIndex++,
2118 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 }
2120
Reid Kleckner83498642014-08-26 00:33:28 +00002121 if (IsMustTailCall && InVarArgsFunc)
2122 return TokError("expected '...' at end of argument list for musttail call "
2123 "in varargs function");
2124
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 Lex.Lex(); // Lex the ')'.
2126 return false;
2127}
2128
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002129/// ParseOptionalOperandBundles
2130/// ::= /*empty*/
2131/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2132///
2133/// OperandBundle
2134/// ::= bundle-tag '(' ')'
2135/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2136///
2137/// bundle-tag ::= String Constant
2138bool LLParser::ParseOptionalOperandBundles(
2139 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2140 LocTy BeginLoc = Lex.getLoc();
2141 if (!EatIfPresent(lltok::lsquare))
2142 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002143
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002144 while (Lex.getKind() != lltok::rsquare) {
2145 // If this isn't the first operand bundle, we need a comma.
2146 if (!BundleList.empty() &&
2147 ParseToken(lltok::comma, "expected ',' in input list"))
2148 return true;
2149
2150 std::string Tag;
2151 if (ParseStringConstant(Tag))
2152 return true;
2153
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002154 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2155 return true;
2156
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002157 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002158 while (Lex.getKind() != lltok::rparen) {
2159 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002160 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002161 ParseToken(lltok::comma, "expected ',' in input list"))
2162 return true;
2163
2164 Type *Ty = nullptr;
2165 Value *Input = nullptr;
2166 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2167 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002168 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002169 }
2170
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002171 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2172
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002173 Lex.Lex(); // Lex the ')'.
2174 }
2175
2176 if (BundleList.empty())
2177 return Error(BeginLoc, "operand bundle set must not be empty");
2178
2179 Lex.Lex(); // Lex the ']'.
2180 return false;
2181}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182
Chris Lattner2ed06b42009-01-05 18:34:07 +00002183/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002184/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185/// ::= '(' ArgTypeListI ')'
2186/// ArgTypeListI
2187/// ::= /*empty*/
2188/// ::= '...'
2189/// ::= ArgTypeList ',' '...'
2190/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002191///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002192bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2193 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 isVarArg = false;
2195 assert(Lex.getKind() == lltok::lparen);
2196 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002197
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 if (Lex.getKind() == lltok::rparen) {
2199 // empty
2200 } else if (Lex.getKind() == lltok::dotdotdot) {
2201 isVarArg = true;
2202 Lex.Lex();
2203 } else {
2204 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002205 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002206 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002209 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002210 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Chris Lattnerfdd87902009-10-05 05:54:46 +00002212 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002213 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002214
Chris Lattnerdef19492011-06-17 06:36:20 +00002215 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 Name = Lex.getStrVal();
2217 Lex.Lex();
2218 }
Chris Lattner3822f632009-01-02 08:05:26 +00002219
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002220 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002221 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002222
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002223 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002224 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2225 AttrIndex++, Attrs),
2226 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattner3822f632009-01-02 08:05:26 +00002228 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002230 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 break;
2233 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 // Otherwise must be an argument type.
2236 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002237 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002238
Chris Lattnerfdd87902009-10-05 05:54:46 +00002239 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002240 return Error(TypeLoc, "argument can not have void type");
2241
Chris Lattnerdef19492011-06-17 06:36:20 +00002242 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 Name = Lex.getStrVal();
2244 Lex.Lex();
2245 } else {
2246 Name = "";
2247 }
Chris Lattner3822f632009-01-02 08:05:26 +00002248
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002249 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002250 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002251
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002252 ArgList.emplace_back(
2253 TypeLoc, ArgTy,
2254 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2255 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256 }
2257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002258
Chris Lattner3822f632009-01-02 08:05:26 +00002259 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262/// ParseFunctionType
2263/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 assert(Lex.getKind() == lltok::lparen);
2266
Chris Lattnerce473c72009-01-05 08:04:33 +00002267 if (!FunctionType::isValidReturnType(Result))
2268 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002269
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002270 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002272 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002274
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 // Reject names on the arguments lists.
2276 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2277 if (!ArgList[i].Name.empty())
2278 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002279 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002280 return Error(ArgList[i].Loc,
2281 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002283
Jay Foadb804a2b2011-07-12 14:06:48 +00002284 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002286 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002287
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002288 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002289 return false;
2290}
2291
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002292/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2293/// other structs.
2294bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2295 SmallVector<Type*, 8> Elts;
2296 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002297
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002298 Result = StructType::get(Context, Elts, Packed);
2299 return false;
2300}
2301
2302/// ParseStructDefinition - Parse a struct in a 'type' definition.
2303bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2304 std::pair<Type*, LocTy> &Entry,
2305 Type *&ResultTy) {
2306 // If the type was already defined, diagnose the redefinition.
2307 if (Entry.first && !Entry.second.isValid())
2308 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002309
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002310 // If we have opaque, just return without filling in the definition for the
2311 // struct. This counts as a definition as far as the .ll file goes.
2312 if (EatIfPresent(lltok::kw_opaque)) {
2313 // This type is being defined, so clear the location to indicate this.
2314 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002315
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002316 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002317 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002318 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002319 ResultTy = Entry.first;
2320 return false;
2321 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002323 // If the type starts with '<', then it is either a packed struct or a vector.
2324 bool isPacked = EatIfPresent(lltok::less);
2325
2326 // If we don't have a struct, then we have a random type alias, which we
2327 // accept for compatibility with old files. These types are not allowed to be
2328 // forward referenced and not allowed to be recursive.
2329 if (Lex.getKind() != lltok::lbrace) {
2330 if (Entry.first)
2331 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002332
Craig Topper2617dcc2014-04-15 06:32:26 +00002333 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002334 if (isPacked)
2335 return ParseArrayVectorType(ResultTy, true);
2336 return ParseType(ResultTy);
2337 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002339 // This type is being defined, so clear the location to indicate this.
2340 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002341
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002342 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002343 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002344 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002345
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002346 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002348 SmallVector<Type*, 8> Body;
2349 if (ParseStructBody(Body) ||
2350 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2351 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002353 STy->setBody(Body, isPacked);
2354 ResultTy = STy;
2355 return false;
2356}
2357
2358
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002360/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002362/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002363/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002364/// ::= '<' '{' Type (',' Type)* '}' '>'
2365bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 assert(Lex.getKind() == lltok::lbrace);
2367 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002368
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002369 // Handle the empty struct.
2370 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372
Chris Lattnerf880ca22009-03-09 04:49:14 +00002373 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002374 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002375 if (ParseType(Ty)) return true;
2376 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002378 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002379 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002380
Chris Lattner3822f632009-01-02 08:05:26 +00002381 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002382 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002383 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002386 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002387
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002388 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002390
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002391 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392}
2393
2394/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2395/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397/// ::= '[' APSINTVAL 'x' Types ']'
2398/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002399bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2401 Lex.getAPSIntVal().getBitWidth() > 64)
2402 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002403
Chris Lattnerac161bf2009-01-02 07:01:27 +00002404 LocTy SizeLoc = Lex.getLoc();
2405 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002406 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002407
Chris Lattner3822f632009-01-02 08:05:26 +00002408 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2409 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410
2411 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002412 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002413 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002414
Chris Lattner3822f632009-01-02 08:05:26 +00002415 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2416 "expected end of sequential type"))
2417 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002420 if (Size == 0)
2421 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002422 if ((unsigned)Size != Size)
2423 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002424 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002425 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002426 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002428 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 }
2432 return false;
2433}
2434
2435//===----------------------------------------------------------------------===//
2436// Function Semantic Analysis.
2437//===----------------------------------------------------------------------===//
2438
Chris Lattner3432c622009-10-28 03:39:23 +00002439LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2440 int functionNumber)
2441 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002442
2443 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002444 for (Argument &A : F.args())
2445 if (!A.hasName())
2446 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447}
2448
2449LLParser::PerFunctionState::~PerFunctionState() {
2450 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002451
David Blaikie9ebdc692015-09-21 21:07:50 +00002452 for (const auto &P : ForwardRefVals) {
2453 if (isa<BasicBlock>(P.second.first))
2454 continue;
2455 P.second.first->replaceAllUsesWith(
2456 UndefValue::get(P.second.first->getType()));
2457 delete P.second.first;
2458 }
2459
2460 for (const auto &P : ForwardRefValIDs) {
2461 if (isa<BasicBlock>(P.second.first))
2462 continue;
2463 P.second.first->replaceAllUsesWith(
2464 UndefValue::get(P.second.first->getType()));
2465 delete P.second.first;
2466 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467}
2468
Chris Lattner3432c622009-10-28 03:39:23 +00002469bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002470 if (!ForwardRefVals.empty())
2471 return P.Error(ForwardRefVals.begin()->second.second,
2472 "use of undefined value '%" + ForwardRefVals.begin()->first +
2473 "'");
2474 if (!ForwardRefValIDs.empty())
2475 return P.Error(ForwardRefValIDs.begin()->second.second,
2476 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002477 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 return false;
2479}
2480
2481
2482/// GetVal - Get a value with the specified name or ID, creating a
2483/// forward reference record if needed. This can return null if the value
2484/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002485Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002486 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 // Look this name up in the normal function symbol table.
2488 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002489
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 // If this is a forward reference for the value, see if we already created a
2491 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002492 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002493 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494 if (I != ForwardRefVals.end())
2495 Val = I->second.first;
2496 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002497
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498 // If we have the value in the symbol table or fwd-ref table, return it.
2499 if (Val) {
2500 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002501 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502 P.Error(Loc, "'%" + Name + "' is not a basic block");
2503 else
2504 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002505 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002506 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002508
Chris Lattnerac161bf2009-01-02 07:01:27 +00002509 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002510 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002512 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 // Otherwise, create a new forward reference for this value and remember it.
2516 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002517 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002518 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002519 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002520 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002521 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2524 return FwdVal;
2525}
2526
David Majnemer8a1c45d2015-12-12 05:38:55 +00002527Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002529 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 // If this is a forward reference for the value, see if we already created a
2532 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002533 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002534 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002535 if (I != ForwardRefValIDs.end())
2536 Val = I->second.first;
2537 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 // If we have the value in the symbol table or fwd-ref table, return it.
2540 if (Val) {
2541 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002542 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002543 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002545 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002546 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002547 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002549
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002550 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002551 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002552 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002554
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 // Otherwise, create a new forward reference for this value and remember it.
2556 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002557 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002558 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002559 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002560 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002561 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002562
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2564 return FwdVal;
2565}
2566
2567/// SetInstName - After an instruction is parsed and inserted into its
2568/// basic block, this installs its name.
2569bool LLParser::PerFunctionState::SetInstName(int NameID,
2570 const std::string &NameStr,
2571 LocTy NameLoc, Instruction *Inst) {
2572 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002573 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 if (NameID != -1 || !NameStr.empty())
2575 return P.Error(NameLoc, "instructions returning void cannot have a name");
2576 return false;
2577 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002578
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 // If this was a numbered instruction, verify that the instruction is the
2580 // expected value and resolve any forward references.
2581 if (NameStr.empty()) {
2582 // If neither a name nor an ID was specified, just use the next ID.
2583 if (NameID == -1)
2584 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002585
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586 if (unsigned(NameID) != NumberedVals.size())
2587 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002588 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002589
David Blaikie9ebdc692015-09-21 21:07:50 +00002590 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002592 Value *Sentinel = FI->second.first;
2593 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002594 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002595 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002596
2597 Sentinel->replaceAllUsesWith(Inst);
2598 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 ForwardRefValIDs.erase(FI);
2600 }
2601
2602 NumberedVals.push_back(Inst);
2603 return false;
2604 }
2605
2606 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002607 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002609 Value *Sentinel = FI->second.first;
2610 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002611 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002612 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002613
2614 Sentinel->replaceAllUsesWith(Inst);
2615 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002616 ForwardRefVals.erase(FI);
2617 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 // Set the name on the instruction.
2620 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002621
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002622 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002623 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 NameStr + "'");
2625 return false;
2626}
2627
2628/// GetBB - Get a basic block with the specified name or ID, creating a
2629/// forward reference record if needed.
2630BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2631 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002632 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2633 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002634}
2635
2636BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002637 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2638 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639}
2640
2641/// DefineBB - Define the specified basic block, which is either named or
2642/// unnamed. If there is an error, this returns null otherwise it returns
2643/// the block being defined.
2644BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2645 LocTy Loc) {
2646 BasicBlock *BB;
2647 if (Name.empty())
2648 BB = GetBB(NumberedVals.size(), Loc);
2649 else
2650 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002651 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 // Move the block to the end of the function. Forward ref'd blocks are
2654 // inserted wherever they happen to be referenced.
2655 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 // Remove the block from forward ref sets.
2658 if (Name.empty()) {
2659 ForwardRefValIDs.erase(NumberedVals.size());
2660 NumberedVals.push_back(BB);
2661 } else {
2662 // BB forward references are already in the function symbol table.
2663 ForwardRefVals.erase(Name);
2664 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002665
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 return BB;
2667}
2668
2669//===----------------------------------------------------------------------===//
2670// Constants.
2671//===----------------------------------------------------------------------===//
2672
2673/// ParseValID - Parse an abstract value that doesn't necessarily have a
2674/// type implied. For example, if we parse "4" we don't know what integer type
2675/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002676/// sanity. PFS is used to convert function-local operands of metadata (since
2677/// metadata operands are not just parsed here but also converted to values).
2678/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002679bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 ID.Loc = Lex.getLoc();
2681 switch (Lex.getKind()) {
2682 default: return TokError("expected value token");
2683 case lltok::GlobalID: // @42
2684 ID.UIntVal = Lex.getUIntVal();
2685 ID.Kind = ValID::t_GlobalID;
2686 break;
2687 case lltok::GlobalVar: // @foo
2688 ID.StrVal = Lex.getStrVal();
2689 ID.Kind = ValID::t_GlobalName;
2690 break;
2691 case lltok::LocalVarID: // %42
2692 ID.UIntVal = Lex.getUIntVal();
2693 ID.Kind = ValID::t_LocalID;
2694 break;
2695 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002696 ID.StrVal = Lex.getStrVal();
2697 ID.Kind = ValID::t_LocalName;
2698 break;
2699 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002700 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701 ID.Kind = ValID::t_APSInt;
2702 break;
2703 case lltok::APFloat:
2704 ID.APFloatVal = Lex.getAPFloatVal();
2705 ID.Kind = ValID::t_APFloat;
2706 break;
2707 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002708 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 ID.Kind = ValID::t_Constant;
2710 break;
2711 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002712 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 ID.Kind = ValID::t_Constant;
2714 break;
2715 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2716 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2717 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002718 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002719
Chris Lattnerac161bf2009-01-02 07:01:27 +00002720 case lltok::lbrace: {
2721 // ValID ::= '{' ConstVector '}'
2722 Lex.Lex();
2723 SmallVector<Constant*, 16> Elts;
2724 if (ParseGlobalValueVector(Elts) ||
2725 ParseToken(lltok::rbrace, "expected end of struct constant"))
2726 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002727
David Blaikieadbda4b2015-08-03 20:08:41 +00002728 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002729 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002730 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2731 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002732 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733 return false;
2734 }
2735 case lltok::less: {
2736 // ValID ::= '<' ConstVector '>' --> Vector.
2737 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2738 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002739 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002740
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 SmallVector<Constant*, 16> Elts;
2742 LocTy FirstEltLoc = Lex.getLoc();
2743 if (ParseGlobalValueVector(Elts) ||
2744 (isPackedStruct &&
2745 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2746 ParseToken(lltok::greater, "expected end of constant"))
2747 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002748
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002750 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2751 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2752 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002753 ID.UIntVal = Elts.size();
2754 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 return false;
2756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002757
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 if (Elts.empty())
2759 return Error(ID.Loc, "constant vector must not be empty");
2760
Duncan Sands9dff9be2010-02-15 16:12:20 +00002761 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002762 !Elts[0]->getType()->isFloatingPointTy() &&
2763 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002764 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002765 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002766
Chris Lattnerac161bf2009-01-02 07:01:27 +00002767 // Verify that all the vector elements have the same type.
2768 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2769 if (Elts[i]->getType() != Elts[0]->getType())
2770 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002771 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002772 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002773
Chris Lattner69229312011-02-15 00:14:00 +00002774 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 ID.Kind = ValID::t_Constant;
2776 return false;
2777 }
2778 case lltok::lsquare: { // Array Constant
2779 Lex.Lex();
2780 SmallVector<Constant*, 16> Elts;
2781 LocTy FirstEltLoc = Lex.getLoc();
2782 if (ParseGlobalValueVector(Elts) ||
2783 ParseToken(lltok::rsquare, "expected end of array constant"))
2784 return true;
2785
2786 // Handle empty element.
2787 if (Elts.empty()) {
2788 // Use undef instead of an array because it's inconvenient to determine
2789 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002790 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 return false;
2792 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002793
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002795 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002796 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797
Owen Anderson4056ca92009-07-29 22:17:13 +00002798 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002799
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002801 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 if (Elts[i]->getType() != Elts[0]->getType())
2803 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002804 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002805 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807
Jay Foad83be3612011-06-22 09:24:39 +00002808 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 ID.Kind = ValID::t_Constant;
2810 return false;
2811 }
2812 case lltok::kw_c: // c "foo"
2813 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002814 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2815 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002816 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2817 ID.Kind = ValID::t_Constant;
2818 return false;
2819
2820 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002821 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2822 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002823 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 Lex.Lex();
2825 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002826 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002827 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002828 ParseStringConstant(ID.StrVal) ||
2829 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002830 ParseToken(lltok::StringConstant, "expected constraint string"))
2831 return true;
2832 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002833 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002834 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 ID.Kind = ValID::t_InlineAsm;
2836 return false;
2837 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002838
Chris Lattner3432c622009-10-28 03:39:23 +00002839 case lltok::kw_blockaddress: {
2840 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2841 Lex.Lex();
2842
2843 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002844
Chris Lattner3432c622009-10-28 03:39:23 +00002845 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2846 ParseValID(Fn) ||
2847 ParseToken(lltok::comma, "expected comma in block address expression")||
2848 ParseValID(Label) ||
2849 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2850 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002851
Chris Lattner3432c622009-10-28 03:39:23 +00002852 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2853 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002854 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002855 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002856
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002857 // Try to find the function (but skip it if it's forward-referenced).
2858 GlobalValue *GV = nullptr;
2859 if (Fn.Kind == ValID::t_GlobalID) {
2860 if (Fn.UIntVal < NumberedVals.size())
2861 GV = NumberedVals[Fn.UIntVal];
2862 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2863 GV = M->getNamedValue(Fn.StrVal);
2864 }
2865 Function *F = nullptr;
2866 if (GV) {
2867 // Confirm that it's actually a function with a definition.
2868 if (!isa<Function>(GV))
2869 return Error(Fn.Loc, "expected function name in blockaddress");
2870 F = cast<Function>(GV);
2871 if (F->isDeclaration())
2872 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2873 }
2874
2875 if (!F) {
2876 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002877 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002878 ForwardRefBlockAddresses.insert(std::make_pair(
2879 std::move(Fn),
2880 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002881 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2882 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002883 if (!FwdRef)
2884 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2885 GlobalValue::InternalLinkage, nullptr, "");
2886 ID.ConstantVal = FwdRef;
2887 ID.Kind = ValID::t_Constant;
2888 return false;
2889 }
2890
2891 // We found the function; now find the basic block. Don't use PFS, since we
2892 // might be inside a constant expression.
2893 BasicBlock *BB;
2894 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2895 if (Label.Kind == ValID::t_LocalID)
2896 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2897 else
2898 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2899 if (!BB)
2900 return Error(Label.Loc, "referenced value is not a basic block");
2901 } else {
2902 if (Label.Kind == ValID::t_LocalID)
2903 return Error(Label.Loc, "cannot take address of numeric label after "
2904 "the function is defined");
2905 BB = dyn_cast_or_null<BasicBlock>(
2906 F->getValueSymbolTable().lookup(Label.StrVal));
2907 if (!BB)
2908 return Error(Label.Loc, "referenced value is not a basic block");
2909 }
2910
2911 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002912 ID.Kind = ValID::t_Constant;
2913 return false;
2914 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002915
Chris Lattnerac161bf2009-01-02 07:01:27 +00002916 case lltok::kw_trunc:
2917 case lltok::kw_zext:
2918 case lltok::kw_sext:
2919 case lltok::kw_fptrunc:
2920 case lltok::kw_fpext:
2921 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002922 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002923 case lltok::kw_uitofp:
2924 case lltok::kw_sitofp:
2925 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002926 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002928 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002930 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 Constant *SrcVal;
2932 Lex.Lex();
2933 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2934 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002935 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002936 ParseType(DestTy) ||
2937 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2938 return true;
2939 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2940 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002941 getTypeString(SrcVal->getType()) + "' to '" +
2942 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002943 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002944 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002945 ID.Kind = ValID::t_Constant;
2946 return false;
2947 }
2948 case lltok::kw_extractvalue: {
2949 Lex.Lex();
2950 Constant *Val;
2951 SmallVector<unsigned, 4> Indices;
2952 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2953 ParseGlobalTypeAndValue(Val) ||
2954 ParseIndexList(Indices) ||
2955 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2956 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002957
Chris Lattner392be582010-02-12 20:49:41 +00002958 if (!Val->getType()->isAggregateType())
2959 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002960 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002961 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002962 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002963 ID.Kind = ValID::t_Constant;
2964 return false;
2965 }
2966 case lltok::kw_insertvalue: {
2967 Lex.Lex();
2968 Constant *Val0, *Val1;
2969 SmallVector<unsigned, 4> Indices;
2970 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2971 ParseGlobalTypeAndValue(Val0) ||
2972 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2973 ParseGlobalTypeAndValue(Val1) ||
2974 ParseIndexList(Indices) ||
2975 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2976 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002977 if (!Val0->getType()->isAggregateType())
2978 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002979 Type *IndexedType =
2980 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2981 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002982 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002983 if (IndexedType != Val1->getType())
2984 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2985 getTypeString(Val1->getType()) +
2986 "' instead of '" + getTypeString(IndexedType) +
2987 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002988 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002989 ID.Kind = ValID::t_Constant;
2990 return false;
2991 }
2992 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002993 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 unsigned PredVal, Opc = Lex.getUIntVal();
2995 Constant *Val0, *Val1;
2996 Lex.Lex();
2997 if (ParseCmpPredicate(PredVal, Opc) ||
2998 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2999 ParseGlobalTypeAndValue(Val0) ||
3000 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3001 ParseGlobalTypeAndValue(Val1) ||
3002 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3003 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003004
Chris Lattnerac161bf2009-01-02 07:01:27 +00003005 if (Val0->getType() != Val1->getType())
3006 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003007
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003009
Chris Lattnerac161bf2009-01-02 07:01:27 +00003010 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003011 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003012 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003013 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003014 } else {
3015 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003016 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003017 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003018 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003019 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 }
3021 ID.Kind = ValID::t_Constant;
3022 return false;
3023 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003024
Chris Lattnerac161bf2009-01-02 07:01:27 +00003025 // Binary Operators.
3026 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003027 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003028 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003029 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003031 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 case lltok::kw_udiv:
3033 case lltok::kw_sdiv:
3034 case lltok::kw_fdiv:
3035 case lltok::kw_urem:
3036 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003037 case lltok::kw_frem:
3038 case lltok::kw_shl:
3039 case lltok::kw_lshr:
3040 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003041 bool NUW = false;
3042 bool NSW = false;
3043 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003044 unsigned Opc = Lex.getUIntVal();
3045 Constant *Val0, *Val1;
3046 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003047 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003048 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3049 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003050 if (EatIfPresent(lltok::kw_nuw))
3051 NUW = true;
3052 if (EatIfPresent(lltok::kw_nsw)) {
3053 NSW = true;
3054 if (EatIfPresent(lltok::kw_nuw))
3055 NUW = true;
3056 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003057 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3058 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003059 if (EatIfPresent(lltok::kw_exact))
3060 Exact = true;
3061 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003062 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3063 ParseGlobalTypeAndValue(Val0) ||
3064 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3065 ParseGlobalTypeAndValue(Val1) ||
3066 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3067 return true;
3068 if (Val0->getType() != Val1->getType())
3069 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003070 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003071 if (NUW)
3072 return Error(ModifierLoc, "nuw only applies to integer operations");
3073 if (NSW)
3074 return Error(ModifierLoc, "nsw only applies to integer operations");
3075 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003076 // Check that the type is valid for the operator.
3077 switch (Opc) {
3078 case Instruction::Add:
3079 case Instruction::Sub:
3080 case Instruction::Mul:
3081 case Instruction::UDiv:
3082 case Instruction::SDiv:
3083 case Instruction::URem:
3084 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003085 case Instruction::Shl:
3086 case Instruction::AShr:
3087 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003088 if (!Val0->getType()->isIntOrIntVectorTy())
3089 return Error(ID.Loc, "constexpr requires integer operands");
3090 break;
3091 case Instruction::FAdd:
3092 case Instruction::FSub:
3093 case Instruction::FMul:
3094 case Instruction::FDiv:
3095 case Instruction::FRem:
3096 if (!Val0->getType()->isFPOrFPVectorTy())
3097 return Error(ID.Loc, "constexpr requires fp operands");
3098 break;
3099 default: llvm_unreachable("Unknown binary operator!");
3100 }
Dan Gohman1b849082009-09-07 23:54:19 +00003101 unsigned Flags = 0;
3102 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3103 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003104 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003105 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003106 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003107 ID.Kind = ValID::t_Constant;
3108 return false;
3109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003110
Chris Lattnerac161bf2009-01-02 07:01:27 +00003111 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112 case lltok::kw_and:
3113 case lltok::kw_or:
3114 case lltok::kw_xor: {
3115 unsigned Opc = Lex.getUIntVal();
3116 Constant *Val0, *Val1;
3117 Lex.Lex();
3118 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3119 ParseGlobalTypeAndValue(Val0) ||
3120 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3121 ParseGlobalTypeAndValue(Val1) ||
3122 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3123 return true;
3124 if (Val0->getType() != Val1->getType())
3125 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003126 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003127 return Error(ID.Loc,
3128 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003129 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003130 ID.Kind = ValID::t_Constant;
3131 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003132 }
3133
Chris Lattnerac161bf2009-01-02 07:01:27 +00003134 case lltok::kw_getelementptr:
3135 case lltok::kw_shufflevector:
3136 case lltok::kw_insertelement:
3137 case lltok::kw_extractelement:
3138 case lltok::kw_select: {
3139 unsigned Opc = Lex.getUIntVal();
3140 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003141 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003142 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003143 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003144
Dan Gohman1639c392009-07-27 21:53:46 +00003145 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003146 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003147
3148 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3149 return true;
3150
3151 LocTy ExplicitTypeLoc = Lex.getLoc();
3152 if (Opc == Instruction::GetElementPtr) {
3153 if (ParseType(Ty) ||
3154 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3155 return true;
3156 }
3157
3158 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003159 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3160 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003161
Chris Lattnerac161bf2009-01-02 07:01:27 +00003162 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003163 if (Elts.size() == 0 ||
3164 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003165 return Error(ID.Loc, "base of getelementptr must be a pointer");
3166
3167 Type *BaseType = Elts[0]->getType();
3168 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003169 if (Ty != BasePointerType->getElementType())
3170 return Error(
3171 ExplicitTypeLoc,
3172 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003173
Jay Foaded8db7d2011-07-21 14:31:17 +00003174 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003175 for (Constant *Val : Indices) {
3176 Type *ValTy = Val->getType();
3177 if (!ValTy->getScalarType()->isIntegerTy())
3178 return Error(ID.Loc, "getelementptr index must be an integer");
3179 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3180 return Error(ID.Loc, "getelementptr index type missmatch");
3181 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003182 unsigned ValNumEl = ValTy->getVectorNumElements();
3183 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003184 if (ValNumEl != PtrNumEl)
3185 return Error(
3186 ID.Loc,
3187 "getelementptr vector index has a wrong number of elements");
3188 }
3189 }
3190
Craig Toppere3dcce92015-08-01 22:20:21 +00003191 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003192 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003193 return Error(ID.Loc, "base element of getelementptr must be sized");
3194
David Blaikie4a2e73b2015-04-02 18:55:32 +00003195 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003196 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003197 ID.ConstantVal =
3198 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003199 } else if (Opc == Instruction::Select) {
3200 if (Elts.size() != 3)
3201 return Error(ID.Loc, "expected three operands to select");
3202 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3203 Elts[2]))
3204 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003205 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003206 } else if (Opc == Instruction::ShuffleVector) {
3207 if (Elts.size() != 3)
3208 return Error(ID.Loc, "expected three operands to shufflevector");
3209 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3210 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003211 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003212 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 } else if (Opc == Instruction::ExtractElement) {
3214 if (Elts.size() != 2)
3215 return Error(ID.Loc, "expected two operands to extractelement");
3216 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3217 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003218 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003219 } else {
3220 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3221 if (Elts.size() != 3)
3222 return Error(ID.Loc, "expected three operands to insertelement");
3223 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3224 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003225 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003226 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003227 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003228
Chris Lattnerac161bf2009-01-02 07:01:27 +00003229 ID.Kind = ValID::t_Constant;
3230 return false;
3231 }
3232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003233
Chris Lattnerac161bf2009-01-02 07:01:27 +00003234 Lex.Lex();
3235 return false;
3236}
3237
3238/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003239bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003240 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003242 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003243 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003244 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003245 if (V && !(C = dyn_cast<Constant>(V)))
3246 return Error(ID.Loc, "global values must be constants");
3247 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003248}
3249
Victor Hernandez9d75c962010-01-11 22:31:58 +00003250bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003251 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003252 return ParseType(Ty) ||
3253 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003254}
3255
Rafael Espindola83a362c2015-01-06 22:55:16 +00003256bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003257 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003258
3259 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003260 if (!EatIfPresent(lltok::kw_comdat))
3261 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003262
3263 if (EatIfPresent(lltok::lparen)) {
3264 if (Lex.getKind() != lltok::ComdatVar)
3265 return TokError("expected comdat variable");
3266 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3267 Lex.Lex();
3268 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3269 return true;
3270 } else {
3271 if (GlobalName.empty())
3272 return TokError("comdat cannot be unnamed");
3273 C = getComdat(GlobalName, KwLoc);
3274 }
3275
David Majnemerdad0a642014-06-27 18:19:56 +00003276 return false;
3277}
3278
Victor Hernandez9d75c962010-01-11 22:31:58 +00003279/// ParseGlobalValueVector
3280/// ::= /*empty*/
3281/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003282bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003283 // Empty list.
3284 if (Lex.getKind() == lltok::rbrace ||
3285 Lex.getKind() == lltok::rsquare ||
3286 Lex.getKind() == lltok::greater ||
3287 Lex.getKind() == lltok::rparen)
3288 return false;
3289
3290 Constant *C;
3291 if (ParseGlobalTypeAndValue(C)) return true;
3292 Elts.push_back(C);
3293
3294 while (EatIfPresent(lltok::comma)) {
3295 if (ParseGlobalTypeAndValue(C)) return true;
3296 Elts.push_back(C);
3297 }
3298
3299 return false;
3300}
3301
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003302bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003303 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003304 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003305 return true;
3306
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003307 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003308 return false;
3309}
3310
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003311/// MDNode:
3312/// ::= !{ ... }
3313/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003314/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003315bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003316 if (Lex.getKind() == lltok::MetadataVar)
3317 return ParseSpecializedMDNode(N);
3318
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003319 return ParseToken(lltok::exclaim, "expected '!' here") ||
3320 ParseMDNodeTail(N);
3321}
3322
3323bool LLParser::ParseMDNodeTail(MDNode *&N) {
3324 // !{ ... }
3325 if (Lex.getKind() == lltok::lbrace)
3326 return ParseMDTuple(N);
3327
3328 // !42
3329 return ParseMDNodeID(N);
3330}
3331
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003332namespace {
3333
3334/// Structure to represent an optional metadata field.
3335template <class FieldTy> struct MDFieldImpl {
3336 typedef MDFieldImpl ImplTy;
3337 FieldTy Val;
3338 bool Seen;
3339
3340 void assign(FieldTy Val) {
3341 Seen = true;
3342 this->Val = std::move(Val);
3343 }
3344
3345 explicit MDFieldImpl(FieldTy Default)
3346 : Val(std::move(Default)), Seen(false) {}
3347};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003348
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003349struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3350 uint64_t Max;
3351
3352 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3353 : ImplTy(Default), Max(Max) {}
3354};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003355struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003356 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003357};
3358struct ColumnField : public MDUnsignedField {
3359 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3360};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003361struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003362 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003363 DwarfTagField(dwarf::Tag DefaultTag)
3364 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003365};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003366struct DwarfMacinfoTypeField : public MDUnsignedField {
3367 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3368 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3369 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3370};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003371struct DwarfAttEncodingField : public MDUnsignedField {
3372 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3373};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003374struct DwarfVirtualityField : public MDUnsignedField {
3375 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3376};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003377struct DwarfLangField : public MDUnsignedField {
3378 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3379};
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003380struct DwarfCCField : public MDUnsignedField {
3381 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3382};
Adrian Prantlb939a252016-03-31 23:56:58 +00003383struct EmissionKindField : public MDUnsignedField {
3384 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3385};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003386
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003387struct DIFlagField : public MDUnsignedField {
3388 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3389};
3390
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003391struct MDSignedField : public MDFieldImpl<int64_t> {
3392 int64_t Min;
3393 int64_t Max;
3394
3395 MDSignedField(int64_t Default = 0)
3396 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3397 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3398 : ImplTy(Default), Min(Min), Max(Max) {}
3399};
3400
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003401struct MDBoolField : public MDFieldImpl<bool> {
3402 MDBoolField(bool Default = false) : ImplTy(Default) {}
3403};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003404struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003405 bool AllowNull;
3406
3407 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003408};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003409struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3410 MDConstant() : ImplTy(nullptr) {}
3411};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003412struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003413 bool AllowEmpty;
3414 MDStringField(bool AllowEmpty = true)
3415 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003416};
3417struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3418 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3419};
3420
3421} // end namespace
3422
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003423namespace llvm {
3424
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003425template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003426bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003427 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003428 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3429 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003430
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003431 auto &U = Lex.getAPSIntVal();
3432 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003433 return TokError("value for '" + Name + "' too large, limit is " +
3434 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003435 Result.assign(U.getZExtValue());
3436 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003437 Lex.Lex();
3438 return false;
3439}
3440
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003441template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003442bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3443 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3444}
3445template <>
3446bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3447 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3448}
3449
3450template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003451bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3452 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003453 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003454
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003455 if (Lex.getKind() != lltok::DwarfTag)
3456 return TokError("expected DWARF tag");
3457
3458 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3459 if (Tag == dwarf::DW_TAG_invalid)
3460 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003461 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003462
3463 Result.assign(Tag);
3464 Lex.Lex();
3465 return false;
3466}
3467
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003468template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003469bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003470 DwarfMacinfoTypeField &Result) {
3471 if (Lex.getKind() == lltok::APSInt)
3472 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3473
3474 if (Lex.getKind() != lltok::DwarfMacinfo)
3475 return TokError("expected DWARF macinfo type");
3476
3477 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3478 if (Macinfo == dwarf::DW_MACINFO_invalid)
3479 return TokError(
3480 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3481 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3482
3483 Result.assign(Macinfo);
3484 Lex.Lex();
3485 return false;
3486}
3487
3488template <>
3489bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003490 DwarfVirtualityField &Result) {
3491 if (Lex.getKind() == lltok::APSInt)
3492 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3493
3494 if (Lex.getKind() != lltok::DwarfVirtuality)
3495 return TokError("expected DWARF virtuality code");
3496
3497 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003498 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003499 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3500 Lex.getStrVal() + "'");
3501 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3502 Result.assign(Virtuality);
3503 Lex.Lex();
3504 return false;
3505}
3506
3507template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003508bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3509 if (Lex.getKind() == lltok::APSInt)
3510 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3511
3512 if (Lex.getKind() != lltok::DwarfLang)
3513 return TokError("expected DWARF language");
3514
3515 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3516 if (!Lang)
3517 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3518 "'");
3519 assert(Lang <= Result.Max && "Expected valid DWARF language");
3520 Result.assign(Lang);
3521 Lex.Lex();
3522 return false;
3523}
3524
3525template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003526bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3527 if (Lex.getKind() == lltok::APSInt)
3528 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3529
3530 if (Lex.getKind() != lltok::DwarfCC)
3531 return TokError("expected DWARF calling convention");
3532
3533 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3534 if (!CC)
3535 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3536 "'");
3537 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3538 Result.assign(CC);
3539 Lex.Lex();
3540 return false;
3541}
3542
3543template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003544bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3545 if (Lex.getKind() == lltok::APSInt)
3546 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3547
3548 if (Lex.getKind() != lltok::EmissionKind)
3549 return TokError("expected emission kind");
3550
3551 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3552 if (!Kind)
3553 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3554 "'");
3555 assert(*Kind <= Result.Max && "Expected valid emission kind");
3556 Result.assign(*Kind);
3557 Lex.Lex();
3558 return false;
3559}
3560
3561template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003562bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003563 DwarfAttEncodingField &Result) {
3564 if (Lex.getKind() == lltok::APSInt)
3565 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3566
3567 if (Lex.getKind() != lltok::DwarfAttEncoding)
3568 return TokError("expected DWARF type attribute encoding");
3569
3570 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3571 if (!Encoding)
3572 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3573 Lex.getStrVal() + "'");
3574 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3575 Result.assign(Encoding);
3576 Lex.Lex();
3577 return false;
3578}
3579
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003580/// DIFlagField
3581/// ::= uint32
3582/// ::= DIFlagVector
3583/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3584template <>
3585bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3586 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3587
3588 // Parser for a single flag.
3589 auto parseFlag = [&](unsigned &Val) {
3590 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3591 return ParseUInt32(Val);
3592
3593 if (Lex.getKind() != lltok::DIFlag)
3594 return TokError("expected debug info flag");
3595
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003596 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003597 if (!Val)
3598 return TokError(Twine("invalid debug info flag flag '") +
3599 Lex.getStrVal() + "'");
3600 Lex.Lex();
3601 return false;
3602 };
3603
3604 // Parse the flags and combine them together.
3605 unsigned Combined = 0;
3606 do {
3607 unsigned Val;
3608 if (parseFlag(Val))
3609 return true;
3610 Combined |= Val;
3611 } while (EatIfPresent(lltok::bar));
3612
3613 Result.assign(Combined);
3614 return false;
3615}
3616
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003617template <>
3618bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003619 MDSignedField &Result) {
3620 if (Lex.getKind() != lltok::APSInt)
3621 return TokError("expected signed integer");
3622
3623 auto &S = Lex.getAPSIntVal();
3624 if (S < Result.Min)
3625 return TokError("value for '" + Name + "' too small, limit is " +
3626 Twine(Result.Min));
3627 if (S > Result.Max)
3628 return TokError("value for '" + Name + "' too large, limit is " +
3629 Twine(Result.Max));
3630 Result.assign(S.getExtValue());
3631 assert(Result.Val >= Result.Min && "Expected value in range");
3632 assert(Result.Val <= Result.Max && "Expected value in range");
3633 Lex.Lex();
3634 return false;
3635}
3636
3637template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003638bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3639 switch (Lex.getKind()) {
3640 default:
3641 return TokError("expected 'true' or 'false'");
3642 case lltok::kw_true:
3643 Result.assign(true);
3644 break;
3645 case lltok::kw_false:
3646 Result.assign(false);
3647 break;
3648 }
3649 Lex.Lex();
3650 return false;
3651}
3652
3653template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003654bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003655 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003656 if (!Result.AllowNull)
3657 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003658 Lex.Lex();
3659 Result.assign(nullptr);
3660 return false;
3661 }
3662
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003663 Metadata *MD;
3664 if (ParseMetadata(MD, nullptr))
3665 return true;
3666
3667 Result.assign(MD);
3668 return false;
3669}
3670
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003671template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003672bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3673 Metadata *MD;
3674 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3675 return true;
3676
3677 Result.assign(cast<ConstantAsMetadata>(MD));
3678 return false;
3679}
3680
3681template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003682bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003683 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003684 std::string S;
3685 if (ParseStringConstant(S))
3686 return true;
3687
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003688 if (!Result.AllowEmpty && S.empty())
3689 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3690
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003691 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003692 return false;
3693}
3694
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003695template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003696bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3697 SmallVector<Metadata *, 4> MDs;
3698 if (ParseMDNodeVector(MDs))
3699 return true;
3700
3701 Result.assign(std::move(MDs));
3702 return false;
3703}
3704
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003705} // end namespace llvm
3706
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003707template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003708bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003709 do {
3710 if (Lex.getKind() != lltok::LabelStr)
3711 return TokError("expected field label here");
3712
3713 if (parseField())
3714 return true;
3715 } while (EatIfPresent(lltok::comma));
3716
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003717 return false;
3718}
3719
3720template <class ParserTy>
3721bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3722 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3723 Lex.Lex();
3724
3725 if (ParseToken(lltok::lparen, "expected '(' here"))
3726 return true;
3727 if (Lex.getKind() != lltok::rparen)
3728 if (ParseMDFieldsImplBody(parseField))
3729 return true;
3730
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003731 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003732 return ParseToken(lltok::rparen, "expected ')' here");
3733}
3734
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003735template <class FieldTy>
3736bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3737 if (Result.Seen)
3738 return TokError("field '" + Name + "' cannot be specified more than once");
3739
3740 LocTy Loc = Lex.getLoc();
3741 Lex.Lex();
3742 return ParseMDField(Loc, Name, Result);
3743}
3744
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003745bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3746 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003747
3748#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003749 if (Lex.getStrVal() == #CLASS) \
3750 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003751#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003752
3753 return TokError("expected metadata type");
3754}
3755
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003756#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3757#define NOP_FIELD(NAME, TYPE, INIT)
3758#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3759 if (!NAME.Seen) \
3760 return Error(ClosingLoc, "missing required field '" #NAME "'");
3761#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003762 if (Lex.getStrVal() == #NAME) \
3763 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003764#define PARSE_MD_FIELDS() \
3765 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3766 do { \
3767 LocTy ClosingLoc; \
3768 if (ParseMDFieldsImpl([&]() -> bool { \
3769 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3770 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3771 }, ClosingLoc)) \
3772 return true; \
3773 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3774 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003775#define GET_OR_DISTINCT(CLASS, ARGS) \
3776 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003777
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003778/// ParseDILocationFields:
3779/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3780bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003781#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003782 OPTIONAL(line, LineField, ); \
3783 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003784 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003785 OPTIONAL(inlinedAt, MDField, );
3786 PARSE_MD_FIELDS();
3787#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003788
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003789 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003790 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003791 return false;
3792}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003793
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003794/// ParseGenericDINode:
3795/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3796bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003797#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003798 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003799 OPTIONAL(header, MDStringField, ); \
3800 OPTIONAL(operands, MDFieldList, );
3801 PARSE_MD_FIELDS();
3802#undef VISIT_MD_FIELDS
3803
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003804 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003805 (Context, tag.Val, header.Val, operands.Val));
3806 return false;
3807}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003808
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003809/// ParseDISubrange:
3810/// ::= !DISubrange(count: 30, lowerBound: 2)
3811bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003812#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003813 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003814 OPTIONAL(lowerBound, MDSignedField, );
3815 PARSE_MD_FIELDS();
3816#undef VISIT_MD_FIELDS
3817
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003818 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003819 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003820}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003821
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003822/// ParseDIEnumerator:
3823/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3824bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003826 REQUIRED(name, MDStringField, ); \
3827 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003828 PARSE_MD_FIELDS();
3829#undef VISIT_MD_FIELDS
3830
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003831 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003832 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003833}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003834
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003835/// ParseDIBasicType:
3836/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3837bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003838#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003839 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003840 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003841 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3842 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003843 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003844 PARSE_MD_FIELDS();
3845#undef VISIT_MD_FIELDS
3846
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003847 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003848 align.Val, encoding.Val));
3849 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003850}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003852/// ParseDIDerivedType:
3853/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003854/// line: 7, scope: !1, baseType: !2, size: 32,
3855/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003856bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003857#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3858 REQUIRED(tag, DwarfTagField, ); \
3859 OPTIONAL(name, MDStringField, ); \
3860 OPTIONAL(file, MDField, ); \
3861 OPTIONAL(line, LineField, ); \
3862 OPTIONAL(scope, MDField, ); \
3863 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003864 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3865 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3866 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003867 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003868 OPTIONAL(extraData, MDField, );
3869 PARSE_MD_FIELDS();
3870#undef VISIT_MD_FIELDS
3871
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003872 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003873 (Context, tag.Val, name.Val, file.Val, line.Val,
3874 scope.Val, baseType.Val, size.Val, align.Val,
3875 offset.Val, flags.Val, extraData.Val));
3876 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003877}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003878
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003879bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3881 REQUIRED(tag, DwarfTagField, ); \
3882 OPTIONAL(name, MDStringField, ); \
3883 OPTIONAL(file, MDField, ); \
3884 OPTIONAL(line, LineField, ); \
3885 OPTIONAL(scope, MDField, ); \
3886 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003887 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3888 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3889 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003890 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003891 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003892 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003893 OPTIONAL(vtableHolder, MDField, ); \
3894 OPTIONAL(templateParams, MDField, ); \
3895 OPTIONAL(identifier, MDStringField, );
3896 PARSE_MD_FIELDS();
3897#undef VISIT_MD_FIELDS
3898
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003899 // If this has an identifier try to build an ODR type.
3900 if (identifier.Val)
3901 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003902 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3903 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3904 elements.Val, runtimeLang.Val, vtableHolder.Val,
3905 templateParams.Val)) {
3906 Result = CT;
3907 return false;
3908 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003909
3910 // Create a new node, and save it in the context if it belongs in the type
3911 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003912 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003913 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003914 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3915 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3916 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3917 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003918}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003919
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003920bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003921#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003922 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003923 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003924 REQUIRED(types, MDField, );
3925 PARSE_MD_FIELDS();
3926#undef VISIT_MD_FIELDS
3927
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003928 Result = GET_OR_DISTINCT(DISubroutineType,
3929 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003930 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003931}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003932
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003933/// ParseDIFileType:
3934/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3935bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3937 REQUIRED(filename, MDStringField, ); \
3938 REQUIRED(directory, MDStringField, );
3939 PARSE_MD_FIELDS();
3940#undef VISIT_MD_FIELDS
3941
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003942 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003943 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003944}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003945
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003946/// ParseDICompileUnit:
3947/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003948/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003949/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003950/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003951/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003952bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003953 if (!IsDistinct)
3954 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3955
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003956#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3957 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003958 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003959 OPTIONAL(producer, MDStringField, ); \
3960 OPTIONAL(isOptimized, MDBoolField, ); \
3961 OPTIONAL(flags, MDStringField, ); \
3962 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3963 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003964 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003965 OPTIONAL(enums, MDField, ); \
3966 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003967 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003968 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003969 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003970 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003971 PARSE_MD_FIELDS();
3972#undef VISIT_MD_FIELDS
3973
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003974 Result = DICompileUnit::getDistinct(
3975 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3976 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Adrian Prantl75819ae2016-04-15 15:57:41 +00003977 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003978 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003979}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003980
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003981/// ParseDISubprogram:
3982/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003983/// file: !1, line: 7, type: !2, isLocal: false,
3984/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003985/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00003986/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003987/// isOptimized: false, templateParams: !4, declaration: !5,
3988/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003989bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003990 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003991#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3992 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003993 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003994 OPTIONAL(linkageName, MDStringField, ); \
3995 OPTIONAL(file, MDField, ); \
3996 OPTIONAL(line, LineField, ); \
3997 OPTIONAL(type, MDField, ); \
3998 OPTIONAL(isLocal, MDBoolField, ); \
3999 OPTIONAL(isDefinition, MDBoolField, (true)); \
4000 OPTIONAL(scopeLine, LineField, ); \
4001 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004002 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004003 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004004 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004005 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004006 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004007 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004008 OPTIONAL(templateParams, MDField, ); \
4009 OPTIONAL(declaration, MDField, ); \
4010 OPTIONAL(variables, MDField, );
4011 PARSE_MD_FIELDS();
4012#undef VISIT_MD_FIELDS
4013
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004014 if (isDefinition.Val && !IsDistinct)
4015 return Lex.Error(
4016 Loc,
4017 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4018
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004019 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004020 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4021 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4022 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004023 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4024 isOptimized.Val, unit.Val, templateParams.Val,
4025 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004026 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004027}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004028
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004029/// ParseDILexicalBlock:
4030/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4031bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004032#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004033 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004034 OPTIONAL(file, MDField, ); \
4035 OPTIONAL(line, LineField, ); \
4036 OPTIONAL(column, ColumnField, );
4037 PARSE_MD_FIELDS();
4038#undef VISIT_MD_FIELDS
4039
4040 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004041 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004042 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004043}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004044
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004045/// ParseDILexicalBlockFile:
4046/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4047bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004048#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004049 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004050 OPTIONAL(file, MDField, ); \
4051 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4052 PARSE_MD_FIELDS();
4053#undef VISIT_MD_FIELDS
4054
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004055 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004056 (Context, scope.Val, file.Val, discriminator.Val));
4057 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004058}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004059
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004060/// ParseDINamespace:
4061/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4062bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004063#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4064 REQUIRED(scope, MDField, ); \
4065 OPTIONAL(file, MDField, ); \
4066 OPTIONAL(name, MDStringField, ); \
4067 OPTIONAL(line, LineField, );
4068 PARSE_MD_FIELDS();
4069#undef VISIT_MD_FIELDS
4070
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004071 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004072 (Context, scope.Val, file.Val, name.Val, line.Val));
4073 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004074}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004075
Amjad Abouda9bcf162015-12-10 12:56:35 +00004076/// ParseDIMacro:
4077/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4078bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4079#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4080 REQUIRED(type, DwarfMacinfoTypeField, ); \
4081 REQUIRED(line, LineField, ); \
4082 REQUIRED(name, MDStringField, ); \
4083 OPTIONAL(value, MDStringField, );
4084 PARSE_MD_FIELDS();
4085#undef VISIT_MD_FIELDS
4086
4087 Result = GET_OR_DISTINCT(DIMacro,
4088 (Context, type.Val, line.Val, name.Val, value.Val));
4089 return false;
4090}
4091
4092/// ParseDIMacroFile:
4093/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4094bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4095#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4096 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4097 REQUIRED(line, LineField, ); \
4098 REQUIRED(file, MDField, ); \
4099 OPTIONAL(nodes, MDField, );
4100 PARSE_MD_FIELDS();
4101#undef VISIT_MD_FIELDS
4102
4103 Result = GET_OR_DISTINCT(DIMacroFile,
4104 (Context, type.Val, line.Val, file.Val, nodes.Val));
4105 return false;
4106}
4107
4108
Adrian Prantlab1243f2015-06-29 23:03:47 +00004109/// ParseDIModule:
4110/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4111/// includePath: "/usr/include", isysroot: "/")
4112bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4113#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4114 REQUIRED(scope, MDField, ); \
4115 REQUIRED(name, MDStringField, ); \
4116 OPTIONAL(configMacros, MDStringField, ); \
4117 OPTIONAL(includePath, MDStringField, ); \
4118 OPTIONAL(isysroot, MDStringField, );
4119 PARSE_MD_FIELDS();
4120#undef VISIT_MD_FIELDS
4121
4122 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4123 configMacros.Val, includePath.Val, isysroot.Val));
4124 return false;
4125}
4126
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004127/// ParseDITemplateTypeParameter:
4128/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4129bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004130#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004131 OPTIONAL(name, MDStringField, ); \
4132 REQUIRED(type, MDField, );
4133 PARSE_MD_FIELDS();
4134#undef VISIT_MD_FIELDS
4135
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004136 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004137 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004138 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004139}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004140
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004141/// ParseDITemplateValueParameter:
4142/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004143/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004144bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004145#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004146 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004147 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004148 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004149 REQUIRED(value, MDField, );
4150 PARSE_MD_FIELDS();
4151#undef VISIT_MD_FIELDS
4152
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004153 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004154 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004155 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004156}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004157
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004158/// ParseDIGlobalVariable:
4159/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004160/// file: !1, line: 7, type: !2, isLocal: false,
4161/// isDefinition: true, variable: i32* @foo,
4162/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004163bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004164#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004165 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004166 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004167 OPTIONAL(linkageName, MDStringField, ); \
4168 OPTIONAL(file, MDField, ); \
4169 OPTIONAL(line, LineField, ); \
4170 OPTIONAL(type, MDField, ); \
4171 OPTIONAL(isLocal, MDBoolField, ); \
4172 OPTIONAL(isDefinition, MDBoolField, (true)); \
4173 OPTIONAL(variable, MDConstant, ); \
4174 OPTIONAL(declaration, MDField, );
4175 PARSE_MD_FIELDS();
4176#undef VISIT_MD_FIELDS
4177
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004178 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004179 (Context, scope.Val, name.Val, linkageName.Val,
4180 file.Val, line.Val, type.Val, isLocal.Val,
4181 isDefinition.Val, variable.Val, declaration.Val));
4182 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004183}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004184
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004185/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004186/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4187/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4188/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004189/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004190bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004191#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004192 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004193 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004194 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004195 OPTIONAL(file, MDField, ); \
4196 OPTIONAL(line, LineField, ); \
4197 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004198 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004199 PARSE_MD_FIELDS();
4200#undef VISIT_MD_FIELDS
4201
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004202 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004203 (Context, scope.Val, name.Val, file.Val, line.Val,
4204 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004205 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004206}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004207
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004208/// ParseDIExpression:
4209/// ::= !DIExpression(0, 7, -1)
4210bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004211 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4212 Lex.Lex();
4213
4214 if (ParseToken(lltok::lparen, "expected '(' here"))
4215 return true;
4216
4217 SmallVector<uint64_t, 8> Elements;
4218 if (Lex.getKind() != lltok::rparen)
4219 do {
4220 if (Lex.getKind() == lltok::DwarfOp) {
4221 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4222 Lex.Lex();
4223 Elements.push_back(Op);
4224 continue;
4225 }
4226 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4227 }
4228
4229 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4230 return TokError("expected unsigned integer");
4231
4232 auto &U = Lex.getAPSIntVal();
4233 if (U.ugt(UINT64_MAX))
4234 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4235 Elements.push_back(U.getZExtValue());
4236 Lex.Lex();
4237 } while (EatIfPresent(lltok::comma));
4238
4239 if (ParseToken(lltok::rparen, "expected ')' here"))
4240 return true;
4241
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004242 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004243 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004244}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004245
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004246/// ParseDIObjCProperty:
4247/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004248/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004249bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004250#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004251 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004252 OPTIONAL(file, MDField, ); \
4253 OPTIONAL(line, LineField, ); \
4254 OPTIONAL(setter, MDStringField, ); \
4255 OPTIONAL(getter, MDStringField, ); \
4256 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4257 OPTIONAL(type, MDField, );
4258 PARSE_MD_FIELDS();
4259#undef VISIT_MD_FIELDS
4260
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004261 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004262 (Context, name.Val, file.Val, line.Val, setter.Val,
4263 getter.Val, attributes.Val, type.Val));
4264 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004265}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004266
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004267/// ParseDIImportedEntity:
4268/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004269/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004270bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004271#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4272 REQUIRED(tag, DwarfTagField, ); \
4273 REQUIRED(scope, MDField, ); \
4274 OPTIONAL(entity, MDField, ); \
4275 OPTIONAL(line, LineField, ); \
4276 OPTIONAL(name, MDStringField, );
4277 PARSE_MD_FIELDS();
4278#undef VISIT_MD_FIELDS
4279
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004280 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004281 entity.Val, line.Val, name.Val));
4282 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004283}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004284
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004285#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004286#undef NOP_FIELD
4287#undef REQUIRE_FIELD
4288#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004289
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004290/// ParseMetadataAsValue
4291/// ::= metadata i32 %local
4292/// ::= metadata i32 @global
4293/// ::= metadata i32 7
4294/// ::= metadata !0
4295/// ::= metadata !{...}
4296/// ::= metadata !"string"
4297bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4298 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004299 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004300 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004301 return true;
4302
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004303 V = MetadataAsValue::get(Context, MD);
4304 return false;
4305}
4306
4307/// ParseValueAsMetadata
4308/// ::= i32 %local
4309/// ::= i32 @global
4310/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004311bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4312 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004313 Type *Ty;
4314 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004315 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004316 return true;
4317 if (Ty->isMetadataTy())
4318 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4319
4320 Value *V;
4321 if (ParseValue(Ty, V, PFS))
4322 return true;
4323
4324 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004325 return false;
4326}
4327
4328/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004329/// ::= i32 %local
4330/// ::= i32 @global
4331/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004332/// ::= !42
4333/// ::= !{...}
4334/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004335/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004336bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004337 if (Lex.getKind() == lltok::MetadataVar) {
4338 MDNode *N;
4339 if (ParseSpecializedMDNode(N))
4340 return true;
4341 MD = N;
4342 return false;
4343 }
4344
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004345 // ValueAsMetadata:
4346 // <type> <value>
4347 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004348 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004349
4350 // '!'.
4351 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4352 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004353
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004354 // MDString:
4355 // ::= '!' STRINGCONSTANT
4356 if (Lex.getKind() == lltok::StringConstant) {
4357 MDString *S;
4358 if (ParseMDString(S))
4359 return true;
4360 MD = S;
4361 return false;
4362 }
4363
Dan Gohman8939ba332010-07-14 18:26:50 +00004364 // MDNode:
4365 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004366 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004367 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004368 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004369 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004370 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004371 return false;
4372}
4373
Victor Hernandez9d75c962010-01-11 22:31:58 +00004374
4375//===----------------------------------------------------------------------===//
4376// Function Parsing.
4377//===----------------------------------------------------------------------===//
4378
Chris Lattner229907c2011-07-18 04:54:35 +00004379bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004380 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004381 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004383
Chris Lattnerac161bf2009-01-02 07:01:27 +00004384 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004385 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004386 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004387 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004388 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004389 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004390 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004391 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004392 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004393 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004394 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004395 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004396 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4397 (ID.UIntVal >> 1) & 1,
4398 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004399 return false;
4400 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 case ValID::t_GlobalName:
4402 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004403 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004404 case ValID::t_GlobalID:
4405 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004406 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004407 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004408 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004409 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004410 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004411 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 return false;
4413 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004414 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004415 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4416 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004417
Dan Gohman518cda42011-12-17 00:04:22 +00004418 // The lexer has no type info, so builds all half, float, and double FP
4419 // constants as double. Fix this here. Long double does not need this.
4420 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004421 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004422 if (Ty->isHalfTy())
4423 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4424 &Ignored);
4425 else if (Ty->isFloatTy())
4426 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4427 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004428 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004429 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004430
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004431 if (V->getType() != Ty)
4432 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004433 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004434
Chris Lattnerac161bf2009-01-02 07:01:27 +00004435 return false;
4436 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004437 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004438 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004439 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004440 return false;
4441 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004442 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004443 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004444 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004445 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004446 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004447 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004448 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004449 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004450 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004451 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004452 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004453 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004454 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004455 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004456 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004457 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004458 case ValID::t_None:
4459 if (!Ty->isTokenTy())
4460 return Error(ID.Loc, "invalid type for none constant");
4461 V = Constant::getNullValue(Ty);
4462 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004464 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004465 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004466
Chris Lattnerac161bf2009-01-02 07:01:27 +00004467 V = ID.ConstantVal;
4468 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004469 case ValID::t_ConstantStruct:
4470 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004471 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004472 if (ST->getNumElements() != ID.UIntVal)
4473 return Error(ID.Loc,
4474 "initializer with struct type has wrong # elements");
4475 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4476 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004477
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004478 // Verify that the elements are compatible with the structtype.
4479 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4480 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4481 return Error(ID.Loc, "element " + Twine(i) +
4482 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004483
David Blaikieadbda4b2015-08-03 20:08:41 +00004484 V = ConstantStruct::get(
4485 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004486 } else
4487 return Error(ID.Loc, "constant expression type mismatch");
4488 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004489 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004490 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004491}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004492
Alex Lorenzd2255952015-07-17 22:07:03 +00004493bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4494 C = nullptr;
4495 ValID ID;
4496 auto Loc = Lex.getLoc();
4497 if (ParseValID(ID, /*PFS=*/nullptr))
4498 return true;
4499 switch (ID.Kind) {
4500 case ValID::t_APSInt:
4501 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004502 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004503 case ValID::t_Constant:
4504 case ValID::t_ConstantStruct:
4505 case ValID::t_PackedConstantStruct: {
4506 Value *V;
4507 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4508 return true;
4509 assert(isa<Constant>(V) && "Expected a constant value");
4510 C = cast<Constant>(V);
4511 return false;
4512 }
4513 default:
4514 return Error(Loc, "expected a constant value");
4515 }
4516}
4517
David Majnemer8a1c45d2015-12-12 05:38:55 +00004518bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004519 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004521 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004522}
4523
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004524bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004525 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004526 return ParseType(Ty) ||
4527 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004528}
4529
Chris Lattner3ed871f2009-10-27 19:13:16 +00004530bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4531 PerFunctionState &PFS) {
4532 Value *V;
4533 Loc = Lex.getLoc();
4534 if (ParseTypeAndValue(V, PFS)) return true;
4535 if (!isa<BasicBlock>(V))
4536 return Error(Loc, "expected a basic block");
4537 BB = cast<BasicBlock>(V);
4538 return false;
4539}
4540
4541
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542/// FunctionHeader
4543/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004544/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004545/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4547 // Parse the linkage.
4548 LocTy LinkageLoc = Lex.getLoc();
4549 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004550
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004551 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004552 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004553 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004554 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004555 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004556 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004558 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4559 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004560 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004561 return true;
4562
4563 // Verify that the linkage is ok.
4564 switch ((GlobalValue::LinkageTypes)Linkage) {
4565 case GlobalValue::ExternalLinkage:
4566 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004567 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004568 if (isDefine)
4569 return Error(LinkageLoc, "invalid linkage for function definition");
4570 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004571 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004573 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004574 case GlobalValue::LinkOnceAnyLinkage:
4575 case GlobalValue::LinkOnceODRLinkage:
4576 case GlobalValue::WeakAnyLinkage:
4577 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578 if (!isDefine)
4579 return Error(LinkageLoc, "invalid linkage for function declaration");
4580 break;
4581 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004582 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004583 return Error(LinkageLoc, "invalid function linkage type");
4584 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004585
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004586 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4587 return Error(LinkageLoc,
4588 "symbol with local linkage must have default visibility");
4589
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004590 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004592
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004594
4595 std::string FunctionName;
4596 if (Lex.getKind() == lltok::GlobalVar) {
4597 FunctionName = Lex.getStrVal();
4598 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4599 unsigned NameID = Lex.getUIntVal();
4600
4601 if (NameID != NumberedVals.size())
4602 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004603 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004604 } else {
4605 return TokError("expected function name");
4606 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004607
Chris Lattner3822f632009-01-02 08:05:26 +00004608 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004609
Chris Lattner3822f632009-01-02 08:05:26 +00004610 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004611 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004612
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004613 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004615 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004616 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004617 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004618 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004619 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004620 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004621 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004622 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004623 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004624 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004625 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004626 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004627
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004628 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004629 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004630 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004631 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004632 (EatIfPresent(lltok::kw_section) &&
4633 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004634 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004635 ParseOptionalAlignment(Alignment) ||
4636 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004637 ParseStringConstant(GC)) ||
4638 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004639 ParseGlobalTypeAndValue(Prefix)) ||
4640 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004641 ParseGlobalTypeAndValue(Prologue)) ||
4642 (EatIfPresent(lltok::kw_personality) &&
4643 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004644 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645
Michael Gottesman41748d72013-06-27 00:25:01 +00004646 if (FuncAttrs.contains(Attribute::Builtin))
4647 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004648
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004650 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004651 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004652 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004653 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004654
Chris Lattnerac161bf2009-01-02 07:01:27 +00004655 // Okay, if we got here, the function is syntactically valid. Convert types
4656 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004657 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004658 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004659
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004660 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004661 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4662 AttributeSet::ReturnIndex,
4663 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004664
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004666 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004667 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4668 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004669 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4670 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004671 }
4672
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004673 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004674 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4675 AttributeSet::FunctionIndex,
4676 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004677
Bill Wendlinge94d8432012-12-07 23:16:57 +00004678 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004679
Bill Wendling749a43d2012-12-30 13:50:49 +00004680 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004681 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4682
Chris Lattner229907c2011-07-18 04:54:35 +00004683 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004684 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004685 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004686
Craig Topper2617dcc2014-04-15 06:32:26 +00004687 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004688 if (!FunctionName.empty()) {
4689 // If this was a definition of a forward reference, remove the definition
4690 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004691 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004692 if (FRVI != ForwardRefVals.end()) {
4693 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004694 if (!Fn)
4695 return Error(FRVI->second.second, "invalid forward reference to "
4696 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004697 if (Fn->getType() != PFT)
4698 return Error(FRVI->second.second, "invalid forward reference to "
4699 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004700
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701 ForwardRefVals.erase(FRVI);
4702 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004703 // Reject redefinitions.
4704 return Error(NameLoc, "invalid redefinition of function '" +
4705 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004706 } else if (M->getNamedValue(FunctionName)) {
4707 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004708 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004709
Dan Gohman399d6ae2009-08-29 23:37:49 +00004710 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004711 // If this is a definition of a forward referenced function, make sure the
4712 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004713 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004714 if (I != ForwardRefValIDs.end()) {
4715 Fn = cast<Function>(I->second.first);
4716 if (Fn->getType() != PFT)
4717 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004718 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004719 ForwardRefValIDs.erase(I);
4720 }
4721 }
4722
Craig Topper2617dcc2014-04-15 06:32:26 +00004723 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004724 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4725 else // Move the forward-reference to the correct spot in the module.
4726 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4727
4728 if (FunctionName.empty())
4729 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004730
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4732 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004733 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734 Fn->setCallingConv(CC);
4735 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004736 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 Fn->setAlignment(Alignment);
4738 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004739 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004740 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004741 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004742 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004743 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004744 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004745
Chris Lattnerac161bf2009-01-02 07:01:27 +00004746 // Add all of the arguments we parsed to the function.
4747 Function::arg_iterator ArgIt = Fn->arg_begin();
4748 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4749 // If the argument has a name, insert it into the argument symbol table.
4750 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004751
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752 // Set the name, if it conflicted, it will be auto-renamed.
4753 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004755 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4757 ArgList[i].Name + "'");
4758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004759
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004760 if (isDefine)
4761 return false;
4762
Robin Morisset039781e2014-08-29 21:53:01 +00004763 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004764 ValID ID;
4765 if (FunctionName.empty()) {
4766 ID.Kind = ValID::t_GlobalID;
4767 ID.UIntVal = NumberedVals.size() - 1;
4768 } else {
4769 ID.Kind = ValID::t_GlobalName;
4770 ID.StrVal = FunctionName;
4771 }
4772 auto Blocks = ForwardRefBlockAddresses.find(ID);
4773 if (Blocks != ForwardRefBlockAddresses.end())
4774 return Error(Blocks->first.Loc,
4775 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 return false;
4777}
4778
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004779bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4780 ValID ID;
4781 if (FunctionNumber == -1) {
4782 ID.Kind = ValID::t_GlobalName;
4783 ID.StrVal = F.getName();
4784 } else {
4785 ID.Kind = ValID::t_GlobalID;
4786 ID.UIntVal = FunctionNumber;
4787 }
4788
4789 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4790 if (Blocks == P.ForwardRefBlockAddresses.end())
4791 return false;
4792
4793 for (const auto &I : Blocks->second) {
4794 const ValID &BBID = I.first;
4795 GlobalValue *GV = I.second;
4796
4797 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4798 "Expected local id or name");
4799 BasicBlock *BB;
4800 if (BBID.Kind == ValID::t_LocalName)
4801 BB = GetBB(BBID.StrVal, BBID.Loc);
4802 else
4803 BB = GetBB(BBID.UIntVal, BBID.Loc);
4804 if (!BB)
4805 return P.Error(BBID.Loc, "referenced value is not a basic block");
4806
4807 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4808 GV->eraseFromParent();
4809 }
4810
4811 P.ForwardRefBlockAddresses.erase(Blocks);
4812 return false;
4813}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814
4815/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004816/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004818 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004819 return TokError("expected '{' in function body");
4820 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004821
Chris Lattner3432c622009-10-28 03:39:23 +00004822 int FunctionNumber = -1;
4823 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004824
Chris Lattner3432c622009-10-28 03:39:23 +00004825 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004827 // Resolve block addresses and allow basic blocks to be forward-declared
4828 // within this function.
4829 if (PFS.resolveForwardRefBlockAddresses())
4830 return true;
4831 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4832
Chris Lattnerbbddd962010-01-09 19:20:07 +00004833 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004834 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004835 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004836
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004837 while (Lex.getKind() != lltok::rbrace &&
4838 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004839 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004840
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004841 while (Lex.getKind() != lltok::rbrace)
4842 if (ParseUseListOrder(&PFS))
4843 return true;
4844
Chris Lattnerac161bf2009-01-02 07:01:27 +00004845 // Eat the }.
4846 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004847
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004849 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004850}
4851
4852/// ParseBasicBlock
4853/// ::= LabelStr? Instruction*
4854bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4855 // If this basic block starts out with a name, remember it.
4856 std::string Name;
4857 LocTy NameLoc = Lex.getLoc();
4858 if (Lex.getKind() == lltok::LabelStr) {
4859 Name = Lex.getStrVal();
4860 Lex.Lex();
4861 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004862
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004864 if (!BB)
4865 return Error(NameLoc,
4866 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004867
Chris Lattnerac161bf2009-01-02 07:01:27 +00004868 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004869
Chris Lattnerac161bf2009-01-02 07:01:27 +00004870 // Parse the instructions in this block until we get a terminator.
4871 Instruction *Inst;
4872 do {
4873 // This instruction may have three possibilities for a name: a) none
4874 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4875 LocTy NameLoc = Lex.getLoc();
4876 int NameID = -1;
4877 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004878
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879 if (Lex.getKind() == lltok::LocalVarID) {
4880 NameID = Lex.getUIntVal();
4881 Lex.Lex();
4882 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4883 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004884 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 NameStr = Lex.getStrVal();
4886 Lex.Lex();
4887 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4888 return true;
4889 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004890
Chris Lattner77b89dc2009-12-30 05:23:43 +00004891 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004892 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004893 case InstError: return true;
4894 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004895 BB->getInstList().push_back(Inst);
4896
Chris Lattner77b89dc2009-12-30 05:23:43 +00004897 // With a normal result, we check to see if the instruction is followed by
4898 // a comma and metadata.
4899 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004900 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004901 return true;
4902 break;
4903 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004904 BB->getInstList().push_back(Inst);
4905
Chris Lattner77b89dc2009-12-30 05:23:43 +00004906 // If the instruction parser ate an extra comma at the end of it, it
4907 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004908 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004909 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004910 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004911 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004912
Chris Lattnerac161bf2009-01-02 07:01:27 +00004913 // Set the name on the instruction.
4914 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4915 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004916
Chris Lattnerac161bf2009-01-02 07:01:27 +00004917 return false;
4918}
4919
4920//===----------------------------------------------------------------------===//
4921// Instruction Parsing.
4922//===----------------------------------------------------------------------===//
4923
4924/// ParseInstruction - Parse one of the many different instructions.
4925///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004926int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4927 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004928 lltok::Kind Token = Lex.getKind();
4929 if (Token == lltok::Eof)
4930 return TokError("found end of file when expecting more instructions");
4931 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004932 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004933 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004934
Chris Lattnerac161bf2009-01-02 07:01:27 +00004935 switch (Token) {
4936 default: return Error(Loc, "expected instruction opcode");
4937 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004938 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4940 case lltok::kw_br: return ParseBr(Inst, PFS);
4941 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004942 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004944 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004945 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4946 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004947 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4948 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004949 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 // Binary Operators.
4951 case lltok::kw_add:
4952 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004953 case lltok::kw_mul:
4954 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004955 bool NUW = EatIfPresent(lltok::kw_nuw);
4956 bool NSW = EatIfPresent(lltok::kw_nsw);
4957 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004958
Chris Lattnera676c0f2011-02-07 16:40:21 +00004959 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004960
Chris Lattnera676c0f2011-02-07 16:40:21 +00004961 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4962 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4963 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004964 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004965 case lltok::kw_fadd:
4966 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004967 case lltok::kw_fmul:
4968 case lltok::kw_fdiv:
4969 case lltok::kw_frem: {
4970 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4971 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4972 if (Res != 0)
4973 return Res;
4974 if (FMF.any())
4975 Inst->setFastMathFlags(FMF);
4976 return 0;
4977 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004978
Chris Lattner35315d02011-02-06 21:44:57 +00004979 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004980 case lltok::kw_udiv:
4981 case lltok::kw_lshr:
4982 case lltok::kw_ashr: {
4983 bool Exact = EatIfPresent(lltok::kw_exact);
4984
4985 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4986 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4987 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004988 }
4989
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004991 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 case lltok::kw_and:
4993 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004994 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004995 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4996 case lltok::kw_fcmp: {
4997 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4998 int Res = ParseCompare(Inst, PFS, KeywordVal);
4999 if (Res != 0)
5000 return Res;
5001 if (FMF.any())
5002 Inst->setFastMathFlags(FMF);
5003 return 0;
5004 }
5005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 // Casts.
5007 case lltok::kw_trunc:
5008 case lltok::kw_zext:
5009 case lltok::kw_sext:
5010 case lltok::kw_fptrunc:
5011 case lltok::kw_fpext:
5012 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005013 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 case lltok::kw_uitofp:
5015 case lltok::kw_sitofp:
5016 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005017 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005018 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005019 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005020 // Other.
5021 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005022 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005023 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5024 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5025 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5026 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005027 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005028 // Call.
5029 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5030 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5031 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005032 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005033 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005034 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005035 case lltok::kw_load: return ParseLoad(Inst, PFS);
5036 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005037 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5038 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005039 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005040 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5041 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5042 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5043 }
5044}
5045
5046/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5047bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005048 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005049 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005050 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005051 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5052 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5053 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5054 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5055 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5056 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5057 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5058 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5059 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5060 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5061 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5062 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5063 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5064 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5065 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5066 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5067 }
5068 } else {
5069 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005070 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005071 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5072 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5073 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5074 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5075 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5076 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5077 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5078 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5079 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5080 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5081 }
5082 }
5083 Lex.Lex();
5084 return false;
5085}
5086
5087//===----------------------------------------------------------------------===//
5088// Terminator Instructions.
5089//===----------------------------------------------------------------------===//
5090
5091/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005092/// ::= 'ret' void (',' !dbg, !1)*
5093/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005094bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005095 PerFunctionState &PFS) {
5096 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005097 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005098 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005099
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005100 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005101
Chris Lattnerfdd87902009-10-05 05:54:46 +00005102 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005103 if (!ResType->isVoidTy())
5104 return Error(TypeLoc, "value doesn't match function result type '" +
5105 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005106
Owen Anderson55f1c092009-08-13 21:58:54 +00005107 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005108 return false;
5109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005110
Chris Lattnerac161bf2009-01-02 07:01:27 +00005111 Value *RV;
5112 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005114 if (ResType != RV->getType())
5115 return Error(TypeLoc, "value doesn't match function result type '" +
5116 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005117
Owen Anderson55f1c092009-08-13 21:58:54 +00005118 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005119 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005120}
5121
5122
5123/// ParseBr
5124/// ::= 'br' TypeAndValue
5125/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5126bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5127 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005128 Value *Op0;
5129 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Chris Lattnerac161bf2009-01-02 07:01:27 +00005132 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5133 Inst = BranchInst::Create(BB);
5134 return false;
5135 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005136
Owen Anderson55f1c092009-08-13 21:58:54 +00005137 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005138 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005139
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005141 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005143 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005145
Chris Lattner3ed871f2009-10-27 19:13:16 +00005146 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 return false;
5148}
5149
5150/// ParseSwitch
5151/// Instruction
5152/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5153/// JumpTable
5154/// ::= (TypeAndValue ',' TypeAndValue)*
5155bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5156 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005157 Value *Cond;
5158 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005159 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5160 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005161 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5163 return true;
5164
Duncan Sands19d0b472010-02-16 11:11:14 +00005165 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005167
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 // Parse the jump table pairs.
5169 SmallPtrSet<Value*, 32> SeenCases;
5170 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5171 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005172 Value *Constant;
5173 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005174
Chris Lattnerac161bf2009-01-02 07:01:27 +00005175 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5176 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005177 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005178 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005179
David Blaikie70573dc2014-11-19 07:49:26 +00005180 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005181 return Error(CondLoc, "duplicate case value in switch");
5182 if (!isa<ConstantInt>(Constant))
5183 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005184
Chris Lattner3ed871f2009-10-27 19:13:16 +00005185 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005187
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005189
Chris Lattner3ed871f2009-10-27 19:13:16 +00005190 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5192 SI->addCase(Table[i].first, Table[i].second);
5193 Inst = SI;
5194 return false;
5195}
5196
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005197/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005198/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005199/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5200bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005201 LocTy AddrLoc;
5202 Value *Address;
5203 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005204 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5205 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005206 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005207
Duncan Sands19d0b472010-02-16 11:11:14 +00005208 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005209 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005210
Chris Lattner3ed871f2009-10-27 19:13:16 +00005211 // Parse the destination list.
5212 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005213
Chris Lattner3ed871f2009-10-27 19:13:16 +00005214 if (Lex.getKind() != lltok::rsquare) {
5215 BasicBlock *DestBB;
5216 if (ParseTypeAndBasicBlock(DestBB, PFS))
5217 return true;
5218 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005219
Chris Lattner3ed871f2009-10-27 19:13:16 +00005220 while (EatIfPresent(lltok::comma)) {
5221 if (ParseTypeAndBasicBlock(DestBB, PFS))
5222 return true;
5223 DestList.push_back(DestBB);
5224 }
5225 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005226
Chris Lattner3ed871f2009-10-27 19:13:16 +00005227 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5228 return true;
5229
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005230 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005231 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5232 IBI->addDestination(DestList[i]);
5233 Inst = IBI;
5234 return false;
5235}
5236
5237
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238/// ParseInvoke
5239/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5240/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5241bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5242 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005243 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005244 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005245 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005246 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005247 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 LocTy RetTypeLoc;
5249 ValID CalleeID;
5250 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005251 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005252
Chris Lattner3ed871f2009-10-27 19:13:16 +00005253 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005254 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005255 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005256 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005257 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5258 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005259 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005261 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005262 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005263 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005265
Chris Lattnerac161bf2009-01-02 07:01:27 +00005266 // If RetType is a non-function pointer type, then this is the short syntax
5267 // for the call, which means that RetType is just the return type. Infer the
5268 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005269 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5270 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005271 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005272 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005273 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5274 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005275
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 if (!FunctionType::isValidReturnType(RetType))
5277 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005278
Owen Anderson4056ca92009-07-29 22:17:13 +00005279 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005281
David Blaikie41ba2b42015-07-27 23:32:19 +00005282 CalleeID.FTy = Ty;
5283
Chris Lattnerac161bf2009-01-02 07:01:27 +00005284 // Look up the callee.
5285 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005286 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5287 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005288
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005289 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005290 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005291 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005292 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5293 AttributeSet::ReturnIndex,
5294 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005295
Chris Lattnerac161bf2009-01-02 07:01:27 +00005296 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005297
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298 // Loop through FunctionType's arguments and ensure they are specified
5299 // correctly. Also, gather any parameter attributes.
5300 FunctionType::param_iterator I = Ty->param_begin();
5301 FunctionType::param_iterator E = Ty->param_end();
5302 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005303 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005304 if (I != E) {
5305 ExpectedTy = *I++;
5306 } else if (!Ty->isVarArg()) {
5307 return Error(ArgList[i].Loc, "too many arguments specified");
5308 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005309
Chris Lattnerac161bf2009-01-02 07:01:27 +00005310 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5311 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005312 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005313 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005314 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5315 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005316 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5317 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005319
Chris Lattnerac161bf2009-01-02 07:01:27 +00005320 if (I != E)
5321 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005322
David Majnemer8d22abd2015-02-23 00:01:32 +00005323 if (FnAttrs.hasAttributes()) {
5324 if (FnAttrs.hasAlignmentAttr())
5325 return Error(CallLoc, "invoke instructions may not have an alignment");
5326
Bill Wendlingf5075a42013-01-27 02:24:02 +00005327 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5328 AttributeSet::FunctionIndex,
5329 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005330 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005331
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005332 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005333 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005334
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005335 InvokeInst *II =
5336 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005337 II->setCallingConv(CC);
5338 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005339 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340 Inst = II;
5341 return false;
5342}
5343
Bill Wendlingf891bf82011-07-31 06:30:59 +00005344/// ParseResume
5345/// ::= 'resume' TypeAndValue
5346bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5347 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005348 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5349 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005350
Bill Wendlingf891bf82011-07-31 06:30:59 +00005351 ResumeInst *RI = ResumeInst::Create(Exn);
5352 Inst = RI;
5353 return false;
5354}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355
David Majnemer654e1302015-07-31 17:58:14 +00005356bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5357 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005358 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005359 return true;
5360
5361 while (Lex.getKind() != lltok::rsquare) {
5362 // If this isn't the first argument, we need a comma.
5363 if (!Args.empty() &&
5364 ParseToken(lltok::comma, "expected ',' in argument list"))
5365 return true;
5366
5367 // Parse the argument.
5368 LocTy ArgLoc;
5369 Type *ArgTy = nullptr;
5370 if (ParseType(ArgTy, ArgLoc))
5371 return true;
5372
5373 Value *V;
5374 if (ArgTy->isMetadataTy()) {
5375 if (ParseMetadataAsValue(V, PFS))
5376 return true;
5377 } else {
5378 if (ParseValue(ArgTy, V, PFS))
5379 return true;
5380 }
5381 Args.push_back(V);
5382 }
5383
5384 Lex.Lex(); // Lex the ']'.
5385 return false;
5386}
5387
5388/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005389/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005390bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005391 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005392
David Majnemer8a1c45d2015-12-12 05:38:55 +00005393 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5394 return true;
5395
5396 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005397 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005398
5399 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5400 return true;
5401
5402 BasicBlock *UnwindBB = nullptr;
5403 if (Lex.getKind() == lltok::kw_to) {
5404 Lex.Lex();
5405 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5406 return true;
5407 } else {
5408 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5409 return true;
5410 }
5411 }
5412
David Majnemer8a1c45d2015-12-12 05:38:55 +00005413 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005414 return false;
5415}
5416
5417/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005418/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005419bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005420 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005421
David Majnemer8a1c45d2015-12-12 05:38:55 +00005422 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5423 return true;
5424
5425 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005426 return true;
5427
David Majnemer0bc0eef2015-08-15 02:46:08 +00005428 BasicBlock *BB;
5429 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5430 ParseTypeAndBasicBlock(BB, PFS))
5431 return true;
5432
David Majnemer8a1c45d2015-12-12 05:38:55 +00005433 Inst = CatchReturnInst::Create(CatchPad, BB);
5434 return false;
5435}
5436
5437/// ParseCatchSwitch
5438/// ::= 'catchswitch' within Parent
5439bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5440 Value *ParentPad;
5441 LocTy BBLoc;
5442
5443 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5444 return true;
5445
5446 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5447 Lex.getKind() != lltok::LocalVarID)
5448 return TokError("expected scope value for catchswitch");
5449
5450 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5451 return true;
5452
5453 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5454 return true;
5455
5456 SmallVector<BasicBlock *, 32> Table;
5457 do {
5458 BasicBlock *DestBB;
5459 if (ParseTypeAndBasicBlock(DestBB, PFS))
5460 return true;
5461 Table.push_back(DestBB);
5462 } while (EatIfPresent(lltok::comma));
5463
5464 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5465 return true;
5466
5467 if (ParseToken(lltok::kw_unwind,
5468 "expected 'unwind' after catchswitch scope"))
5469 return true;
5470
5471 BasicBlock *UnwindBB = nullptr;
5472 if (EatIfPresent(lltok::kw_to)) {
5473 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5474 return true;
5475 } else {
5476 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5477 return true;
5478 }
5479
5480 auto *CatchSwitch =
5481 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5482 for (BasicBlock *DestBB : Table)
5483 CatchSwitch->addHandler(DestBB);
5484 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005485 return false;
5486}
5487
5488/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005489/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005490bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005491 Value *CatchSwitch = nullptr;
5492
5493 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5494 return true;
5495
5496 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5497 return TokError("expected scope value for catchpad");
5498
5499 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5500 return true;
5501
David Majnemer654e1302015-07-31 17:58:14 +00005502 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005503 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005504 return true;
5505
David Majnemer8a1c45d2015-12-12 05:38:55 +00005506 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005507 return false;
5508}
5509
David Majnemer654e1302015-07-31 17:58:14 +00005510/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005511/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005512bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005513 Value *ParentPad = nullptr;
5514
5515 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5516 return true;
5517
5518 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5519 Lex.getKind() != lltok::LocalVarID)
5520 return TokError("expected scope value for cleanuppad");
5521
5522 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5523 return true;
5524
David Majnemer654e1302015-07-31 17:58:14 +00005525 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005526 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005527 return true;
5528
David Majnemer8a1c45d2015-12-12 05:38:55 +00005529 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005530 return false;
5531}
5532
Chris Lattnerac161bf2009-01-02 07:01:27 +00005533//===----------------------------------------------------------------------===//
5534// Binary Operators.
5535//===----------------------------------------------------------------------===//
5536
5537/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005538/// ::= ArithmeticOps TypeAndValue ',' Value
5539///
5540/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5541/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005542bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005543 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005544 LocTy Loc; Value *LHS, *RHS;
5545 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5546 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5547 ParseValue(LHS->getType(), RHS, PFS))
5548 return true;
5549
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005550 bool Valid;
5551 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005552 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005553 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005554 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5555 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005556 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005557 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5558 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005559 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005560
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005561 if (!Valid)
5562 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005563
Chris Lattnerac161bf2009-01-02 07:01:27 +00005564 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5565 return false;
5566}
5567
5568/// ParseLogical
5569/// ::= ArithmeticOps TypeAndValue ',' Value {
5570bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5571 unsigned Opc) {
5572 LocTy Loc; Value *LHS, *RHS;
5573 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5574 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5575 ParseValue(LHS->getType(), RHS, PFS))
5576 return true;
5577
Duncan Sands9dff9be2010-02-15 16:12:20 +00005578 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005579 return Error(Loc,"instruction requires integer or integer vector operands");
5580
5581 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5582 return false;
5583}
5584
5585
5586/// ParseCompare
5587/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5588/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005589bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5590 unsigned Opc) {
5591 // Parse the integer/fp comparison predicate.
5592 LocTy Loc;
5593 unsigned Pred;
5594 Value *LHS, *RHS;
5595 if (ParseCmpPredicate(Pred, Opc) ||
5596 ParseTypeAndValue(LHS, Loc, PFS) ||
5597 ParseToken(lltok::comma, "expected ',' after compare value") ||
5598 ParseValue(LHS->getType(), RHS, PFS))
5599 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005600
Chris Lattnerac161bf2009-01-02 07:01:27 +00005601 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005602 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005603 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005604 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005605 } else {
5606 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005607 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005608 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005610 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005611 }
5612 return false;
5613}
5614
5615//===----------------------------------------------------------------------===//
5616// Other Instructions.
5617//===----------------------------------------------------------------------===//
5618
5619
5620/// ParseCast
5621/// ::= CastOpc TypeAndValue 'to' Type
5622bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5623 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005624 LocTy Loc;
5625 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005626 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005627 if (ParseTypeAndValue(Op, Loc, PFS) ||
5628 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5629 ParseType(DestTy))
5630 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005631
Chris Lattner89d856e2009-03-01 00:53:13 +00005632 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5633 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005634 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005635 getTypeString(Op->getType()) + "' to '" +
5636 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005637 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005638 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5639 return false;
5640}
5641
5642/// ParseSelect
5643/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5644bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5645 LocTy Loc;
5646 Value *Op0, *Op1, *Op2;
5647 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5648 ParseToken(lltok::comma, "expected ',' after select condition") ||
5649 ParseTypeAndValue(Op1, PFS) ||
5650 ParseToken(lltok::comma, "expected ',' after select value") ||
5651 ParseTypeAndValue(Op2, PFS))
5652 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005653
Chris Lattnerac161bf2009-01-02 07:01:27 +00005654 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5655 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005656
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657 Inst = SelectInst::Create(Op0, Op1, Op2);
5658 return false;
5659}
5660
Chris Lattnerb55ab542009-01-05 08:18:44 +00005661/// ParseVA_Arg
5662/// ::= 'va_arg' TypeAndValue ',' Type
5663bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005665 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005666 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667 if (ParseTypeAndValue(Op, PFS) ||
5668 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005669 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005670 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005671
Chris Lattnerb55ab542009-01-05 08:18:44 +00005672 if (!EltTy->isFirstClassType())
5673 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674
5675 Inst = new VAArgInst(Op, EltTy);
5676 return false;
5677}
5678
5679/// ParseExtractElement
5680/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5681bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5682 LocTy Loc;
5683 Value *Op0, *Op1;
5684 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5685 ParseToken(lltok::comma, "expected ',' after extract value") ||
5686 ParseTypeAndValue(Op1, PFS))
5687 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005688
Chris Lattnerac161bf2009-01-02 07:01:27 +00005689 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5690 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005691
Eric Christopherc9742252009-07-25 02:28:41 +00005692 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 return false;
5694}
5695
5696/// ParseInsertElement
5697/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5698bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5699 LocTy Loc;
5700 Value *Op0, *Op1, *Op2;
5701 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5702 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5703 ParseTypeAndValue(Op1, PFS) ||
5704 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5705 ParseTypeAndValue(Op2, PFS))
5706 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005707
Chris Lattnerac161bf2009-01-02 07:01:27 +00005708 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005709 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005710
Chris Lattnerac161bf2009-01-02 07:01:27 +00005711 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5712 return false;
5713}
5714
5715/// ParseShuffleVector
5716/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5717bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5718 LocTy Loc;
5719 Value *Op0, *Op1, *Op2;
5720 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5721 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5722 ParseTypeAndValue(Op1, PFS) ||
5723 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5724 ParseTypeAndValue(Op2, PFS))
5725 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005726
Chris Lattnerac161bf2009-01-02 07:01:27 +00005727 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005728 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005729
Chris Lattnerac161bf2009-01-02 07:01:27 +00005730 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5731 return false;
5732}
5733
5734/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005735/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005736int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005737 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005738 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005739
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005740 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5742 ParseValue(Ty, Op0, PFS) ||
5743 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005744 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5746 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005747
Chris Lattnerf4f03422009-12-30 05:27:33 +00005748 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5750 while (1) {
5751 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005752
Chris Lattner3822f632009-01-02 08:05:26 +00005753 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005754 break;
5755
Chris Lattnerf4f03422009-12-30 05:27:33 +00005756 if (Lex.getKind() == lltok::MetadataVar) {
5757 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005758 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005759 }
Devang Patel8f842d32009-10-16 18:45:49 +00005760
Chris Lattner3822f632009-01-02 08:05:26 +00005761 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005762 ParseValue(Ty, Op0, PFS) ||
5763 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005764 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005765 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5766 return true;
5767 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005768
Chris Lattnerac161bf2009-01-02 07:01:27 +00005769 if (!Ty->isFirstClassType())
5770 return Error(TypeLoc, "phi node must have first class type");
5771
Jay Foad52131342011-03-30 11:28:46 +00005772 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005773 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5774 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5775 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005776 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005777}
5778
Bill Wendlingfae14752011-08-12 20:24:12 +00005779/// ParseLandingPad
5780/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5781/// Clause
5782/// ::= 'catch' TypeAndValue
5783/// ::= 'filter'
5784/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5785bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005786 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005787
David Majnemer7fddecc2015-06-17 20:52:32 +00005788 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005789 return true;
5790
David Majnemer7fddecc2015-06-17 20:52:32 +00005791 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005792 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5793
5794 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5795 LandingPadInst::ClauseType CT;
5796 if (EatIfPresent(lltok::kw_catch))
5797 CT = LandingPadInst::Catch;
5798 else if (EatIfPresent(lltok::kw_filter))
5799 CT = LandingPadInst::Filter;
5800 else
5801 return TokError("expected 'catch' or 'filter' clause type");
5802
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005803 Value *V;
5804 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005805 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005806 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005807
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005808 // A 'catch' type expects a non-array constant. A filter clause expects an
5809 // array constant.
5810 if (CT == LandingPadInst::Catch) {
5811 if (isa<ArrayType>(V->getType()))
5812 Error(VLoc, "'catch' clause has an invalid type");
5813 } else {
5814 if (!isa<ArrayType>(V->getType()))
5815 Error(VLoc, "'filter' clause has an invalid type");
5816 }
5817
Owen Andersonf8f259d2015-03-09 07:13:42 +00005818 Constant *CV = dyn_cast<Constant>(V);
5819 if (!CV)
5820 return Error(VLoc, "clause argument must be a constant");
5821 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005822 }
5823
Owen Andersonf8f259d2015-03-09 07:13:42 +00005824 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005825 return false;
5826}
5827
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005829/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5830/// OptionalAttrs Type Value ParameterList OptionalAttrs
5831/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5832/// OptionalAttrs Type Value ParameterList OptionalAttrs
5833/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5834/// OptionalAttrs Type Value ParameterList OptionalAttrs
5835/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5836/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005837bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005838 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005839 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005840 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005841 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005842 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005843 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 LocTy RetTypeLoc;
5845 ValID CalleeID;
5846 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005847 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005848 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005849
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005850 if (TCK != CallInst::TCK_None &&
5851 ParseToken(lltok::kw_call,
5852 "expected 'tail call', 'musttail call', or 'notail call'"))
5853 return true;
5854
5855 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5856
5857 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005858 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005860 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5861 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005862 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5863 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005864 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005865
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005866 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5867 return Error(CallLoc, "fast-math-flags specified for call without "
5868 "floating-point scalar or vector return type");
5869
Chris Lattnerac161bf2009-01-02 07:01:27 +00005870 // If RetType is a non-function pointer type, then this is the short syntax
5871 // for the call, which means that RetType is just the return type. Infer the
5872 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005873 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5874 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005875 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005876 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005877 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5878 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005879
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 if (!FunctionType::isValidReturnType(RetType))
5881 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005882
Owen Anderson4056ca92009-07-29 22:17:13 +00005883 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005885
David Blaikie41ba2b42015-07-27 23:32:19 +00005886 CalleeID.FTy = Ty;
5887
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888 // Look up the callee.
5889 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005890 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5891 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005892
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005893 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005894 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005895 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005896 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5897 AttributeSet::ReturnIndex,
5898 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005899
Chris Lattnerac161bf2009-01-02 07:01:27 +00005900 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005901
Chris Lattnerac161bf2009-01-02 07:01:27 +00005902 // Loop through FunctionType's arguments and ensure they are specified
5903 // correctly. Also, gather any parameter attributes.
5904 FunctionType::param_iterator I = Ty->param_begin();
5905 FunctionType::param_iterator E = Ty->param_end();
5906 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005907 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005908 if (I != E) {
5909 ExpectedTy = *I++;
5910 } else if (!Ty->isVarArg()) {
5911 return Error(ArgList[i].Loc, "too many arguments specified");
5912 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005913
Chris Lattnerac161bf2009-01-02 07:01:27 +00005914 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5915 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005916 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005917 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005918 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5919 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005920 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5921 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005922 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005923
Chris Lattnerac161bf2009-01-02 07:01:27 +00005924 if (I != E)
5925 return Error(CallLoc, "not enough parameters specified for call");
5926
David Majnemer8d22abd2015-02-23 00:01:32 +00005927 if (FnAttrs.hasAttributes()) {
5928 if (FnAttrs.hasAlignmentAttr())
5929 return Error(CallLoc, "call instructions may not have an alignment");
5930
Bill Wendlingf5075a42013-01-27 02:24:02 +00005931 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5932 AttributeSet::FunctionIndex,
5933 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005934 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005935
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005936 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005937 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005938
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005939 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005940 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005941 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005942 if (FMF.any())
5943 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005944 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005945 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005946 Inst = CI;
5947 return false;
5948}
5949
5950//===----------------------------------------------------------------------===//
5951// Memory Instructions.
5952//===----------------------------------------------------------------------===//
5953
5954/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005955/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5956/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005957int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005958 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005959 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005960 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005961 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005962
5963 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005964 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005965
David Majnemera3b0eb22015-02-16 08:38:03 +00005966 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005967
David Majnemera3b0eb22015-02-16 08:38:03 +00005968 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5969 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005970
Chris Lattnerb2f39502009-12-30 05:44:30 +00005971 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005972 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005973 if (Lex.getKind() == lltok::kw_align) {
5974 if (ParseOptionalAlignment(Alignment)) return true;
5975 } else if (Lex.getKind() == lltok::MetadataVar) {
5976 AteExtraComma = true;
5977 } else {
5978 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5979 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5980 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005981 }
5982 }
5983
Dan Gohman2140a742010-05-28 01:14:11 +00005984 if (Size && !Size->getType()->isIntegerTy())
5985 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005986
Reid Kleckner436c42e2014-01-17 23:58:17 +00005987 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5988 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005989 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005990 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005991 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992}
5993
5994/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005995/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005996/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005997/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005998int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005999 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006000 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006001 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006002 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006003 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006004 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006005
6006 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006007 isAtomic = true;
6008 Lex.Lex();
6009 }
6010
Chris Lattnerbc639292011-11-27 06:56:53 +00006011 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006012 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006013 isVolatile = true;
6014 Lex.Lex();
6015 }
6016
David Blaikie15d9a4c2015-04-06 20:59:48 +00006017 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006018 LocTy ExplicitTypeLoc = Lex.getLoc();
6019 if (ParseType(Ty) ||
6020 ParseToken(lltok::comma, "expected comma after load's type") ||
6021 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006022 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006023 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6024 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006025
David Blaikie15d9a4c2015-04-06 20:59:48 +00006026 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006027 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006028 if (isAtomic && !Alignment)
6029 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006030 if (Ordering == AtomicOrdering::Release ||
6031 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006032 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006033
David Blaikiea79ac142015-02-27 21:17:42 +00006034 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6035 return Error(ExplicitTypeLoc,
6036 "explicit pointee type doesn't match operand's pointee type");
6037
David Blaikie15d9a4c2015-04-06 20:59:48 +00006038 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006039 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006040}
6041
6042/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006043
6044/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6045/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006046/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006047int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006048 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006049 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006050 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006051 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006052 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006053 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006054
6055 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006056 isAtomic = true;
6057 Lex.Lex();
6058 }
6059
Chris Lattnerbc639292011-11-27 06:56:53 +00006060 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006061 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006062 isVolatile = true;
6063 Lex.Lex();
6064 }
6065
Chris Lattnerac161bf2009-01-02 07:01:27 +00006066 if (ParseTypeAndValue(Val, Loc, PFS) ||
6067 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006068 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006069 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006070 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006071 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006072
Duncan Sands19d0b472010-02-16 11:11:14 +00006073 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006074 return Error(PtrLoc, "store operand must be a pointer");
6075 if (!Val->getType()->isFirstClassType())
6076 return Error(Loc, "store operand must be a first class value");
6077 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6078 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006079 if (isAtomic && !Alignment)
6080 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006081 if (Ordering == AtomicOrdering::Acquire ||
6082 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006083 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006084
Eli Friedman59b66882011-08-09 23:02:53 +00006085 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006086 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006087}
6088
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006089/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006090/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6091/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006092int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006093 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6094 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006095 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6096 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006097 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006098 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006099 bool isWeak = false;
6100
6101 if (EatIfPresent(lltok::kw_weak))
6102 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006103
6104 if (EatIfPresent(lltok::kw_volatile))
6105 isVolatile = true;
6106
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006107 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6108 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6109 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6110 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6111 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006112 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6113 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006114 return true;
6115
JF Bastien800f87a2016-04-06 21:19:33 +00006116 if (SuccessOrdering == AtomicOrdering::Unordered ||
6117 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006118 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006119 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6120 return TokError("cmpxchg failure argument shall be no stronger than the "
6121 "success argument");
6122 if (FailureOrdering == AtomicOrdering::Release ||
6123 FailureOrdering == AtomicOrdering::AcquireRelease)
6124 return TokError(
6125 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006126 if (!Ptr->getType()->isPointerTy())
6127 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6128 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6129 return Error(CmpLoc, "compare value and pointer type do not match");
6130 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6131 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006132 if (!New->getType()->isFirstClassType())
6133 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006134 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6135 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006136 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006137 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006138 Inst = CXI;
6139 return AteExtraComma ? InstExtraComma : InstNormal;
6140}
6141
6142/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006143/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6144/// 'singlethread'? AtomicOrdering
6145int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006146 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6147 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006148 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006149 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006150 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006151 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006152
6153 if (EatIfPresent(lltok::kw_volatile))
6154 isVolatile = true;
6155
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006156 switch (Lex.getKind()) {
6157 default: return TokError("expected binary operation in atomicrmw");
6158 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6159 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6160 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6161 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6162 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6163 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6164 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6165 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6166 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6167 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6168 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6169 }
6170 Lex.Lex(); // Eat the operation.
6171
6172 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6173 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6174 ParseTypeAndValue(Val, ValLoc, PFS) ||
6175 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6176 return true;
6177
JF Bastien800f87a2016-04-06 21:19:33 +00006178 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006179 return TokError("atomicrmw cannot be unordered");
6180 if (!Ptr->getType()->isPointerTy())
6181 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6182 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6183 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6184 if (!Val->getType()->isIntegerTy())
6185 return Error(ValLoc, "atomicrmw operand must be an integer");
6186 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6187 if (Size < 8 || (Size & (Size - 1)))
6188 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6189 " integer");
6190
6191 AtomicRMWInst *RMWI =
6192 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6193 RMWI->setVolatile(isVolatile);
6194 Inst = RMWI;
6195 return AteExtraComma ? InstExtraComma : InstNormal;
6196}
6197
Eli Friedmanfee02c62011-07-25 23:16:38 +00006198/// ParseFence
6199/// ::= 'fence' 'singlethread'? AtomicOrdering
6200int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006201 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006202 SynchronizationScope Scope = CrossThread;
6203 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6204 return true;
6205
JF Bastien800f87a2016-04-06 21:19:33 +00006206 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006207 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006208 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006209 return TokError("fence cannot be monotonic");
6210
6211 Inst = new FenceInst(Context, Ordering, Scope);
6212 return InstNormal;
6213}
6214
Chris Lattnerac161bf2009-01-02 07:01:27 +00006215/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006216/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006217int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006218 Value *Ptr = nullptr;
6219 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006220 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006221
Dan Gohman16cbbe42009-07-29 15:58:36 +00006222 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006223
David Blaikie79e6c742015-02-27 19:29:02 +00006224 Type *Ty = nullptr;
6225 LocTy ExplicitTypeLoc = Lex.getLoc();
6226 if (ParseType(Ty) ||
6227 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6228 ParseTypeAndValue(Ptr, Loc, PFS))
6229 return true;
6230
Eli Benderskyd9806682013-04-22 17:03:42 +00006231 Type *BaseType = Ptr->getType();
6232 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6233 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006234 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006235
David Blaikie8d757942015-03-09 23:08:44 +00006236 if (Ty != BasePointerType->getElementType())
6237 return Error(ExplicitTypeLoc,
6238 "explicit pointee type doesn't match operand's pointee type");
6239
Chris Lattnerac161bf2009-01-02 07:01:27 +00006240 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006241 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006242 // GEP returns a vector of pointers if at least one of parameters is a vector.
6243 // All vector parameters should have the same vector width.
6244 unsigned GEPWidth = BaseType->isVectorTy() ?
6245 BaseType->getVectorNumElements() : 0;
6246
Chris Lattner3822f632009-01-02 08:05:26 +00006247 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006248 if (Lex.getKind() == lltok::MetadataVar) {
6249 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006250 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006251 }
Chris Lattner3822f632009-01-02 08:05:26 +00006252 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006253 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006254 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006255
Nadav Rotem3924cb02011-12-05 06:29:09 +00006256 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006257 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6258 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006259 return Error(EltLoc,
6260 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006261 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006262 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006263 Indices.push_back(Val);
6264 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006265
Craig Toppere3dcce92015-08-01 22:20:21 +00006266 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006267 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006268 return Error(Loc, "base element of getelementptr must be sized");
6269
David Blaikied33bad32015-04-17 22:32:13 +00006270 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006271 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006272 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006273 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006274 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006275 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006276}
6277
6278/// ParseExtractValue
6279/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006280int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006281 Value *Val; LocTy Loc;
6282 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006283 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006284 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006285 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006286 return true;
6287
Chris Lattner392be582010-02-12 20:49:41 +00006288 if (!Val->getType()->isAggregateType())
6289 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006290
Jay Foad57aa6362011-07-13 10:26:04 +00006291 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006292 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006293 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006294 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006295}
6296
6297/// ParseInsertValue
6298/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006299int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006300 Value *Val0, *Val1; LocTy Loc0, Loc1;
6301 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006302 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006303 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6304 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6305 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006306 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006307 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006308
Chris Lattner392be582010-02-12 20:49:41 +00006309 if (!Val0->getType()->isAggregateType())
6310 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006311
David Majnemer30074532015-02-11 07:43:58 +00006312 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6313 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006314 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006315 if (IndexedType != Val1->getType())
6316 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6317 getTypeString(Val1->getType()) + "' instead of '" +
6318 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006319 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006320 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006321}
Nick Lewycky49f89192009-04-04 07:22:01 +00006322
6323//===----------------------------------------------------------------------===//
6324// Embedded metadata.
6325//===----------------------------------------------------------------------===//
6326
6327/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006328/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006329/// Element
6330/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006331bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006332 if (ParseToken(lltok::lbrace, "expected '{' here"))
6333 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006334
Dan Gohman1e0213a2010-07-13 19:33:27 +00006335 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006336 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006337 return false;
6338
Nick Lewycky49f89192009-04-04 07:22:01 +00006339 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006340 // Null is a special case since it is typeless.
6341 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006342 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006343 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006344 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006345
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006346 Metadata *MD;
6347 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006348 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006349 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006350 } while (EatIfPresent(lltok::comma));
6351
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006352 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006353}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006354
6355//===----------------------------------------------------------------------===//
6356// Use-list order directives.
6357//===----------------------------------------------------------------------===//
6358bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6359 SMLoc Loc) {
6360 if (V->use_empty())
6361 return Error(Loc, "value has no uses");
6362
6363 unsigned NumUses = 0;
6364 SmallDenseMap<const Use *, unsigned, 16> Order;
6365 for (const Use &U : V->uses()) {
6366 if (++NumUses > Indexes.size())
6367 break;
6368 Order[&U] = Indexes[NumUses - 1];
6369 }
6370 if (NumUses < 2)
6371 return Error(Loc, "value only has one use");
6372 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6373 return Error(Loc, "wrong number of indexes, expected " +
6374 Twine(std::distance(V->use_begin(), V->use_end())));
6375
6376 V->sortUseList([&](const Use &L, const Use &R) {
6377 return Order.lookup(&L) < Order.lookup(&R);
6378 });
6379 return false;
6380}
6381
6382/// ParseUseListOrderIndexes
6383/// ::= '{' uint32 (',' uint32)+ '}'
6384bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6385 SMLoc Loc = Lex.getLoc();
6386 if (ParseToken(lltok::lbrace, "expected '{' here"))
6387 return true;
6388 if (Lex.getKind() == lltok::rbrace)
6389 return Lex.Error("expected non-empty list of uselistorder indexes");
6390
6391 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6392 // indexes should be distinct numbers in the range [0, size-1], and should
6393 // not be in order.
6394 unsigned Offset = 0;
6395 unsigned Max = 0;
6396 bool IsOrdered = true;
6397 assert(Indexes.empty() && "Expected empty order vector");
6398 do {
6399 unsigned Index;
6400 if (ParseUInt32(Index))
6401 return true;
6402
6403 // Update consistency checks.
6404 Offset += Index - Indexes.size();
6405 Max = std::max(Max, Index);
6406 IsOrdered &= Index == Indexes.size();
6407
6408 Indexes.push_back(Index);
6409 } while (EatIfPresent(lltok::comma));
6410
6411 if (ParseToken(lltok::rbrace, "expected '}' here"))
6412 return true;
6413
6414 if (Indexes.size() < 2)
6415 return Error(Loc, "expected >= 2 uselistorder indexes");
6416 if (Offset != 0 || Max >= Indexes.size())
6417 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6418 if (IsOrdered)
6419 return Error(Loc, "expected uselistorder indexes to change the order");
6420
6421 return false;
6422}
6423
6424/// ParseUseListOrder
6425/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6426bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6427 SMLoc Loc = Lex.getLoc();
6428 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6429 return true;
6430
6431 Value *V;
6432 SmallVector<unsigned, 16> Indexes;
6433 if (ParseTypeAndValue(V, PFS) ||
6434 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6435 ParseUseListOrderIndexes(Indexes))
6436 return true;
6437
6438 return sortUseListOrder(V, Indexes, Loc);
6439}
6440
6441/// ParseUseListOrderBB
6442/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6443bool LLParser::ParseUseListOrderBB() {
6444 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6445 SMLoc Loc = Lex.getLoc();
6446 Lex.Lex();
6447
6448 ValID Fn, Label;
6449 SmallVector<unsigned, 16> Indexes;
6450 if (ParseValID(Fn) ||
6451 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6452 ParseValID(Label) ||
6453 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6454 ParseUseListOrderIndexes(Indexes))
6455 return true;
6456
6457 // Check the function.
6458 GlobalValue *GV;
6459 if (Fn.Kind == ValID::t_GlobalName)
6460 GV = M->getNamedValue(Fn.StrVal);
6461 else if (Fn.Kind == ValID::t_GlobalID)
6462 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6463 else
6464 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6465 if (!GV)
6466 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6467 auto *F = dyn_cast<Function>(GV);
6468 if (!F)
6469 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6470 if (F->isDeclaration())
6471 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6472
6473 // Check the basic block.
6474 if (Label.Kind == ValID::t_LocalID)
6475 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6476 if (Label.Kind != ValID::t_LocalName)
6477 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6478 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6479 if (!V)
6480 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6481 if (!isa<BasicBlock>(V))
6482 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6483
6484 return sortUseListOrder(V, Indexes, Loc);
6485}