blob: 5120b949e842fec57a011ac3b5d03c299b0d98b0 [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"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000019#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000044#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
124 for (std::map<Value*, std::vector<unsigned> >::iterator
125 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
126 I != E; ++I) {
127 Value *V = I->first;
128 std::vector<unsigned> &Vec = I->second;
129 AttrBuilder B;
130
131 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
132 VI != VE; ++VI)
133 B.merge(NumberedAttrBuilders[*VI]);
134
135 if (Function *Fn = dyn_cast<Function>(V)) {
136 AttributeSet AS = Fn->getAttributes();
137 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
138 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
139 AS.getFnAttributes());
140
141 FnAttrs.merge(B);
142
143 // If the alignment was parsed as an attribute, move to the alignment
144 // field.
145 if (FnAttrs.hasAlignmentAttr()) {
146 Fn->setAlignment(FnAttrs.getAlignment());
147 FnAttrs.removeAttribute(Attribute::Alignment);
148 }
149
150 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
151 AttributeSet::get(Context,
152 AttributeSet::FunctionIndex,
153 FnAttrs));
154 Fn->setAttributes(AS);
155 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
156 AttributeSet AS = CI->getAttributes();
157 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
158 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
159 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000160 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000161 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
162 AttributeSet::get(Context,
163 AttributeSet::FunctionIndex,
164 FnAttrs));
165 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeSet AS = II->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
169 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
170 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000171 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000172 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
173 AttributeSet::get(Context,
174 AttributeSet::FunctionIndex,
175 FnAttrs));
176 II->setAttributes(AS);
177 } else {
178 llvm_unreachable("invalid object with forward attribute group reference");
179 }
180 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000181
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000182 // If there are entries in ForwardRefBlockAddresses at this point, the
183 // function was never defined.
184 if (!ForwardRefBlockAddresses.empty())
185 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
186 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000187
David Majnemer19b51052015-02-11 07:43:56 +0000188 for (const auto &NT : NumberedTypes)
189 if (NT.second.second.isValid())
190 return Error(NT.second.second,
191 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000192
193 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
194 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
195 if (I->second.second.isValid())
196 return Error(I->second.second,
197 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000198
David Majnemerdad0a642014-06-27 18:19:56 +0000199 if (!ForwardRefComdats.empty())
200 return Error(ForwardRefComdats.begin()->second,
201 "use of undefined comdat '$" +
202 ForwardRefComdats.begin()->first + "'");
203
Chris Lattnerac161bf2009-01-02 07:01:27 +0000204 if (!ForwardRefVals.empty())
205 return Error(ForwardRefVals.begin()->second.second,
206 "use of undefined value '@" + ForwardRefVals.begin()->first +
207 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000208
Chris Lattnerac161bf2009-01-02 07:01:27 +0000209 if (!ForwardRefValIDs.empty())
210 return Error(ForwardRefValIDs.begin()->second.second,
211 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000212 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000213
Devang Pateld2541152009-07-08 19:23:54 +0000214 if (!ForwardRefMDNodes.empty())
215 return Error(ForwardRefMDNodes.begin()->second.second,
216 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000217 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000218
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000219 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000220 for (auto &N : NumberedMetadata) {
221 if (N.second && !N.second->isResolved())
222 N.second->resolveCycles();
223 }
Devang Pateld2541152009-07-08 19:23:54 +0000224
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000225 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
226 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
227
Chris Lattnerac161bf2009-01-02 07:01:27 +0000228 // Look for intrinsic functions and CallInst that need to be upgraded
229 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000230 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000231
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000232 // Some types could be renamed during loading if several modules are
233 // loaded in the same LLVMContext (LTO scenario). In this case we should
234 // remangle intrinsics names as well.
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
236 Function *F = &*FI++;
237 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
238 F->replaceAllUsesWith(Remangled.getValue());
239 F->eraseFromParent();
240 }
241 }
242
Manman Ren8b4306c2013-12-02 21:29:56 +0000243 UpgradeDebugInfo(*M);
244
Manman Renb5d7ff42016-05-25 23:14:48 +0000245 UpgradeModuleFlags(*M);
246
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000247 if (!Slots)
248 return false;
249 // Initialize the slot mapping.
250 // Because by this point we've parsed and validated everything, we can "steal"
251 // the mapping from LLParser as it doesn't need it anymore.
252 Slots->GlobalValues = std::move(NumberedVals);
253 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000254 for (const auto &I : NamedTypes)
255 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
256 for (const auto &I : NumberedTypes)
257 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000258
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 return false;
260}
261
262//===----------------------------------------------------------------------===//
263// Top-Level Entities
264//===----------------------------------------------------------------------===//
265
266bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000267 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 switch (Lex.getKind()) {
269 default: return TokError("expected top-level entity");
270 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000271 case lltok::kw_declare: if (ParseDeclare()) return true; break;
272 case lltok::kw_define: if (ParseDefine()) return true; break;
273 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
274 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000275 case lltok::kw_source_filename:
276 if (ParseSourceFileName())
277 return true;
278 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000279 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000280 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000281 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000282 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000283 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000284 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000285 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000286 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000287 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000288 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
289 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000290 if (ParseUseListOrderBB())
291 return true;
292 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000293 }
294 }
295}
296
Chris Lattnerac161bf2009-01-02 07:01:27 +0000297/// toplevelentity
298/// ::= 'module' 'asm' STRINGCONSTANT
299bool LLParser::ParseModuleAsm() {
300 assert(Lex.getKind() == lltok::kw_module);
301 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000302
303 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000304 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
305 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000306
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000307 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000308 return false;
309}
310
311/// toplevelentity
312/// ::= 'target' 'triple' '=' STRINGCONSTANT
313/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
314bool LLParser::ParseTargetDefinition() {
315 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000316 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000317 switch (Lex.Lex()) {
318 default: return TokError("unknown target property");
319 case lltok::kw_triple:
320 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000321 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
322 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000324 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return false;
326 case lltok::kw_datalayout:
327 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000328 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
329 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000330 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000331 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 return false;
333 }
334}
335
Bill Wendling706d3d62012-11-28 08:41:48 +0000336/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000337/// ::= 'source_filename' '=' STRINGCONSTANT
338bool LLParser::ParseSourceFileName() {
339 assert(Lex.getKind() == lltok::kw_source_filename);
340 std::string Str;
341 Lex.Lex();
342 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
343 ParseStringConstant(Str))
344 return true;
345 M->setSourceFileName(Str);
346 return false;
347}
348
349/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000350/// ::= 'deplibs' '=' '[' ']'
351/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
352/// FIXME: Remove in 4.0. Currently parse, but ignore.
353bool LLParser::ParseDepLibs() {
354 assert(Lex.getKind() == lltok::kw_deplibs);
355 Lex.Lex();
356 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
357 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
358 return true;
359
360 if (EatIfPresent(lltok::rsquare))
361 return false;
362
363 do {
364 std::string Str;
365 if (ParseStringConstant(Str)) return true;
366 } while (EatIfPresent(lltok::comma));
367
368 return ParseToken(lltok::rsquare, "expected ']' at end of list");
369}
370
Dan Gohman466876b2009-08-12 23:32:33 +0000371/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000372/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000373bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000374 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000375 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000376 Lex.Lex(); // eat LocalVarID;
377
378 if (ParseToken(lltok::equal, "expected '=' after name") ||
379 ParseToken(lltok::kw_type, "expected 'type' after '='"))
380 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381
Craig Topper2617dcc2014-04-15 06:32:26 +0000382 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383 if (ParseStructDefinition(TypeLoc, "",
384 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000385
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000386 if (!isa<StructType>(Result)) {
387 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
388 if (Entry.first)
389 return Error(TypeLoc, "non-struct types may not be recursive");
390 Entry.first = Result;
391 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000392 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000393
Chris Lattnerac161bf2009-01-02 07:01:27 +0000394 return false;
395}
396
397/// toplevelentity
398/// ::= LocalVar '=' 'type' type
399bool LLParser::ParseNamedType() {
400 std::string Name = Lex.getStrVal();
401 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000402 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000403
Chris Lattner3822f632009-01-02 08:05:26 +0000404 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000405 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000406 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000407
Craig Topper2617dcc2014-04-15 06:32:26 +0000408 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 if (ParseStructDefinition(NameLoc, Name,
410 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000411
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000412 if (!isa<StructType>(Result)) {
413 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
414 if (Entry.first)
415 return Error(NameLoc, "non-struct types may not be recursive");
416 Entry.first = Result;
417 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000418 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000420 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000421}
422
Chris Lattnerac161bf2009-01-02 07:01:27 +0000423/// toplevelentity
424/// ::= 'declare' FunctionHeader
425bool LLParser::ParseDeclare() {
426 assert(Lex.getKind() == lltok::kw_declare);
427 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000428
Peter Collingbourne21521892016-06-21 23:42:48 +0000429 std::vector<std::pair<unsigned, MDNode *>> MDs;
430 while (Lex.getKind() == lltok::MetadataVar) {
431 unsigned MDK;
432 MDNode *N;
433 if (ParseMetadataAttachment(MDK, N))
434 return true;
435 MDs.push_back({MDK, N});
436 }
437
Chris Lattnerac161bf2009-01-02 07:01:27 +0000438 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000439 if (ParseFunctionHeader(F, false))
440 return true;
441 for (auto &MD : MDs)
442 F->addMetadata(MD.first, *MD.second);
443 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444}
445
446/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000447/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448bool LLParser::ParseDefine() {
449 assert(Lex.getKind() == lltok::kw_define);
450 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000453 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000454 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000455 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000456}
457
Chris Lattner3822f632009-01-02 08:05:26 +0000458/// ParseGlobalType
459/// ::= 'constant'
460/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000461bool LLParser::ParseGlobalType(bool &IsConstant) {
462 if (Lex.getKind() == lltok::kw_constant)
463 IsConstant = true;
464 else if (Lex.getKind() == lltok::kw_global)
465 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000466 else {
467 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000468 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000469 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470 Lex.Lex();
471 return false;
472}
473
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000474bool LLParser::ParseOptionalUnnamedAddr(
475 GlobalVariable::UnnamedAddr &UnnamedAddr) {
476 if (EatIfPresent(lltok::kw_unnamed_addr))
477 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
478 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
479 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
480 else
481 UnnamedAddr = GlobalValue::UnnamedAddr::None;
482 return false;
483}
484
Dan Gohman466876b2009-08-12 23:32:33 +0000485/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000486/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000487/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
488/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000489/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000490/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
491/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000492bool LLParser::ParseUnnamedGlobal() {
493 unsigned VarID = NumberedVals.size();
494 std::string Name;
495 LocTy NameLoc = Lex.getLoc();
496
497 // Handle the GlobalID form.
498 if (Lex.getKind() == lltok::GlobalID) {
499 if (Lex.getUIntVal() != VarID)
500 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000501 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000502 Lex.Lex(); // eat GlobalID;
503
504 if (ParseToken(lltok::equal, "expected '=' after name"))
505 return true;
506 }
507
508 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000509 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000510 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000511 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000512 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000513 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000514 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000515
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000516 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000517 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000518 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000519
520 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
521 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000522}
523
Chris Lattnerac161bf2009-01-02 07:01:27 +0000524/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000525/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000526/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
527/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000528bool LLParser::ParseNamedGlobal() {
529 assert(Lex.getKind() == lltok::GlobalVar);
530 LocTy NameLoc = Lex.getLoc();
531 std::string Name = Lex.getStrVal();
532 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000533
Chris Lattnerac161bf2009-01-02 07:01:27 +0000534 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000535 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000536 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000537 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000538 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000539 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000540 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000541 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000542
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000543 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000544 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000545 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000546
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000547 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
548 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000549}
550
David Majnemerdad0a642014-06-27 18:19:56 +0000551bool LLParser::parseComdat() {
552 assert(Lex.getKind() == lltok::ComdatVar);
553 std::string Name = Lex.getStrVal();
554 LocTy NameLoc = Lex.getLoc();
555 Lex.Lex();
556
557 if (ParseToken(lltok::equal, "expected '=' here"))
558 return true;
559
560 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
561 return TokError("expected comdat type");
562
563 Comdat::SelectionKind SK;
564 switch (Lex.getKind()) {
565 default:
566 return TokError("unknown selection kind");
567 case lltok::kw_any:
568 SK = Comdat::Any;
569 break;
570 case lltok::kw_exactmatch:
571 SK = Comdat::ExactMatch;
572 break;
573 case lltok::kw_largest:
574 SK = Comdat::Largest;
575 break;
576 case lltok::kw_noduplicates:
577 SK = Comdat::NoDuplicates;
578 break;
579 case lltok::kw_samesize:
580 SK = Comdat::SameSize;
581 break;
582 }
583 Lex.Lex();
584
585 // See if the comdat was forward referenced, if so, use the comdat.
586 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
587 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
588 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
589 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
590
591 Comdat *C;
592 if (I != ComdatSymTab.end())
593 C = &I->second;
594 else
595 C = M->getOrInsertComdat(Name);
596 C->setSelectionKind(SK);
597
598 return false;
599}
600
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000601// MDString:
602// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000603bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000604 std::string Str;
605 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000606 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000607 return false;
608}
609
610// MDNode:
611// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000612bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000613 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000614 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000616 if (ParseUInt32(MID))
617 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000618
Chris Lattner8eff0152010-04-01 05:14:45 +0000619 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000620 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000621 Result = NumberedMetadata[MID];
622 return false;
623 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000624
Chris Lattner8eff0152010-04-01 05:14:45 +0000625 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000626 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000627 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000628
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000629 Result = FwdRef.first.get();
630 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000631 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000632}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000633
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000634/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000635/// !foo = !{ !1, !2 }
636bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000637 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000638 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000639 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000640
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000641 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000642 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000643 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000644 return true;
645
Dan Gohman2637cc12010-07-21 23:38:33 +0000646 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000647 if (Lex.getKind() != lltok::rbrace)
648 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000649 if (ParseToken(lltok::exclaim, "Expected '!' here"))
650 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000651
Craig Topper2617dcc2014-04-15 06:32:26 +0000652 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000653 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000654 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000655 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000656
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000657 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000658}
659
Devang Patel39e64d42009-07-01 19:21:12 +0000660/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000661/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000662bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000663 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000664 Lex.Lex();
665 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000666
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000667 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000668 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000669 ParseToken(lltok::equal, "expected '=' here"))
670 return true;
671
672 // Detect common error, from old metadata syntax.
673 if (Lex.getKind() == lltok::Type)
674 return TokError("unexpected type in metadata definition");
675
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000676 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000677 if (Lex.getKind() == lltok::MetadataVar) {
678 if (ParseSpecializedMDNode(Init, IsDistinct))
679 return true;
680 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
681 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000682 return true;
683
Chris Lattnerfc58af22009-12-30 04:51:58 +0000684 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000685 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000686 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000687 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000688 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000689
Chris Lattnerfc58af22009-12-30 04:51:58 +0000690 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
691 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000692 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000693 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000694 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000695 }
696
Devang Patel39e64d42009-07-01 19:21:12 +0000697 return false;
698}
699
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000700static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
701 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
702 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
703}
704
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000705/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000706/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
707/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000708/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000709///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000710/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000711/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712///
Eric Christopher536f0a92015-05-28 23:07:39 +0000713/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000714///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000715bool LLParser::parseIndirectSymbol(
716 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
717 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
718 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000719 bool IsAlias;
720 if (Lex.getKind() == lltok::kw_alias)
721 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000722 else if (Lex.getKind() == lltok::kw_ifunc)
723 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000724 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000725 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000727
Rafael Espindola78527052013-10-06 15:10:43 +0000728 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
729
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000730 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000731 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000732
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000733 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000734 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000735 "symbol with local linkage must have default visibility");
736
David Blaikie2f408302015-09-11 03:22:04 +0000737 Type *Ty;
738 LocTy ExplicitTypeLoc = Lex.getLoc();
739 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000740 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000741 return true;
742
Rafael Espindola64c1e182014-06-03 02:41:57 +0000743 Constant *Aliasee;
744 LocTy AliaseeLoc = Lex.getLoc();
745 if (Lex.getKind() != lltok::kw_bitcast &&
746 Lex.getKind() != lltok::kw_getelementptr &&
747 Lex.getKind() != lltok::kw_addrspacecast &&
748 Lex.getKind() != lltok::kw_inttoptr) {
749 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000750 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000751 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000752 // The bitcast dest type is not present, it is implied by the dest type.
753 ValID ID;
754 if (ParseValID(ID))
755 return true;
756 if (ID.Kind != ValID::t_Constant)
757 return Error(AliaseeLoc, "invalid aliasee");
758 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000759 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000760
Rafael Espindola64c1e182014-06-03 02:41:57 +0000761 Type *AliaseeType = Aliasee->getType();
762 auto *PTy = dyn_cast<PointerType>(AliaseeType);
763 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000764 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000765 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000766
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000767 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000768 return Error(
769 ExplicitTypeLoc,
770 "explicit pointee type doesn't match operand's pointee type");
771
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000772 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
773 return Error(
774 ExplicitTypeLoc,
775 "explicit pointee type should be a function type");
776
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000777 GlobalValue *GVal = nullptr;
778
779 // See if the alias was forward referenced, if so, prepare to replace the
780 // forward reference.
781 if (!Name.empty()) {
782 GVal = M->getNamedValue(Name);
783 if (GVal) {
784 if (!ForwardRefVals.erase(Name))
785 return Error(NameLoc, "redefinition of global '@" + Name + "'");
786 }
787 } else {
788 auto I = ForwardRefValIDs.find(NumberedVals.size());
789 if (I != ForwardRefValIDs.end()) {
790 GVal = I->second.first;
791 ForwardRefValIDs.erase(I);
792 }
793 }
794
Chris Lattnerac161bf2009-01-02 07:01:27 +0000795 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000796 std::unique_ptr<GlobalIndirectSymbol> GA;
797 if (IsAlias)
798 GA.reset(GlobalAlias::create(Ty, AddrSpace,
799 (GlobalValue::LinkageTypes)Linkage, Name,
800 Aliasee, /*Parent*/ nullptr));
801 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000802 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
803 (GlobalValue::LinkageTypes)Linkage, Name,
804 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000805 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000806 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000807 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000808 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Rafael Espindola54fc2982015-06-17 17:53:31 +0000810 if (Name.empty())
811 NumberedVals.push_back(GA.get());
812
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000813 if (GVal) {
814 // Verify that types agree.
815 if (GVal->getType() != GA->getType())
816 return Error(
817 ExplicitTypeLoc,
818 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000819
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 // If they agree, just RAUW the old value with the alias and remove the
821 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000822 GVal->replaceAllUsesWith(GA.get());
823 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000825
Chris Lattnerac161bf2009-01-02 07:01:27 +0000826 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000827 if (IsAlias)
828 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
829 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000830 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000831 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000832
Rafael Espindolaaa273822014-05-09 21:49:17 +0000833 // The module owns this now
834 GA.release();
835
Chris Lattnerac161bf2009-01-02 07:01:27 +0000836 return false;
837}
838
839/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000840/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000841/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000842/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000843/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000844/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000845/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846///
Eric Christopher536f0a92015-05-28 23:07:39 +0000847/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000848/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000849///
850bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
851 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000852 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000853 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000854 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000855 if (!isValidVisibilityForLinkage(Visibility, Linkage))
856 return Error(NameLoc,
857 "symbol with local linkage must have default visibility");
858
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000860 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000861 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000862 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000863
Craig Topper2617dcc2014-04-15 06:32:26 +0000864 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000865 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000866 ParseOptionalToken(lltok::kw_externally_initialized,
867 IsExternallyInitialized,
868 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000869 ParseGlobalType(IsConstant) ||
870 ParseType(Ty, TyLoc))
871 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000872
Chris Lattnerac161bf2009-01-02 07:01:27 +0000873 // If the linkage is specified and is external, then no initializer is
874 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000875 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000876 if (!HasLinkage ||
877 !GlobalValue::isValidDeclarationLinkage(
878 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000879 if (ParseGlobalValue(Ty, Init))
880 return true;
881 }
882
David Majnemer49b3d9b2015-02-16 08:41:08 +0000883 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000884 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000885
David Majnemer598bd052014-12-09 05:56:09 +0000886 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000887
888 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000889 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000890 GVal = M->getNamedValue(Name);
891 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000892 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000893 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000894 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000895 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000896 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000897 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000898 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 ForwardRefValIDs.erase(I);
900 }
901 }
902
David Majnemer598bd052014-12-09 05:56:09 +0000903 GlobalVariable *GV;
904 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000905 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
906 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000907 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000908 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000909 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000910 return Error(TyLoc,
911 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
David Majnemer598bd052014-12-09 05:56:09 +0000913 GV = cast<GlobalVariable>(GVal);
914
Chris Lattnerac161bf2009-01-02 07:01:27 +0000915 // Move the forward-reference to the correct spot in the module.
916 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
917 }
918
919 if (Name.empty())
920 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000921
Chris Lattnerac161bf2009-01-02 07:01:27 +0000922 // Set the parsed properties on the global.
923 if (Init)
924 GV->setInitializer(Init);
925 GV->setConstant(IsConstant);
926 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
927 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000928 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000929 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000930 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000931 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000932
Chris Lattnerac161bf2009-01-02 07:01:27 +0000933 // Parse attributes on the global.
934 while (Lex.getKind() == lltok::comma) {
935 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000936
Chris Lattnerac161bf2009-01-02 07:01:27 +0000937 if (Lex.getKind() == lltok::kw_section) {
938 Lex.Lex();
939 GV->setSection(Lex.getStrVal());
940 if (ParseToken(lltok::StringConstant, "expected global section string"))
941 return true;
942 } else if (Lex.getKind() == lltok::kw_align) {
943 unsigned Alignment;
944 if (ParseOptionalAlignment(Alignment)) return true;
945 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000946 } else if (Lex.getKind() == lltok::MetadataVar) {
947 if (ParseGlobalObjectMetadataAttachment(*GV))
948 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000949 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000950 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000951 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000952 return true;
953 if (C)
954 GV->setComdat(C);
955 else
956 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000957 }
958 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000959
Chris Lattnerac161bf2009-01-02 07:01:27 +0000960 return false;
961}
962
Bill Wendling63b88192013-02-06 06:52:58 +0000963/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000964/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000965bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000966 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000967 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000968 Lex.Lex();
969
David Majnemerb39e22b2014-12-09 18:33:57 +0000970 if (Lex.getKind() != lltok::AttrGrpID)
971 return TokError("expected attribute group id");
972
Bill Wendling63b88192013-02-06 06:52:58 +0000973 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000974 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000975 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000976 Lex.Lex();
977
978 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000979 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000980 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000981 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000982 ParseToken(lltok::rbrace, "expected end of attribute group"))
983 return true;
984
Bill Wendlingb32b0412013-02-08 06:32:06 +0000985 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000986 return Error(AttrGrpLoc, "attribute group has no attributes");
987
988 return false;
989}
990
Bill Wendling8b0321d2013-02-08 00:52:31 +0000991/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000992/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000993bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
994 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000995 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000996 bool HaveError = false;
997
998 B.clear();
999
Bill Wendling63b88192013-02-06 06:52:58 +00001000 while (true) {
1001 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001002 if (Token == lltok::kw_builtin)
1003 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001004 switch (Token) {
1005 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001006 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001007 return Error(Lex.getLoc(), "unterminated attribute group");
1008 case lltok::rbrace:
1009 // Finished.
1010 return false;
1011
Bill Wendlingb32b0412013-02-08 06:32:06 +00001012 case lltok::AttrGrpID: {
1013 // Allow a function to reference an attribute group:
1014 //
1015 // define void @foo() #1 { ... }
1016 if (inAttrGrp)
1017 HaveError |=
1018 Error(Lex.getLoc(),
1019 "cannot have an attribute group reference in an attribute group");
1020
1021 unsigned AttrGrpNum = Lex.getUIntVal();
1022 if (inAttrGrp) break;
1023
1024 // Save the reference to the attribute group. We'll fill it in later.
1025 FwdRefAttrGrps.push_back(AttrGrpNum);
1026 break;
1027 }
Bill Wendling63b88192013-02-06 06:52:58 +00001028 // Target-dependent attributes:
1029 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001030 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001031 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001032 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001033 }
1034
1035 // Target-independent attributes:
1036 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001037 // As a hack, we allow function alignment to be initially parsed as an
1038 // attribute on a function declaration/definition or added to an attribute
1039 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001040 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001041 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001042 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001043 if (ParseToken(lltok::equal, "expected '=' here") ||
1044 ParseUInt32(Alignment))
1045 return true;
1046 } else {
1047 if (ParseOptionalAlignment(Alignment))
1048 return true;
1049 }
Bill Wendling63b88192013-02-06 06:52:58 +00001050 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001051 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001052 }
1053 case lltok::kw_alignstack: {
1054 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001055 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001056 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001057 if (ParseToken(lltok::equal, "expected '=' here") ||
1058 ParseUInt32(Alignment))
1059 return true;
1060 } else {
1061 if (ParseOptionalStackAlignment(Alignment))
1062 return true;
1063 }
Bill Wendling63b88192013-02-06 06:52:58 +00001064 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001065 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001066 }
George Burgess IV278199f2016-04-12 01:05:35 +00001067 case lltok::kw_allocsize: {
1068 unsigned ElemSizeArg;
1069 Optional<unsigned> NumElemsArg;
1070 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1071 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1072 return true;
1073 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1074 continue;
1075 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001076 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1077 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1078 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1079 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1080 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001081 case lltok::kw_inaccessiblememonly:
1082 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1083 case lltok::kw_inaccessiblemem_or_argmemonly:
1084 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001085 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1086 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1087 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1088 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1089 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1090 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1091 case lltok::kw_noimplicitfloat:
1092 B.addAttribute(Attribute::NoImplicitFloat); break;
1093 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1094 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1095 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1096 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001097 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001098 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1099 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1100 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1101 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1102 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1103 case lltok::kw_returns_twice:
1104 B.addAttribute(Attribute::ReturnsTwice); break;
1105 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1106 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1107 case lltok::kw_sspstrong:
1108 B.addAttribute(Attribute::StackProtectStrong); break;
1109 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1110 case lltok::kw_sanitize_address:
1111 B.addAttribute(Attribute::SanitizeAddress); break;
1112 case lltok::kw_sanitize_thread:
1113 B.addAttribute(Attribute::SanitizeThread); break;
1114 case lltok::kw_sanitize_memory:
1115 B.addAttribute(Attribute::SanitizeMemory); break;
1116 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001117 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001118
1119 // Error handling.
1120 case lltok::kw_inreg:
1121 case lltok::kw_signext:
1122 case lltok::kw_zeroext:
1123 HaveError |=
1124 Error(Lex.getLoc(),
1125 "invalid use of attribute on a function");
1126 break;
1127 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001128 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001129 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001130 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001131 case lltok::kw_nest:
1132 case lltok::kw_noalias:
1133 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001134 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001135 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001136 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001137 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001138 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001139 HaveError |=
1140 Error(Lex.getLoc(),
1141 "invalid use of parameter-only attribute on a function");
1142 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001143 }
1144
1145 Lex.Lex();
1146 }
1147}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001148
1149//===----------------------------------------------------------------------===//
1150// GlobalValue Reference/Resolution Routines.
1151//===----------------------------------------------------------------------===//
1152
Karl Schimpf77729782015-09-03 18:06:44 +00001153static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1154 const std::string &Name) {
1155 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1156 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1157 else
1158 return new GlobalVariable(*M, PTy->getElementType(), false,
1159 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1160 nullptr, GlobalVariable::NotThreadLocal,
1161 PTy->getAddressSpace());
1162}
1163
Chris Lattnerac161bf2009-01-02 07:01:27 +00001164/// GetGlobalVal - Get a value with the specified name or ID, creating a
1165/// forward reference record if needed. This can return null if the value
1166/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001167GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001168 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001169 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001170 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001171 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001172 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001173 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001174
Chris Lattnerac161bf2009-01-02 07:01:27 +00001175 // Look this name up in the normal function symbol table.
1176 GlobalValue *Val =
1177 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001178
Chris Lattnerac161bf2009-01-02 07:01:27 +00001179 // If this is a forward reference for the value, see if we already created a
1180 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001181 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001182 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183 if (I != ForwardRefVals.end())
1184 Val = I->second.first;
1185 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001186
Chris Lattnerac161bf2009-01-02 07:01:27 +00001187 // If we have the value in the symbol table or fwd-ref table, return it.
1188 if (Val) {
1189 if (Val->getType() == Ty) return Val;
1190 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001191 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001192 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001194
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001196 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1198 return FwdVal;
1199}
1200
Chris Lattner229907c2011-07-18 04:54:35 +00001201GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1202 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001203 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001204 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001205 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001207
Craig Topper2617dcc2014-04-15 06:32:26 +00001208 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001209
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210 // If this is a forward reference for the value, see if we already created a
1211 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001212 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001213 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 if (I != ForwardRefValIDs.end())
1215 Val = I->second.first;
1216 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001217
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218 // If we have the value in the symbol table or fwd-ref table, return it.
1219 if (Val) {
1220 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001221 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001222 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001223 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001225
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001227 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1229 return FwdVal;
1230}
1231
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001233// Comdat Reference/Resolution Routines.
1234//===----------------------------------------------------------------------===//
1235
1236Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1237 // Look this name up in the comdat symbol table.
1238 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1239 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1240 if (I != ComdatSymTab.end())
1241 return &I->second;
1242
1243 // Otherwise, create a new forward reference for this value and remember it.
1244 Comdat *C = M->getOrInsertComdat(Name);
1245 ForwardRefComdats[Name] = Loc;
1246 return C;
1247}
1248
David Majnemerdad0a642014-06-27 18:19:56 +00001249//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001250// Helper Routines.
1251//===----------------------------------------------------------------------===//
1252
1253/// ParseToken - If the current token has the specified kind, eat it and return
1254/// success. Otherwise, emit the specified error and return failure.
1255bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1256 if (Lex.getKind() != T)
1257 return TokError(ErrMsg);
1258 Lex.Lex();
1259 return false;
1260}
1261
Chris Lattner3822f632009-01-02 08:05:26 +00001262/// ParseStringConstant
1263/// ::= StringConstant
1264bool LLParser::ParseStringConstant(std::string &Result) {
1265 if (Lex.getKind() != lltok::StringConstant)
1266 return TokError("expected string constant");
1267 Result = Lex.getStrVal();
1268 Lex.Lex();
1269 return false;
1270}
1271
1272/// ParseUInt32
1273/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001274bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001275 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1276 return TokError("expected integer");
1277 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1278 if (Val64 != unsigned(Val64))
1279 return TokError("expected 32-bit integer (too large)");
1280 Val = Val64;
1281 Lex.Lex();
1282 return false;
1283}
1284
Hal Finkelb0407ba2014-07-18 15:51:28 +00001285/// ParseUInt64
1286/// ::= uint64
1287bool LLParser::ParseUInt64(uint64_t &Val) {
1288 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1289 return TokError("expected integer");
1290 Val = Lex.getAPSIntVal().getLimitedValue();
1291 Lex.Lex();
1292 return false;
1293}
1294
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001295/// ParseTLSModel
1296/// := 'localdynamic'
1297/// := 'initialexec'
1298/// := 'localexec'
1299bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1300 switch (Lex.getKind()) {
1301 default:
1302 return TokError("expected localdynamic, initialexec or localexec");
1303 case lltok::kw_localdynamic:
1304 TLM = GlobalVariable::LocalDynamicTLSModel;
1305 break;
1306 case lltok::kw_initialexec:
1307 TLM = GlobalVariable::InitialExecTLSModel;
1308 break;
1309 case lltok::kw_localexec:
1310 TLM = GlobalVariable::LocalExecTLSModel;
1311 break;
1312 }
1313
1314 Lex.Lex();
1315 return false;
1316}
1317
1318/// ParseOptionalThreadLocal
1319/// := /*empty*/
1320/// := 'thread_local'
1321/// := 'thread_local' '(' tlsmodel ')'
1322bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1323 TLM = GlobalVariable::NotThreadLocal;
1324 if (!EatIfPresent(lltok::kw_thread_local))
1325 return false;
1326
1327 TLM = GlobalVariable::GeneralDynamicTLSModel;
1328 if (Lex.getKind() == lltok::lparen) {
1329 Lex.Lex();
1330 return ParseTLSModel(TLM) ||
1331 ParseToken(lltok::rparen, "expected ')' after thread local model");
1332 }
1333 return false;
1334}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001335
1336/// ParseOptionalAddrSpace
1337/// := /*empty*/
1338/// := 'addrspace' '(' uint32 ')'
1339bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1340 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001341 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001342 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001343 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001344 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001345 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001346}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001347
Artur Pilipenko17376c42015-08-03 14:31:49 +00001348/// ParseStringAttribute
1349/// := StringConstant
1350/// := StringConstant '=' StringConstant
1351bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1352 std::string Attr = Lex.getStrVal();
1353 Lex.Lex();
1354 std::string Val;
1355 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1356 return true;
1357 B.addAttribute(Attr, Val);
1358 return false;
1359}
1360
Bill Wendling34c2eb22012-12-04 23:40:58 +00001361/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1362bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1363 bool HaveError = false;
1364
1365 B.clear();
1366
Eugene Zelenko1804a772016-08-25 00:45:04 +00001367 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001368 lltok::Kind Token = Lex.getKind();
1369 switch (Token) {
1370 default: // End of attributes.
1371 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001372 case lltok::StringConstant: {
1373 if (ParseStringAttribute(B))
1374 return true;
1375 continue;
1376 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001377 case lltok::kw_align: {
1378 unsigned Alignment;
1379 if (ParseOptionalAlignment(Alignment))
1380 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001381 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382 continue;
1383 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001384 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001385 case lltok::kw_dereferenceable: {
1386 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001387 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001388 return true;
1389 B.addDereferenceableAttr(Bytes);
1390 continue;
1391 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001392 case lltok::kw_dereferenceable_or_null: {
1393 uint64_t Bytes;
1394 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1395 return true;
1396 B.addDereferenceableOrNullAttr(Bytes);
1397 continue;
1398 }
Reid Klecknera534a382013-12-19 02:14:12 +00001399 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001400 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1401 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1402 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1403 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001404 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001405 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1406 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001407 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001408 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1409 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001410 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001411 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001412 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001413 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001414
Stephen Lin7577ed52013-04-20 13:16:13 +00001415 case lltok::kw_alignstack:
1416 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001417 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001418 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001419 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001420 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001421 case lltok::kw_minsize:
1422 case lltok::kw_naked:
1423 case lltok::kw_nobuiltin:
1424 case lltok::kw_noduplicate:
1425 case lltok::kw_noimplicitfloat:
1426 case lltok::kw_noinline:
1427 case lltok::kw_nonlazybind:
1428 case lltok::kw_noredzone:
1429 case lltok::kw_noreturn:
1430 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001431 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001432 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001433 case lltok::kw_returns_twice:
1434 case lltok::kw_sanitize_address:
1435 case lltok::kw_sanitize_memory:
1436 case lltok::kw_sanitize_thread:
1437 case lltok::kw_ssp:
1438 case lltok::kw_sspreq:
1439 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001440 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001441 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001442 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1443 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001444 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001445
Bill Wendling34c2eb22012-12-04 23:40:58 +00001446 Lex.Lex();
1447 }
1448}
1449
1450/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1451bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1452 bool HaveError = false;
1453
1454 B.clear();
1455
Eugene Zelenko1804a772016-08-25 00:45:04 +00001456 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001457 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001458 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001459 default: // End of attributes.
1460 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001461 case lltok::StringConstant: {
1462 if (ParseStringAttribute(B))
1463 return true;
1464 continue;
1465 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001466 case lltok::kw_dereferenceable: {
1467 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001468 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001469 return true;
1470 B.addDereferenceableAttr(Bytes);
1471 continue;
1472 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001473 case lltok::kw_dereferenceable_or_null: {
1474 uint64_t Bytes;
1475 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1476 return true;
1477 B.addDereferenceableOrNullAttr(Bytes);
1478 continue;
1479 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001480 case lltok::kw_align: {
1481 unsigned Alignment;
1482 if (ParseOptionalAlignment(Alignment))
1483 return true;
1484 B.addAlignmentAttr(Alignment);
1485 continue;
1486 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001487 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1488 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001489 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001490 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1491 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001492
Bill Wendling34c2eb22012-12-04 23:40:58 +00001493 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001494 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001495 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001496 case lltok::kw_nest:
1497 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001498 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001499 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001500 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001501 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001502 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001503 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001504
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001505 case lltok::kw_alignstack:
1506 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001507 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001508 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001509 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001510 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001511 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001512 case lltok::kw_minsize:
1513 case lltok::kw_naked:
1514 case lltok::kw_nobuiltin:
1515 case lltok::kw_noduplicate:
1516 case lltok::kw_noimplicitfloat:
1517 case lltok::kw_noinline:
1518 case lltok::kw_nonlazybind:
1519 case lltok::kw_noredzone:
1520 case lltok::kw_noreturn:
1521 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001522 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001523 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001524 case lltok::kw_returns_twice:
1525 case lltok::kw_sanitize_address:
1526 case lltok::kw_sanitize_memory:
1527 case lltok::kw_sanitize_thread:
1528 case lltok::kw_ssp:
1529 case lltok::kw_sspreq:
1530 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001531 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001532 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001533 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001534 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001535
1536 case lltok::kw_readnone:
1537 case lltok::kw_readonly:
1538 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001539 }
1540
Chris Lattnerac161bf2009-01-02 07:01:27 +00001541 Lex.Lex();
1542 }
1543}
1544
Rafael Espindolac6269912016-05-10 17:16:45 +00001545static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1546 HasLinkage = true;
1547 switch (Kind) {
1548 default:
1549 HasLinkage = false;
1550 return GlobalValue::ExternalLinkage;
1551 case lltok::kw_private:
1552 return GlobalValue::PrivateLinkage;
1553 case lltok::kw_internal:
1554 return GlobalValue::InternalLinkage;
1555 case lltok::kw_weak:
1556 return GlobalValue::WeakAnyLinkage;
1557 case lltok::kw_weak_odr:
1558 return GlobalValue::WeakODRLinkage;
1559 case lltok::kw_linkonce:
1560 return GlobalValue::LinkOnceAnyLinkage;
1561 case lltok::kw_linkonce_odr:
1562 return GlobalValue::LinkOnceODRLinkage;
1563 case lltok::kw_available_externally:
1564 return GlobalValue::AvailableExternallyLinkage;
1565 case lltok::kw_appending:
1566 return GlobalValue::AppendingLinkage;
1567 case lltok::kw_common:
1568 return GlobalValue::CommonLinkage;
1569 case lltok::kw_extern_weak:
1570 return GlobalValue::ExternalWeakLinkage;
1571 case lltok::kw_external:
1572 return GlobalValue::ExternalLinkage;
1573 }
1574}
1575
Chris Lattnerac161bf2009-01-02 07:01:27 +00001576/// ParseOptionalLinkage
1577/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001578/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001579/// ::= 'internal'
1580/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001581/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001582/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001583/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001584/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001585/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001586/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001587/// ::= 'extern_weak'
1588/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001589bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1590 unsigned &Visibility,
1591 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001592 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1593 if (HasLinkage)
1594 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001595 ParseOptionalVisibility(Visibility);
1596 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001597 return false;
1598}
1599
1600/// ParseOptionalVisibility
1601/// ::= /*empty*/
1602/// ::= 'default'
1603/// ::= 'hidden'
1604/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001605///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001606void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001607 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001608 default:
1609 Res = GlobalValue::DefaultVisibility;
1610 return;
1611 case lltok::kw_default:
1612 Res = GlobalValue::DefaultVisibility;
1613 break;
1614 case lltok::kw_hidden:
1615 Res = GlobalValue::HiddenVisibility;
1616 break;
1617 case lltok::kw_protected:
1618 Res = GlobalValue::ProtectedVisibility;
1619 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001620 }
1621 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001622}
1623
Nico Rieck7157bb72014-01-14 15:22:47 +00001624/// ParseOptionalDLLStorageClass
1625/// ::= /*empty*/
1626/// ::= 'dllimport'
1627/// ::= 'dllexport'
1628///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001629void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001630 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001631 default:
1632 Res = GlobalValue::DefaultStorageClass;
1633 return;
1634 case lltok::kw_dllimport:
1635 Res = GlobalValue::DLLImportStorageClass;
1636 break;
1637 case lltok::kw_dllexport:
1638 Res = GlobalValue::DLLExportStorageClass;
1639 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001640 }
1641 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001642}
1643
Chris Lattnerac161bf2009-01-02 07:01:27 +00001644/// ParseOptionalCallingConv
1645/// ::= /*empty*/
1646/// ::= 'ccc'
1647/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001648/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001649/// ::= 'coldcc'
1650/// ::= 'x86_stdcallcc'
1651/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001652/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001653/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001654/// ::= 'arm_apcscc'
1655/// ::= 'arm_aapcscc'
1656/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001657/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001658/// ::= 'avr_intrcc'
1659/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001660/// ::= 'ptx_kernel'
1661/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001662/// ::= 'spir_func'
1663/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001664/// ::= 'x86_64_sysvcc'
1665/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001666/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001667/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001668/// ::= 'preserve_mostcc'
1669/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001670/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001671/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001672/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001673/// ::= 'hhvmcc'
1674/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001675/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001676/// ::= 'amdgpu_vs'
1677/// ::= 'amdgpu_tcs'
1678/// ::= 'amdgpu_tes'
1679/// ::= 'amdgpu_gs'
1680/// ::= 'amdgpu_ps'
1681/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001682/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001683/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001684///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001685bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 switch (Lex.getKind()) {
1687 default: CC = CallingConv::C; return false;
1688 case lltok::kw_ccc: CC = CallingConv::C; break;
1689 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1690 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1691 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1692 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001693 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001694 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001695 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1696 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1697 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001698 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001699 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1700 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001701 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1702 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001703 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1704 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001705 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001706 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1707 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001708 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001709 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001710 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1711 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001712 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001713 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001714 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001715 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1716 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001717 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001718 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1719 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1720 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1721 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001722 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001723 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001724 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001725 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001726 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001728
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729 Lex.Lex();
1730 return false;
1731}
1732
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001733/// ParseMetadataAttachment
1734/// ::= !dbg !42
1735bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1736 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1737
1738 std::string Name = Lex.getStrVal();
1739 Kind = M->getMDKindID(Name);
1740 Lex.Lex();
1741
1742 return ParseMDNode(MD);
1743}
1744
Chris Lattner5c427632009-12-30 05:31:19 +00001745/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001746/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001747bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001748 do {
1749 if (Lex.getKind() != lltok::MetadataVar)
1750 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001751
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001752 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001753 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001754 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001755 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001756
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001757 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001758 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001759 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001760
Chris Lattner596760d2009-12-29 21:25:40 +00001761 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001762 } while (EatIfPresent(lltok::comma));
1763 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001764}
1765
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001766/// ParseGlobalObjectMetadataAttachment
1767/// ::= !dbg !57
1768bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1769 unsigned MDK;
1770 MDNode *N;
1771 if (ParseMetadataAttachment(MDK, N))
1772 return true;
1773
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001774 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001775 return false;
1776}
1777
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001778/// ParseOptionalFunctionMetadata
1779/// ::= (!dbg !57)*
1780bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001781 while (Lex.getKind() == lltok::MetadataVar)
1782 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001783 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001784 return false;
1785}
1786
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787/// ParseOptionalAlignment
1788/// ::= /* empty */
1789/// ::= 'align' 4
1790bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1791 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001792 if (!EatIfPresent(lltok::kw_align))
1793 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001794 LocTy AlignLoc = Lex.getLoc();
1795 if (ParseUInt32(Alignment)) return true;
1796 if (!isPowerOf2_32(Alignment))
1797 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001798 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001799 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001800 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801}
1802
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001803/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001804/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001805/// ::= AttrKind '(' 4 ')'
1806///
1807/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1808bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1809 uint64_t &Bytes) {
1810 assert((AttrKind == lltok::kw_dereferenceable ||
1811 AttrKind == lltok::kw_dereferenceable_or_null) &&
1812 "contract!");
1813
Hal Finkelb0407ba2014-07-18 15:51:28 +00001814 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001815 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001816 return false;
1817 LocTy ParenLoc = Lex.getLoc();
1818 if (!EatIfPresent(lltok::lparen))
1819 return Error(ParenLoc, "expected '('");
1820 LocTy DerefLoc = Lex.getLoc();
1821 if (ParseUInt64(Bytes)) return true;
1822 ParenLoc = Lex.getLoc();
1823 if (!EatIfPresent(lltok::rparen))
1824 return Error(ParenLoc, "expected ')'");
1825 if (!Bytes)
1826 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1827 return false;
1828}
1829
Chris Lattnerb2f39502009-12-30 05:44:30 +00001830/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001831/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001832/// ::= ',' align 4
1833///
1834/// This returns with AteExtraComma set to true if it ate an excess comma at the
1835/// end.
1836bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1837 bool &AteExtraComma) {
1838 AteExtraComma = false;
1839 while (EatIfPresent(lltok::comma)) {
1840 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001841 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001842 AteExtraComma = true;
1843 return false;
1844 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001845
Chris Lattner95b0ff42010-04-23 00:50:50 +00001846 if (Lex.getKind() != lltok::kw_align)
1847 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001848
Chris Lattner95b0ff42010-04-23 00:50:50 +00001849 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001850 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001851
Devang Patelea8a4b92009-09-17 23:04:48 +00001852 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853}
1854
George Burgess IV278199f2016-04-12 01:05:35 +00001855bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1856 Optional<unsigned> &HowManyArg) {
1857 Lex.Lex();
1858
1859 auto StartParen = Lex.getLoc();
1860 if (!EatIfPresent(lltok::lparen))
1861 return Error(StartParen, "expected '('");
1862
1863 if (ParseUInt32(BaseSizeArg))
1864 return true;
1865
1866 if (EatIfPresent(lltok::comma)) {
1867 auto HowManyAt = Lex.getLoc();
1868 unsigned HowMany;
1869 if (ParseUInt32(HowMany))
1870 return true;
1871 if (HowMany == BaseSizeArg)
1872 return Error(HowManyAt,
1873 "'allocsize' indices can't refer to the same parameter");
1874 HowManyArg = HowMany;
1875 } else
1876 HowManyArg = None;
1877
1878 auto EndParen = Lex.getLoc();
1879 if (!EatIfPresent(lltok::rparen))
1880 return Error(EndParen, "expected ')'");
1881 return false;
1882}
1883
Eli Friedmanfee02c62011-07-25 23:16:38 +00001884/// ParseScopeAndOrdering
1885/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1886/// else: ::=
1887///
1888/// This sets Scope and Ordering to the parsed values.
1889bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1890 AtomicOrdering &Ordering) {
1891 if (!isAtomic)
1892 return false;
1893
1894 Scope = CrossThread;
1895 if (EatIfPresent(lltok::kw_singlethread))
1896 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001897
1898 return ParseOrdering(Ordering);
1899}
1900
1901/// ParseOrdering
1902/// ::= AtomicOrdering
1903///
1904/// This sets Ordering to the parsed value.
1905bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001906 switch (Lex.getKind()) {
1907 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001908 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1909 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1910 // Not specified yet:
1911 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1912 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1913 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1914 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1915 case lltok::kw_seq_cst:
1916 Ordering = AtomicOrdering::SequentiallyConsistent;
1917 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001918 }
1919 Lex.Lex();
1920 return false;
1921}
1922
Charles Davisbe5557e2010-02-12 00:31:15 +00001923/// ParseOptionalStackAlignment
1924/// ::= /* empty */
1925/// ::= 'alignstack' '(' 4 ')'
1926bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1927 Alignment = 0;
1928 if (!EatIfPresent(lltok::kw_alignstack))
1929 return false;
1930 LocTy ParenLoc = Lex.getLoc();
1931 if (!EatIfPresent(lltok::lparen))
1932 return Error(ParenLoc, "expected '('");
1933 LocTy AlignLoc = Lex.getLoc();
1934 if (ParseUInt32(Alignment)) return true;
1935 ParenLoc = Lex.getLoc();
1936 if (!EatIfPresent(lltok::rparen))
1937 return Error(ParenLoc, "expected ')'");
1938 if (!isPowerOf2_32(Alignment))
1939 return Error(AlignLoc, "stack alignment is not a power of two");
1940 return false;
1941}
Devang Patelea8a4b92009-09-17 23:04:48 +00001942
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001943/// ParseIndexList - This parses the index list for an insert/extractvalue
1944/// instruction. This sets AteExtraComma in the case where we eat an extra
1945/// comma at the end of the line and find that it is followed by metadata.
1946/// Clients that don't allow metadata can call the version of this function that
1947/// only takes one argument.
1948///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001949/// ParseIndexList
1950/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001951///
1952bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1953 bool &AteExtraComma) {
1954 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001955
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 if (Lex.getKind() != lltok::comma)
1957 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Chris Lattner3822f632009-01-02 08:05:26 +00001959 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001960 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001961 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001962 AteExtraComma = true;
1963 return false;
1964 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001965 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001966 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 Indices.push_back(Idx);
1968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001969
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 return false;
1971}
1972
1973//===----------------------------------------------------------------------===//
1974// Type Parsing.
1975//===----------------------------------------------------------------------===//
1976
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001977/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001978bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001979 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001980 switch (Lex.getKind()) {
1981 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001982 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001987 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 // Type ::= StructType
1990 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 return true;
1992 break;
1993 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001994 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995 Lex.Lex(); // eat the lsquare.
1996 if (ParseArrayVectorType(Result, false))
1997 return true;
1998 break;
1999 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002000 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002001 Lex.Lex();
2002 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002004 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 } else if (ParseArrayVectorType(Result, true))
2007 return true;
2008 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009 case lltok::LocalVar: {
2010 // Type ::= %foo
2011 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002012
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002013 // If the type hasn't been defined yet, create a forward definition and
2014 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002015 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002016 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020 Lex.Lex();
2021 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024 case lltok::LocalVarID: {
2025 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002027
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 // If the type hasn't been defined yet, create a forward definition and
2029 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002030 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002031 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002035 Lex.Lex();
2036 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002037 }
2038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002039
2040 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002041 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 switch (Lex.getKind()) {
2043 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002044 default:
2045 if (!AllowVoid && Result->isVoidTy())
2046 return Error(TypeLoc, "void type only allowed for function results");
2047 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002052 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 if (Result->isVoidTy())
2054 return TokError("pointers to void are invalid - use i8* instead");
2055 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002056 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002057 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 Lex.Lex();
2059 break;
2060
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002066 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002067 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002068 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069 unsigned AddrSpace;
2070 if (ParseOptionalAddrSpace(AddrSpace) ||
2071 ParseToken(lltok::star, "expected '*' in address space"))
2072 return true;
2073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 break;
2076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002077
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2079 case lltok::lparen:
2080 if (ParseFunctionType(Result))
2081 return true;
2082 break;
2083 }
2084 }
2085}
2086
2087/// ParseParameterList
2088/// ::= '(' ')'
2089/// ::= '(' Arg (',' Arg)* ')'
2090/// Arg
2091/// ::= Type OptionalAttributes Value OptionalAttributes
2092bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002093 PerFunctionState &PFS, bool IsMustTailCall,
2094 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 if (ParseToken(lltok::lparen, "expected '(' in call"))
2096 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002097
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002098 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 while (Lex.getKind() != lltok::rparen) {
2100 // If this isn't the first argument, we need a comma.
2101 if (!ArgList.empty() &&
2102 ParseToken(lltok::comma, "expected ',' in argument list"))
2103 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002104
Reid Kleckner83498642014-08-26 00:33:28 +00002105 // Parse an ellipsis if this is a musttail call in a variadic function.
2106 if (Lex.getKind() == lltok::dotdotdot) {
2107 const char *Msg = "unexpected ellipsis in argument list for ";
2108 if (!IsMustTailCall)
2109 return TokError(Twine(Msg) + "non-musttail call");
2110 if (!InVarArgsFunc)
2111 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2112 Lex.Lex(); // Lex the '...', it is purely for readability.
2113 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2114 }
2115
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 // Parse the argument.
2117 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002118 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002119 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002121 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002123
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002124 if (ArgTy->isMetadataTy()) {
2125 if (ParseMetadataAsValue(V, PFS))
2126 return true;
2127 } else {
2128 // Otherwise, handle normal operands.
2129 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2130 return true;
2131 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002132 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2133 AttrIndex++,
2134 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 }
2136
Reid Kleckner83498642014-08-26 00:33:28 +00002137 if (IsMustTailCall && InVarArgsFunc)
2138 return TokError("expected '...' at end of argument list for musttail call "
2139 "in varargs function");
2140
Chris Lattnerac161bf2009-01-02 07:01:27 +00002141 Lex.Lex(); // Lex the ')'.
2142 return false;
2143}
2144
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002145/// ParseOptionalOperandBundles
2146/// ::= /*empty*/
2147/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2148///
2149/// OperandBundle
2150/// ::= bundle-tag '(' ')'
2151/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2152///
2153/// bundle-tag ::= String Constant
2154bool LLParser::ParseOptionalOperandBundles(
2155 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2156 LocTy BeginLoc = Lex.getLoc();
2157 if (!EatIfPresent(lltok::lsquare))
2158 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002160 while (Lex.getKind() != lltok::rsquare) {
2161 // If this isn't the first operand bundle, we need a comma.
2162 if (!BundleList.empty() &&
2163 ParseToken(lltok::comma, "expected ',' in input list"))
2164 return true;
2165
2166 std::string Tag;
2167 if (ParseStringConstant(Tag))
2168 return true;
2169
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002170 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2171 return true;
2172
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002173 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002174 while (Lex.getKind() != lltok::rparen) {
2175 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002176 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002177 ParseToken(lltok::comma, "expected ',' in input list"))
2178 return true;
2179
2180 Type *Ty = nullptr;
2181 Value *Input = nullptr;
2182 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2183 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002184 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002185 }
2186
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002187 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2188
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002189 Lex.Lex(); // Lex the ')'.
2190 }
2191
2192 if (BundleList.empty())
2193 return Error(BeginLoc, "operand bundle set must not be empty");
2194
2195 Lex.Lex(); // Lex the ']'.
2196 return false;
2197}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198
Chris Lattner2ed06b42009-01-05 18:34:07 +00002199/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002200/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201/// ::= '(' ArgTypeListI ')'
2202/// ArgTypeListI
2203/// ::= /*empty*/
2204/// ::= '...'
2205/// ::= ArgTypeList ',' '...'
2206/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002207///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002208bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2209 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 isVarArg = false;
2211 assert(Lex.getKind() == lltok::lparen);
2212 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002213
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 if (Lex.getKind() == lltok::rparen) {
2215 // empty
2216 } else if (Lex.getKind() == lltok::dotdotdot) {
2217 isVarArg = true;
2218 Lex.Lex();
2219 } else {
2220 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002221 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002222 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002223 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002225 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002226 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerfdd87902009-10-05 05:54:46 +00002228 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002229 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002230
Chris Lattnerdef19492011-06-17 06:36:20 +00002231 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 Name = Lex.getStrVal();
2233 Lex.Lex();
2234 }
Chris Lattner3822f632009-01-02 08:05:26 +00002235
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002236 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002237 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002239 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002240 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2241 AttrIndex++, Attrs),
2242 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243
Chris Lattner3822f632009-01-02 08:05:26 +00002244 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002246 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 break;
2249 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 // Otherwise must be an argument type.
2252 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002253 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002254
Chris Lattnerfdd87902009-10-05 05:54:46 +00002255 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002256 return Error(TypeLoc, "argument can not have void type");
2257
Chris Lattnerdef19492011-06-17 06:36:20 +00002258 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 Name = Lex.getStrVal();
2260 Lex.Lex();
2261 } else {
2262 Name = "";
2263 }
Chris Lattner3822f632009-01-02 08:05:26 +00002264
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002265 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002266 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002267
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002268 ArgList.emplace_back(
2269 TypeLoc, ArgTy,
2270 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2271 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 }
2273 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002274
Chris Lattner3822f632009-01-02 08:05:26 +00002275 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002276}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277
Chris Lattnerac161bf2009-01-02 07:01:27 +00002278/// ParseFunctionType
2279/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 assert(Lex.getKind() == lltok::lparen);
2282
Chris Lattnerce473c72009-01-05 08:04:33 +00002283 if (!FunctionType::isValidReturnType(Result))
2284 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002285
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002286 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002288 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002289 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 // Reject names on the arguments lists.
2292 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2293 if (!ArgList[i].Name.empty())
2294 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002295 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002296 return Error(ArgList[i].Loc,
2297 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002298 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Jay Foadb804a2b2011-07-12 14:06:48 +00002300 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002302 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002303
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002304 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 return false;
2306}
2307
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2309/// other structs.
2310bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2311 SmallVector<Type*, 8> Elts;
2312 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002313
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002314 Result = StructType::get(Context, Elts, Packed);
2315 return false;
2316}
2317
2318/// ParseStructDefinition - Parse a struct in a 'type' definition.
2319bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2320 std::pair<Type*, LocTy> &Entry,
2321 Type *&ResultTy) {
2322 // If the type was already defined, diagnose the redefinition.
2323 if (Entry.first && !Entry.second.isValid())
2324 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002325
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 // If we have opaque, just return without filling in the definition for the
2327 // struct. This counts as a definition as far as the .ll file goes.
2328 if (EatIfPresent(lltok::kw_opaque)) {
2329 // This type is being defined, so clear the location to indicate this.
2330 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002331
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002332 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002333 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002334 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 ResultTy = Entry.first;
2336 return false;
2337 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002339 // If the type starts with '<', then it is either a packed struct or a vector.
2340 bool isPacked = EatIfPresent(lltok::less);
2341
2342 // If we don't have a struct, then we have a random type alias, which we
2343 // accept for compatibility with old files. These types are not allowed to be
2344 // forward referenced and not allowed to be recursive.
2345 if (Lex.getKind() != lltok::lbrace) {
2346 if (Entry.first)
2347 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002348
Craig Topper2617dcc2014-04-15 06:32:26 +00002349 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002350 if (isPacked)
2351 return ParseArrayVectorType(ResultTy, true);
2352 return ParseType(ResultTy);
2353 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002354
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002355 // This type is being defined, so clear the location to indicate this.
2356 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002358 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002359 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002360 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002361
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002362 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002363
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002364 SmallVector<Type*, 8> Body;
2365 if (ParseStructBody(Body) ||
2366 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2367 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002368
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002369 STy->setBody(Body, isPacked);
2370 ResultTy = STy;
2371 return false;
2372}
2373
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002375/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002377/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002379/// ::= '<' '{' Type (',' Type)* '}' '>'
2380bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002381 assert(Lex.getKind() == lltok::lbrace);
2382 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002383
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002384 // Handle the empty struct.
2385 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002386 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387
Chris Lattnerf880ca22009-03-09 04:49:14 +00002388 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002389 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002390 if (ParseType(Ty)) return true;
2391 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002393 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002394 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002395
Chris Lattner3822f632009-01-02 08:05:26 +00002396 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002397 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002398 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002399
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002400 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002401 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002403 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407}
2408
2409/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2410/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002411/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412/// ::= '[' APSINTVAL 'x' Types ']'
2413/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002414bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2416 Lex.getAPSIntVal().getBitWidth() > 64)
2417 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 LocTy SizeLoc = Lex.getLoc();
2420 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002421 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002422
Chris Lattner3822f632009-01-02 08:05:26 +00002423 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2424 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002425
2426 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002427 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002428 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002429
Chris Lattner3822f632009-01-02 08:05:26 +00002430 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2431 "expected end of sequential type"))
2432 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002435 if (Size == 0)
2436 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 if ((unsigned)Size != Size)
2438 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002439 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002440 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002441 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002442 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002443 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002445 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 }
2447 return false;
2448}
2449
2450//===----------------------------------------------------------------------===//
2451// Function Semantic Analysis.
2452//===----------------------------------------------------------------------===//
2453
Chris Lattner3432c622009-10-28 03:39:23 +00002454LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2455 int functionNumber)
2456 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457
2458 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002459 for (Argument &A : F.args())
2460 if (!A.hasName())
2461 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462}
2463
2464LLParser::PerFunctionState::~PerFunctionState() {
2465 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002466
David Blaikie9ebdc692015-09-21 21:07:50 +00002467 for (const auto &P : ForwardRefVals) {
2468 if (isa<BasicBlock>(P.second.first))
2469 continue;
2470 P.second.first->replaceAllUsesWith(
2471 UndefValue::get(P.second.first->getType()));
2472 delete P.second.first;
2473 }
2474
2475 for (const auto &P : ForwardRefValIDs) {
2476 if (isa<BasicBlock>(P.second.first))
2477 continue;
2478 P.second.first->replaceAllUsesWith(
2479 UndefValue::get(P.second.first->getType()));
2480 delete P.second.first;
2481 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002482}
2483
Chris Lattner3432c622009-10-28 03:39:23 +00002484bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 if (!ForwardRefVals.empty())
2486 return P.Error(ForwardRefVals.begin()->second.second,
2487 "use of undefined value '%" + ForwardRefVals.begin()->first +
2488 "'");
2489 if (!ForwardRefValIDs.empty())
2490 return P.Error(ForwardRefValIDs.begin()->second.second,
2491 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002492 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002493 return false;
2494}
2495
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496/// GetVal - Get a value with the specified name or ID, creating a
2497/// forward reference record if needed. This can return null if the value
2498/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002499Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002500 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 // Look this name up in the normal function symbol table.
2502 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002503
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 // If this is a forward reference for the value, see if we already created a
2505 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002506 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002507 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 if (I != ForwardRefVals.end())
2509 Val = I->second.first;
2510 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002511
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 // If we have the value in the symbol table or fwd-ref table, return it.
2513 if (Val) {
2514 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002515 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 P.Error(Loc, "'%" + Name + "' is not a basic block");
2517 else
2518 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002519 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002520 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002524 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002526 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002527 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002528
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 // Otherwise, create a new forward reference for this value and remember it.
2530 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002531 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002532 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002533 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002534 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002535 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2538 return FwdVal;
2539}
2540
David Majnemer8a1c45d2015-12-12 05:38:55 +00002541Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002542 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002543 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 // If this is a forward reference for the value, see if we already created a
2546 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002547 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002548 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 if (I != ForwardRefValIDs.end())
2550 Val = I->second.first;
2551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002552
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 // If we have the value in the symbol table or fwd-ref table, return it.
2554 if (Val) {
2555 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002556 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002557 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002559 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002560 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002561 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002564 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002566 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002568
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 // Otherwise, create a new forward reference for this value and remember it.
2570 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002571 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002572 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002573 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002574 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002575 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002576
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2578 return FwdVal;
2579}
2580
2581/// SetInstName - After an instruction is parsed and inserted into its
2582/// basic block, this installs its name.
2583bool LLParser::PerFunctionState::SetInstName(int NameID,
2584 const std::string &NameStr,
2585 LocTy NameLoc, Instruction *Inst) {
2586 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002587 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588 if (NameID != -1 || !NameStr.empty())
2589 return P.Error(NameLoc, "instructions returning void cannot have a name");
2590 return false;
2591 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002592
Chris Lattnerac161bf2009-01-02 07:01:27 +00002593 // If this was a numbered instruction, verify that the instruction is the
2594 // expected value and resolve any forward references.
2595 if (NameStr.empty()) {
2596 // If neither a name nor an ID was specified, just use the next ID.
2597 if (NameID == -1)
2598 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002599
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 if (unsigned(NameID) != NumberedVals.size())
2601 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002602 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002603
David Blaikie9ebdc692015-09-21 21:07:50 +00002604 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002606 Value *Sentinel = FI->second.first;
2607 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002608 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002609 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002610
2611 Sentinel->replaceAllUsesWith(Inst);
2612 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 ForwardRefValIDs.erase(FI);
2614 }
2615
2616 NumberedVals.push_back(Inst);
2617 return false;
2618 }
2619
2620 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002621 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002623 Value *Sentinel = FI->second.first;
2624 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002625 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002626 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002627
2628 Sentinel->replaceAllUsesWith(Inst);
2629 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 ForwardRefVals.erase(FI);
2631 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 // Set the name on the instruction.
2634 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002635
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002636 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002637 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 NameStr + "'");
2639 return false;
2640}
2641
2642/// GetBB - Get a basic block with the specified name or ID, creating a
2643/// forward reference record if needed.
2644BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2645 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002646 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2647 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648}
2649
2650BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002651 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2652 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653}
2654
2655/// DefineBB - Define the specified basic block, which is either named or
2656/// unnamed. If there is an error, this returns null otherwise it returns
2657/// the block being defined.
2658BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2659 LocTy Loc) {
2660 BasicBlock *BB;
2661 if (Name.empty())
2662 BB = GetBB(NumberedVals.size(), Loc);
2663 else
2664 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002665 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 // Move the block to the end of the function. Forward ref'd blocks are
2668 // inserted wherever they happen to be referenced.
2669 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 // Remove the block from forward ref sets.
2672 if (Name.empty()) {
2673 ForwardRefValIDs.erase(NumberedVals.size());
2674 NumberedVals.push_back(BB);
2675 } else {
2676 // BB forward references are already in the function symbol table.
2677 ForwardRefVals.erase(Name);
2678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002679
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 return BB;
2681}
2682
2683//===----------------------------------------------------------------------===//
2684// Constants.
2685//===----------------------------------------------------------------------===//
2686
2687/// ParseValID - Parse an abstract value that doesn't necessarily have a
2688/// type implied. For example, if we parse "4" we don't know what integer type
2689/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002690/// sanity. PFS is used to convert function-local operands of metadata (since
2691/// metadata operands are not just parsed here but also converted to values).
2692/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002693bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 ID.Loc = Lex.getLoc();
2695 switch (Lex.getKind()) {
2696 default: return TokError("expected value token");
2697 case lltok::GlobalID: // @42
2698 ID.UIntVal = Lex.getUIntVal();
2699 ID.Kind = ValID::t_GlobalID;
2700 break;
2701 case lltok::GlobalVar: // @foo
2702 ID.StrVal = Lex.getStrVal();
2703 ID.Kind = ValID::t_GlobalName;
2704 break;
2705 case lltok::LocalVarID: // %42
2706 ID.UIntVal = Lex.getUIntVal();
2707 ID.Kind = ValID::t_LocalID;
2708 break;
2709 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 ID.StrVal = Lex.getStrVal();
2711 ID.Kind = ValID::t_LocalName;
2712 break;
2713 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 ID.Kind = ValID::t_APSInt;
2716 break;
2717 case lltok::APFloat:
2718 ID.APFloatVal = Lex.getAPFloatVal();
2719 ID.Kind = ValID::t_APFloat;
2720 break;
2721 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002722 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723 ID.Kind = ValID::t_Constant;
2724 break;
2725 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002726 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 ID.Kind = ValID::t_Constant;
2728 break;
2729 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2730 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2731 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002732 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002733
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 case lltok::lbrace: {
2735 // ValID ::= '{' ConstVector '}'
2736 Lex.Lex();
2737 SmallVector<Constant*, 16> Elts;
2738 if (ParseGlobalValueVector(Elts) ||
2739 ParseToken(lltok::rbrace, "expected end of struct constant"))
2740 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
David Blaikieadbda4b2015-08-03 20:08:41 +00002742 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002743 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002744 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2745 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002746 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002747 return false;
2748 }
2749 case lltok::less: {
2750 // ValID ::= '<' ConstVector '>' --> Vector.
2751 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2752 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002753 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002754
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 SmallVector<Constant*, 16> Elts;
2756 LocTy FirstEltLoc = Lex.getLoc();
2757 if (ParseGlobalValueVector(Elts) ||
2758 (isPackedStruct &&
2759 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2760 ParseToken(lltok::greater, "expected end of constant"))
2761 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002762
Chris Lattnerac161bf2009-01-02 07:01:27 +00002763 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002764 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2765 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2766 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002767 ID.UIntVal = Elts.size();
2768 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002769 return false;
2770 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002771
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 if (Elts.empty())
2773 return Error(ID.Loc, "constant vector must not be empty");
2774
Duncan Sands9dff9be2010-02-15 16:12:20 +00002775 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002776 !Elts[0]->getType()->isFloatingPointTy() &&
2777 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002778 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002779 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002780
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 // Verify that all the vector elements have the same type.
2782 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2783 if (Elts[i]->getType() != Elts[0]->getType())
2784 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002785 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002786 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787
Chris Lattner69229312011-02-15 00:14:00 +00002788 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002789 ID.Kind = ValID::t_Constant;
2790 return false;
2791 }
2792 case lltok::lsquare: { // Array Constant
2793 Lex.Lex();
2794 SmallVector<Constant*, 16> Elts;
2795 LocTy FirstEltLoc = Lex.getLoc();
2796 if (ParseGlobalValueVector(Elts) ||
2797 ParseToken(lltok::rsquare, "expected end of array constant"))
2798 return true;
2799
2800 // Handle empty element.
2801 if (Elts.empty()) {
2802 // Use undef instead of an array because it's inconvenient to determine
2803 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002804 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 return false;
2806 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002809 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002810 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811
Owen Anderson4056ca92009-07-29 22:17:13 +00002812 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002813
Chris Lattnerac161bf2009-01-02 07:01:27 +00002814 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002815 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002816 if (Elts[i]->getType() != Elts[0]->getType())
2817 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002818 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002819 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002821
Jay Foad83be3612011-06-22 09:24:39 +00002822 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 ID.Kind = ValID::t_Constant;
2824 return false;
2825 }
2826 case lltok::kw_c: // c "foo"
2827 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002828 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2829 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002830 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2831 ID.Kind = ValID::t_Constant;
2832 return false;
2833
2834 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002835 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2836 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002837 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002838 Lex.Lex();
2839 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002840 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002841 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002842 ParseStringConstant(ID.StrVal) ||
2843 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 ParseToken(lltok::StringConstant, "expected constraint string"))
2845 return true;
2846 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002847 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002848 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 ID.Kind = ValID::t_InlineAsm;
2850 return false;
2851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002852
Chris Lattner3432c622009-10-28 03:39:23 +00002853 case lltok::kw_blockaddress: {
2854 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2855 Lex.Lex();
2856
2857 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002858
Chris Lattner3432c622009-10-28 03:39:23 +00002859 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2860 ParseValID(Fn) ||
2861 ParseToken(lltok::comma, "expected comma in block address expression")||
2862 ParseValID(Label) ||
2863 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2864 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002865
Chris Lattner3432c622009-10-28 03:39:23 +00002866 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2867 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002868 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002869 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002870
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002871 // Try to find the function (but skip it if it's forward-referenced).
2872 GlobalValue *GV = nullptr;
2873 if (Fn.Kind == ValID::t_GlobalID) {
2874 if (Fn.UIntVal < NumberedVals.size())
2875 GV = NumberedVals[Fn.UIntVal];
2876 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2877 GV = M->getNamedValue(Fn.StrVal);
2878 }
2879 Function *F = nullptr;
2880 if (GV) {
2881 // Confirm that it's actually a function with a definition.
2882 if (!isa<Function>(GV))
2883 return Error(Fn.Loc, "expected function name in blockaddress");
2884 F = cast<Function>(GV);
2885 if (F->isDeclaration())
2886 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2887 }
2888
2889 if (!F) {
2890 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002891 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002892 ForwardRefBlockAddresses.insert(std::make_pair(
2893 std::move(Fn),
2894 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002895 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2896 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002897 if (!FwdRef)
2898 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2899 GlobalValue::InternalLinkage, nullptr, "");
2900 ID.ConstantVal = FwdRef;
2901 ID.Kind = ValID::t_Constant;
2902 return false;
2903 }
2904
2905 // We found the function; now find the basic block. Don't use PFS, since we
2906 // might be inside a constant expression.
2907 BasicBlock *BB;
2908 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2909 if (Label.Kind == ValID::t_LocalID)
2910 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2911 else
2912 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2913 if (!BB)
2914 return Error(Label.Loc, "referenced value is not a basic block");
2915 } else {
2916 if (Label.Kind == ValID::t_LocalID)
2917 return Error(Label.Loc, "cannot take address of numeric label after "
2918 "the function is defined");
2919 BB = dyn_cast_or_null<BasicBlock>(
2920 F->getValueSymbolTable().lookup(Label.StrVal));
2921 if (!BB)
2922 return Error(Label.Loc, "referenced value is not a basic block");
2923 }
2924
2925 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002926 ID.Kind = ValID::t_Constant;
2927 return false;
2928 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002929
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 case lltok::kw_trunc:
2931 case lltok::kw_zext:
2932 case lltok::kw_sext:
2933 case lltok::kw_fptrunc:
2934 case lltok::kw_fpext:
2935 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002936 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002937 case lltok::kw_uitofp:
2938 case lltok::kw_sitofp:
2939 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002940 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002941 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002943 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002944 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002945 Constant *SrcVal;
2946 Lex.Lex();
2947 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2948 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002949 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950 ParseType(DestTy) ||
2951 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2952 return true;
2953 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2954 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002955 getTypeString(SrcVal->getType()) + "' to '" +
2956 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002957 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002958 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002959 ID.Kind = ValID::t_Constant;
2960 return false;
2961 }
2962 case lltok::kw_extractvalue: {
2963 Lex.Lex();
2964 Constant *Val;
2965 SmallVector<unsigned, 4> Indices;
2966 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2967 ParseGlobalTypeAndValue(Val) ||
2968 ParseIndexList(Indices) ||
2969 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2970 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002971
Chris Lattner392be582010-02-12 20:49:41 +00002972 if (!Val->getType()->isAggregateType())
2973 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002974 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002975 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002976 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002977 ID.Kind = ValID::t_Constant;
2978 return false;
2979 }
2980 case lltok::kw_insertvalue: {
2981 Lex.Lex();
2982 Constant *Val0, *Val1;
2983 SmallVector<unsigned, 4> Indices;
2984 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2985 ParseGlobalTypeAndValue(Val0) ||
2986 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2987 ParseGlobalTypeAndValue(Val1) ||
2988 ParseIndexList(Indices) ||
2989 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2990 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002991 if (!Val0->getType()->isAggregateType())
2992 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002993 Type *IndexedType =
2994 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2995 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002997 if (IndexedType != Val1->getType())
2998 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2999 getTypeString(Val1->getType()) +
3000 "' instead of '" + getTypeString(IndexedType) +
3001 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003002 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003003 ID.Kind = ValID::t_Constant;
3004 return false;
3005 }
3006 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003007 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 unsigned PredVal, Opc = Lex.getUIntVal();
3009 Constant *Val0, *Val1;
3010 Lex.Lex();
3011 if (ParseCmpPredicate(PredVal, Opc) ||
3012 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3013 ParseGlobalTypeAndValue(Val0) ||
3014 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3015 ParseGlobalTypeAndValue(Val1) ||
3016 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3017 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003018
Chris Lattnerac161bf2009-01-02 07:01:27 +00003019 if (Val0->getType() != Val1->getType())
3020 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003021
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003023
Chris Lattnerac161bf2009-01-02 07:01:27 +00003024 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003025 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003026 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003027 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003028 } else {
3029 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003030 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003031 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003033 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003034 }
3035 ID.Kind = ValID::t_Constant;
3036 return false;
3037 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003038
Chris Lattnerac161bf2009-01-02 07:01:27 +00003039 // Binary Operators.
3040 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003041 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003042 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003043 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003044 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003045 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 case lltok::kw_udiv:
3047 case lltok::kw_sdiv:
3048 case lltok::kw_fdiv:
3049 case lltok::kw_urem:
3050 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003051 case lltok::kw_frem:
3052 case lltok::kw_shl:
3053 case lltok::kw_lshr:
3054 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003055 bool NUW = false;
3056 bool NSW = false;
3057 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003058 unsigned Opc = Lex.getUIntVal();
3059 Constant *Val0, *Val1;
3060 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003061 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003062 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3063 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003064 if (EatIfPresent(lltok::kw_nuw))
3065 NUW = true;
3066 if (EatIfPresent(lltok::kw_nsw)) {
3067 NSW = true;
3068 if (EatIfPresent(lltok::kw_nuw))
3069 NUW = true;
3070 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003071 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3072 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003073 if (EatIfPresent(lltok::kw_exact))
3074 Exact = true;
3075 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003076 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3077 ParseGlobalTypeAndValue(Val0) ||
3078 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3079 ParseGlobalTypeAndValue(Val1) ||
3080 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3081 return true;
3082 if (Val0->getType() != Val1->getType())
3083 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003084 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003085 if (NUW)
3086 return Error(ModifierLoc, "nuw only applies to integer operations");
3087 if (NSW)
3088 return Error(ModifierLoc, "nsw only applies to integer operations");
3089 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003090 // Check that the type is valid for the operator.
3091 switch (Opc) {
3092 case Instruction::Add:
3093 case Instruction::Sub:
3094 case Instruction::Mul:
3095 case Instruction::UDiv:
3096 case Instruction::SDiv:
3097 case Instruction::URem:
3098 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003099 case Instruction::Shl:
3100 case Instruction::AShr:
3101 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003102 if (!Val0->getType()->isIntOrIntVectorTy())
3103 return Error(ID.Loc, "constexpr requires integer operands");
3104 break;
3105 case Instruction::FAdd:
3106 case Instruction::FSub:
3107 case Instruction::FMul:
3108 case Instruction::FDiv:
3109 case Instruction::FRem:
3110 if (!Val0->getType()->isFPOrFPVectorTy())
3111 return Error(ID.Loc, "constexpr requires fp operands");
3112 break;
3113 default: llvm_unreachable("Unknown binary operator!");
3114 }
Dan Gohman1b849082009-09-07 23:54:19 +00003115 unsigned Flags = 0;
3116 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3117 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003118 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003119 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003120 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003121 ID.Kind = ValID::t_Constant;
3122 return false;
3123 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003124
Chris Lattnerac161bf2009-01-02 07:01:27 +00003125 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003126 case lltok::kw_and:
3127 case lltok::kw_or:
3128 case lltok::kw_xor: {
3129 unsigned Opc = Lex.getUIntVal();
3130 Constant *Val0, *Val1;
3131 Lex.Lex();
3132 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3133 ParseGlobalTypeAndValue(Val0) ||
3134 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3135 ParseGlobalTypeAndValue(Val1) ||
3136 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3137 return true;
3138 if (Val0->getType() != Val1->getType())
3139 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003140 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003141 return Error(ID.Loc,
3142 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003143 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144 ID.Kind = ValID::t_Constant;
3145 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003146 }
3147
Chris Lattnerac161bf2009-01-02 07:01:27 +00003148 case lltok::kw_getelementptr:
3149 case lltok::kw_shufflevector:
3150 case lltok::kw_insertelement:
3151 case lltok::kw_extractelement:
3152 case lltok::kw_select: {
3153 unsigned Opc = Lex.getUIntVal();
3154 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003155 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003156 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003157 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003158
Dan Gohman1639c392009-07-27 21:53:46 +00003159 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003160 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003161
3162 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3163 return true;
3164
3165 LocTy ExplicitTypeLoc = Lex.getLoc();
3166 if (Opc == Instruction::GetElementPtr) {
3167 if (ParseType(Ty) ||
3168 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3169 return true;
3170 }
3171
3172 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003173 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3174 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003175
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003177 if (Elts.size() == 0 ||
3178 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003179 return Error(ID.Loc, "base of getelementptr must be a pointer");
3180
3181 Type *BaseType = Elts[0]->getType();
3182 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003183 if (Ty != BasePointerType->getElementType())
3184 return Error(
3185 ExplicitTypeLoc,
3186 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003187
Jay Foaded8db7d2011-07-21 14:31:17 +00003188 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003189 for (Constant *Val : Indices) {
3190 Type *ValTy = Val->getType();
3191 if (!ValTy->getScalarType()->isIntegerTy())
3192 return Error(ID.Loc, "getelementptr index must be an integer");
3193 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3194 return Error(ID.Loc, "getelementptr index type missmatch");
3195 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003196 unsigned ValNumEl = ValTy->getVectorNumElements();
3197 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003198 if (ValNumEl != PtrNumEl)
3199 return Error(
3200 ID.Loc,
3201 "getelementptr vector index has a wrong number of elements");
3202 }
3203 }
3204
Craig Toppere3dcce92015-08-01 22:20:21 +00003205 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003206 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003207 return Error(ID.Loc, "base element of getelementptr must be sized");
3208
David Blaikie4a2e73b2015-04-02 18:55:32 +00003209 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003210 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003211 ID.ConstantVal =
3212 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 } else if (Opc == Instruction::Select) {
3214 if (Elts.size() != 3)
3215 return Error(ID.Loc, "expected three operands to select");
3216 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3217 Elts[2]))
3218 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003219 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003220 } else if (Opc == Instruction::ShuffleVector) {
3221 if (Elts.size() != 3)
3222 return Error(ID.Loc, "expected three operands to shufflevector");
3223 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3224 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003225 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003226 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003227 } else if (Opc == Instruction::ExtractElement) {
3228 if (Elts.size() != 2)
3229 return Error(ID.Loc, "expected two operands to extractelement");
3230 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3231 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003232 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003233 } else {
3234 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3235 if (Elts.size() != 3)
3236 return Error(ID.Loc, "expected three operands to insertelement");
3237 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3238 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003239 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003240 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003242
Chris Lattnerac161bf2009-01-02 07:01:27 +00003243 ID.Kind = ValID::t_Constant;
3244 return false;
3245 }
3246 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003247
Chris Lattnerac161bf2009-01-02 07:01:27 +00003248 Lex.Lex();
3249 return false;
3250}
3251
3252/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003253bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003254 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003256 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003257 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003258 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003259 if (V && !(C = dyn_cast<Constant>(V)))
3260 return Error(ID.Loc, "global values must be constants");
3261 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003262}
3263
Victor Hernandez9d75c962010-01-11 22:31:58 +00003264bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003265 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003266 return ParseType(Ty) ||
3267 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003268}
3269
Rafael Espindola83a362c2015-01-06 22:55:16 +00003270bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003271 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003272
3273 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003274 if (!EatIfPresent(lltok::kw_comdat))
3275 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003276
3277 if (EatIfPresent(lltok::lparen)) {
3278 if (Lex.getKind() != lltok::ComdatVar)
3279 return TokError("expected comdat variable");
3280 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3281 Lex.Lex();
3282 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3283 return true;
3284 } else {
3285 if (GlobalName.empty())
3286 return TokError("comdat cannot be unnamed");
3287 C = getComdat(GlobalName, KwLoc);
3288 }
3289
David Majnemerdad0a642014-06-27 18:19:56 +00003290 return false;
3291}
3292
Victor Hernandez9d75c962010-01-11 22:31:58 +00003293/// ParseGlobalValueVector
3294/// ::= /*empty*/
3295/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003296bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003297 // Empty list.
3298 if (Lex.getKind() == lltok::rbrace ||
3299 Lex.getKind() == lltok::rsquare ||
3300 Lex.getKind() == lltok::greater ||
3301 Lex.getKind() == lltok::rparen)
3302 return false;
3303
3304 Constant *C;
3305 if (ParseGlobalTypeAndValue(C)) return true;
3306 Elts.push_back(C);
3307
3308 while (EatIfPresent(lltok::comma)) {
3309 if (ParseGlobalTypeAndValue(C)) return true;
3310 Elts.push_back(C);
3311 }
3312
3313 return false;
3314}
3315
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003316bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003317 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003318 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003319 return true;
3320
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003321 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003322 return false;
3323}
3324
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003325/// MDNode:
3326/// ::= !{ ... }
3327/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003328/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003329bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003330 if (Lex.getKind() == lltok::MetadataVar)
3331 return ParseSpecializedMDNode(N);
3332
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003333 return ParseToken(lltok::exclaim, "expected '!' here") ||
3334 ParseMDNodeTail(N);
3335}
3336
3337bool LLParser::ParseMDNodeTail(MDNode *&N) {
3338 // !{ ... }
3339 if (Lex.getKind() == lltok::lbrace)
3340 return ParseMDTuple(N);
3341
3342 // !42
3343 return ParseMDNodeID(N);
3344}
3345
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003346namespace {
3347
3348/// Structure to represent an optional metadata field.
3349template <class FieldTy> struct MDFieldImpl {
3350 typedef MDFieldImpl ImplTy;
3351 FieldTy Val;
3352 bool Seen;
3353
3354 void assign(FieldTy Val) {
3355 Seen = true;
3356 this->Val = std::move(Val);
3357 }
3358
3359 explicit MDFieldImpl(FieldTy Default)
3360 : Val(std::move(Default)), Seen(false) {}
3361};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003362
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003363struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3364 uint64_t Max;
3365
3366 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3367 : ImplTy(Default), Max(Max) {}
3368};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003369
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003370struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003371 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003372};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003373
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003374struct ColumnField : public MDUnsignedField {
3375 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3376};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003377
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003378struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003379 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003380 DwarfTagField(dwarf::Tag DefaultTag)
3381 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003382};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003383
Amjad Abouda9bcf162015-12-10 12:56:35 +00003384struct DwarfMacinfoTypeField : public MDUnsignedField {
3385 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3386 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3387 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3388};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003389
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003390struct DwarfAttEncodingField : public MDUnsignedField {
3391 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3392};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003393
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003394struct DwarfVirtualityField : public MDUnsignedField {
3395 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3396};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003397
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003398struct DwarfLangField : public MDUnsignedField {
3399 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3400};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003401
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003402struct DwarfCCField : public MDUnsignedField {
3403 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3404};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003405
Adrian Prantlb939a252016-03-31 23:56:58 +00003406struct EmissionKindField : public MDUnsignedField {
3407 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3408};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003409
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003410struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3411 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003412};
3413
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003414struct MDSignedField : public MDFieldImpl<int64_t> {
3415 int64_t Min;
3416 int64_t Max;
3417
3418 MDSignedField(int64_t Default = 0)
3419 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3420 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3421 : ImplTy(Default), Min(Min), Max(Max) {}
3422};
3423
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003424struct MDBoolField : public MDFieldImpl<bool> {
3425 MDBoolField(bool Default = false) : ImplTy(Default) {}
3426};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003427
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003428struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003429 bool AllowNull;
3430
3431 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003432};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003433
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003434struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3435 MDConstant() : ImplTy(nullptr) {}
3436};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003437
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003438struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003439 bool AllowEmpty;
3440 MDStringField(bool AllowEmpty = true)
3441 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003442};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003443
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003444struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3445 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3446};
3447
Eugene Zelenko1804a772016-08-25 00:45:04 +00003448} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003449
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003450namespace llvm {
3451
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003452template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003453bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003454 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003455 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3456 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003457
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003458 auto &U = Lex.getAPSIntVal();
3459 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003460 return TokError("value for '" + Name + "' too large, limit is " +
3461 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003462 Result.assign(U.getZExtValue());
3463 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003464 Lex.Lex();
3465 return false;
3466}
3467
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003468template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003469bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3470 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3471}
3472template <>
3473bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3474 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3475}
3476
3477template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003478bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3479 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003480 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003481
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003482 if (Lex.getKind() != lltok::DwarfTag)
3483 return TokError("expected DWARF tag");
3484
3485 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3486 if (Tag == dwarf::DW_TAG_invalid)
3487 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003488 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003489
3490 Result.assign(Tag);
3491 Lex.Lex();
3492 return false;
3493}
3494
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003495template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003496bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003497 DwarfMacinfoTypeField &Result) {
3498 if (Lex.getKind() == lltok::APSInt)
3499 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3500
3501 if (Lex.getKind() != lltok::DwarfMacinfo)
3502 return TokError("expected DWARF macinfo type");
3503
3504 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3505 if (Macinfo == dwarf::DW_MACINFO_invalid)
3506 return TokError(
3507 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3508 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3509
3510 Result.assign(Macinfo);
3511 Lex.Lex();
3512 return false;
3513}
3514
3515template <>
3516bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003517 DwarfVirtualityField &Result) {
3518 if (Lex.getKind() == lltok::APSInt)
3519 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3520
3521 if (Lex.getKind() != lltok::DwarfVirtuality)
3522 return TokError("expected DWARF virtuality code");
3523
3524 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003525 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003526 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3527 Lex.getStrVal() + "'");
3528 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3529 Result.assign(Virtuality);
3530 Lex.Lex();
3531 return false;
3532}
3533
3534template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003535bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3536 if (Lex.getKind() == lltok::APSInt)
3537 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3538
3539 if (Lex.getKind() != lltok::DwarfLang)
3540 return TokError("expected DWARF language");
3541
3542 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3543 if (!Lang)
3544 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3545 "'");
3546 assert(Lang <= Result.Max && "Expected valid DWARF language");
3547 Result.assign(Lang);
3548 Lex.Lex();
3549 return false;
3550}
3551
3552template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003553bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3554 if (Lex.getKind() == lltok::APSInt)
3555 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3556
3557 if (Lex.getKind() != lltok::DwarfCC)
3558 return TokError("expected DWARF calling convention");
3559
3560 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3561 if (!CC)
3562 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3563 "'");
3564 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3565 Result.assign(CC);
3566 Lex.Lex();
3567 return false;
3568}
3569
3570template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003571bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3572 if (Lex.getKind() == lltok::APSInt)
3573 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3574
3575 if (Lex.getKind() != lltok::EmissionKind)
3576 return TokError("expected emission kind");
3577
3578 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3579 if (!Kind)
3580 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3581 "'");
3582 assert(*Kind <= Result.Max && "Expected valid emission kind");
3583 Result.assign(*Kind);
3584 Lex.Lex();
3585 return false;
3586}
3587
3588template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003589bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003590 DwarfAttEncodingField &Result) {
3591 if (Lex.getKind() == lltok::APSInt)
3592 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3593
3594 if (Lex.getKind() != lltok::DwarfAttEncoding)
3595 return TokError("expected DWARF type attribute encoding");
3596
3597 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3598 if (!Encoding)
3599 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3600 Lex.getStrVal() + "'");
3601 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3602 Result.assign(Encoding);
3603 Lex.Lex();
3604 return false;
3605}
3606
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003607/// DIFlagField
3608/// ::= uint32
3609/// ::= DIFlagVector
3610/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3611template <>
3612bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003613
3614 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003615 auto parseFlag = [&](DINode::DIFlags &Val) {
3616 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3617 uint32_t TempVal = static_cast<uint32_t>(Val);
3618 bool Res = ParseUInt32(TempVal);
3619 Val = static_cast<DINode::DIFlags>(TempVal);
3620 return Res;
3621 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003622
3623 if (Lex.getKind() != lltok::DIFlag)
3624 return TokError("expected debug info flag");
3625
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003626 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003627 if (!Val)
3628 return TokError(Twine("invalid debug info flag flag '") +
3629 Lex.getStrVal() + "'");
3630 Lex.Lex();
3631 return false;
3632 };
3633
3634 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003635 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003636 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003637 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003638 if (parseFlag(Val))
3639 return true;
3640 Combined |= Val;
3641 } while (EatIfPresent(lltok::bar));
3642
3643 Result.assign(Combined);
3644 return false;
3645}
3646
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003647template <>
3648bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003649 MDSignedField &Result) {
3650 if (Lex.getKind() != lltok::APSInt)
3651 return TokError("expected signed integer");
3652
3653 auto &S = Lex.getAPSIntVal();
3654 if (S < Result.Min)
3655 return TokError("value for '" + Name + "' too small, limit is " +
3656 Twine(Result.Min));
3657 if (S > Result.Max)
3658 return TokError("value for '" + Name + "' too large, limit is " +
3659 Twine(Result.Max));
3660 Result.assign(S.getExtValue());
3661 assert(Result.Val >= Result.Min && "Expected value in range");
3662 assert(Result.Val <= Result.Max && "Expected value in range");
3663 Lex.Lex();
3664 return false;
3665}
3666
3667template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003668bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3669 switch (Lex.getKind()) {
3670 default:
3671 return TokError("expected 'true' or 'false'");
3672 case lltok::kw_true:
3673 Result.assign(true);
3674 break;
3675 case lltok::kw_false:
3676 Result.assign(false);
3677 break;
3678 }
3679 Lex.Lex();
3680 return false;
3681}
3682
3683template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003684bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003685 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003686 if (!Result.AllowNull)
3687 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003688 Lex.Lex();
3689 Result.assign(nullptr);
3690 return false;
3691 }
3692
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003693 Metadata *MD;
3694 if (ParseMetadata(MD, nullptr))
3695 return true;
3696
3697 Result.assign(MD);
3698 return false;
3699}
3700
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003701template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003702bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3703 Metadata *MD;
3704 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3705 return true;
3706
3707 Result.assign(cast<ConstantAsMetadata>(MD));
3708 return false;
3709}
3710
3711template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003712bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003713 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003714 std::string S;
3715 if (ParseStringConstant(S))
3716 return true;
3717
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003718 if (!Result.AllowEmpty && S.empty())
3719 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3720
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003721 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003722 return false;
3723}
3724
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003725template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003726bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3727 SmallVector<Metadata *, 4> MDs;
3728 if (ParseMDNodeVector(MDs))
3729 return true;
3730
3731 Result.assign(std::move(MDs));
3732 return false;
3733}
3734
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003735} // end namespace llvm
3736
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003737template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003738bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003739 do {
3740 if (Lex.getKind() != lltok::LabelStr)
3741 return TokError("expected field label here");
3742
3743 if (parseField())
3744 return true;
3745 } while (EatIfPresent(lltok::comma));
3746
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003747 return false;
3748}
3749
3750template <class ParserTy>
3751bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3752 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3753 Lex.Lex();
3754
3755 if (ParseToken(lltok::lparen, "expected '(' here"))
3756 return true;
3757 if (Lex.getKind() != lltok::rparen)
3758 if (ParseMDFieldsImplBody(parseField))
3759 return true;
3760
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003761 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003762 return ParseToken(lltok::rparen, "expected ')' here");
3763}
3764
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003765template <class FieldTy>
3766bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3767 if (Result.Seen)
3768 return TokError("field '" + Name + "' cannot be specified more than once");
3769
3770 LocTy Loc = Lex.getLoc();
3771 Lex.Lex();
3772 return ParseMDField(Loc, Name, Result);
3773}
3774
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003775bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3776 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003777
3778#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003779 if (Lex.getStrVal() == #CLASS) \
3780 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003781#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003782
3783 return TokError("expected metadata type");
3784}
3785
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003786#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3787#define NOP_FIELD(NAME, TYPE, INIT)
3788#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3789 if (!NAME.Seen) \
3790 return Error(ClosingLoc, "missing required field '" #NAME "'");
3791#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003792 if (Lex.getStrVal() == #NAME) \
3793 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003794#define PARSE_MD_FIELDS() \
3795 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3796 do { \
3797 LocTy ClosingLoc; \
3798 if (ParseMDFieldsImpl([&]() -> bool { \
3799 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3800 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3801 }, ClosingLoc)) \
3802 return true; \
3803 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3804 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003805#define GET_OR_DISTINCT(CLASS, ARGS) \
3806 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003807
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003808/// ParseDILocationFields:
3809/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3810bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003811#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003812 OPTIONAL(line, LineField, ); \
3813 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003814 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003815 OPTIONAL(inlinedAt, MDField, );
3816 PARSE_MD_FIELDS();
3817#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003818
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003819 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003820 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003821 return false;
3822}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003823
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003824/// ParseGenericDINode:
3825/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3826bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003827#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003828 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003829 OPTIONAL(header, MDStringField, ); \
3830 OPTIONAL(operands, MDFieldList, );
3831 PARSE_MD_FIELDS();
3832#undef VISIT_MD_FIELDS
3833
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003834 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003835 (Context, tag.Val, header.Val, operands.Val));
3836 return false;
3837}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003838
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003839/// ParseDISubrange:
3840/// ::= !DISubrange(count: 30, lowerBound: 2)
3841bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003842#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003843 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003844 OPTIONAL(lowerBound, MDSignedField, );
3845 PARSE_MD_FIELDS();
3846#undef VISIT_MD_FIELDS
3847
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003848 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003849 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003850}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003852/// ParseDIEnumerator:
3853/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3854bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003855#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003856 REQUIRED(name, MDStringField, ); \
3857 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003858 PARSE_MD_FIELDS();
3859#undef VISIT_MD_FIELDS
3860
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003861 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003862 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003863}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003864
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003865/// ParseDIBasicType:
3866/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3867bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003868#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003869 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003870 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003871 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3872 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003873 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003874 PARSE_MD_FIELDS();
3875#undef VISIT_MD_FIELDS
3876
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003877 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003878 align.Val, encoding.Val));
3879 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003880}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003881
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003882/// ParseDIDerivedType:
3883/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003884/// line: 7, scope: !1, baseType: !2, size: 32,
3885/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003886bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003887#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3888 REQUIRED(tag, DwarfTagField, ); \
3889 OPTIONAL(name, MDStringField, ); \
3890 OPTIONAL(file, MDField, ); \
3891 OPTIONAL(line, LineField, ); \
3892 OPTIONAL(scope, MDField, ); \
3893 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003894 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3895 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3896 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003897 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003898 OPTIONAL(extraData, MDField, );
3899 PARSE_MD_FIELDS();
3900#undef VISIT_MD_FIELDS
3901
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003902 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003903 (Context, tag.Val, name.Val, file.Val, line.Val,
3904 scope.Val, baseType.Val, size.Val, align.Val,
3905 offset.Val, flags.Val, extraData.Val));
3906 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003907}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003908
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003909bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003910#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3911 REQUIRED(tag, DwarfTagField, ); \
3912 OPTIONAL(name, MDStringField, ); \
3913 OPTIONAL(file, MDField, ); \
3914 OPTIONAL(line, LineField, ); \
3915 OPTIONAL(scope, MDField, ); \
3916 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003917 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3918 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3919 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003920 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003921 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003922 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003923 OPTIONAL(vtableHolder, MDField, ); \
3924 OPTIONAL(templateParams, MDField, ); \
3925 OPTIONAL(identifier, MDStringField, );
3926 PARSE_MD_FIELDS();
3927#undef VISIT_MD_FIELDS
3928
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003929 // If this has an identifier try to build an ODR type.
3930 if (identifier.Val)
3931 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003932 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3933 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3934 elements.Val, runtimeLang.Val, vtableHolder.Val,
3935 templateParams.Val)) {
3936 Result = CT;
3937 return false;
3938 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003939
3940 // Create a new node, and save it in the context if it belongs in the type
3941 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003942 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003943 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003944 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3945 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3946 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3947 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003948}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003949
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003950bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003951#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003952 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003953 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003954 REQUIRED(types, MDField, );
3955 PARSE_MD_FIELDS();
3956#undef VISIT_MD_FIELDS
3957
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003958 Result = GET_OR_DISTINCT(DISubroutineType,
3959 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003960 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003961}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003962
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003963/// ParseDIFileType:
3964/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3965bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003966#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3967 REQUIRED(filename, MDStringField, ); \
3968 REQUIRED(directory, MDStringField, );
3969 PARSE_MD_FIELDS();
3970#undef VISIT_MD_FIELDS
3971
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003972 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003973 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003974}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003975
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003976/// ParseDICompileUnit:
3977/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003978/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003979/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003980/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003981/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003982bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003983 if (!IsDistinct)
3984 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3985
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003986#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3987 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003988 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003989 OPTIONAL(producer, MDStringField, ); \
3990 OPTIONAL(isOptimized, MDBoolField, ); \
3991 OPTIONAL(flags, MDStringField, ); \
3992 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3993 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003994 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003995 OPTIONAL(enums, MDField, ); \
3996 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003997 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003998 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003999 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004000 OPTIONAL(dwoId, MDUnsignedField, ); \
4001 OPTIONAL(splitDebugInlining, MDBoolField, = true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004002 PARSE_MD_FIELDS();
4003#undef VISIT_MD_FIELDS
4004
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004005 Result = DICompileUnit::getDistinct(
4006 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4007 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004008 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4009 splitDebugInlining.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004010 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004011}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004012
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004013/// ParseDISubprogram:
4014/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004015/// file: !1, line: 7, type: !2, isLocal: false,
4016/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004017/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004018/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004019/// isOptimized: false, templateParams: !4, declaration: !5,
4020/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004021bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004022 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004023#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4024 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004025 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004026 OPTIONAL(linkageName, MDStringField, ); \
4027 OPTIONAL(file, MDField, ); \
4028 OPTIONAL(line, LineField, ); \
4029 OPTIONAL(type, MDField, ); \
4030 OPTIONAL(isLocal, MDBoolField, ); \
4031 OPTIONAL(isDefinition, MDBoolField, (true)); \
4032 OPTIONAL(scopeLine, LineField, ); \
4033 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004034 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004035 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004036 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004037 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004038 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004039 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004040 OPTIONAL(templateParams, MDField, ); \
4041 OPTIONAL(declaration, MDField, ); \
4042 OPTIONAL(variables, MDField, );
4043 PARSE_MD_FIELDS();
4044#undef VISIT_MD_FIELDS
4045
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004046 if (isDefinition.Val && !IsDistinct)
4047 return Lex.Error(
4048 Loc,
4049 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4050
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004051 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004052 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4053 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4054 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004055 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4056 isOptimized.Val, unit.Val, templateParams.Val,
4057 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004058 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004059}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004060
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004061/// ParseDILexicalBlock:
4062/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4063bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004064#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004065 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004066 OPTIONAL(file, MDField, ); \
4067 OPTIONAL(line, LineField, ); \
4068 OPTIONAL(column, ColumnField, );
4069 PARSE_MD_FIELDS();
4070#undef VISIT_MD_FIELDS
4071
4072 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004073 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004074 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004075}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004076
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004077/// ParseDILexicalBlockFile:
4078/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4079bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004080#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004081 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004082 OPTIONAL(file, MDField, ); \
4083 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4084 PARSE_MD_FIELDS();
4085#undef VISIT_MD_FIELDS
4086
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004087 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004088 (Context, scope.Val, file.Val, discriminator.Val));
4089 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004090}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004091
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004092/// ParseDINamespace:
4093/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4094bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004095#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4096 REQUIRED(scope, MDField, ); \
4097 OPTIONAL(file, MDField, ); \
4098 OPTIONAL(name, MDStringField, ); \
4099 OPTIONAL(line, LineField, );
4100 PARSE_MD_FIELDS();
4101#undef VISIT_MD_FIELDS
4102
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004103 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004104 (Context, scope.Val, file.Val, name.Val, line.Val));
4105 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004106}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004107
Amjad Abouda9bcf162015-12-10 12:56:35 +00004108/// ParseDIMacro:
4109/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4110bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4111#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4112 REQUIRED(type, DwarfMacinfoTypeField, ); \
4113 REQUIRED(line, LineField, ); \
4114 REQUIRED(name, MDStringField, ); \
4115 OPTIONAL(value, MDStringField, );
4116 PARSE_MD_FIELDS();
4117#undef VISIT_MD_FIELDS
4118
4119 Result = GET_OR_DISTINCT(DIMacro,
4120 (Context, type.Val, line.Val, name.Val, value.Val));
4121 return false;
4122}
4123
4124/// ParseDIMacroFile:
4125/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4126bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4127#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4128 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4129 REQUIRED(line, LineField, ); \
4130 REQUIRED(file, MDField, ); \
4131 OPTIONAL(nodes, MDField, );
4132 PARSE_MD_FIELDS();
4133#undef VISIT_MD_FIELDS
4134
4135 Result = GET_OR_DISTINCT(DIMacroFile,
4136 (Context, type.Val, line.Val, file.Val, nodes.Val));
4137 return false;
4138}
4139
Adrian Prantlab1243f2015-06-29 23:03:47 +00004140/// ParseDIModule:
4141/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4142/// includePath: "/usr/include", isysroot: "/")
4143bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4144#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4145 REQUIRED(scope, MDField, ); \
4146 REQUIRED(name, MDStringField, ); \
4147 OPTIONAL(configMacros, MDStringField, ); \
4148 OPTIONAL(includePath, MDStringField, ); \
4149 OPTIONAL(isysroot, MDStringField, );
4150 PARSE_MD_FIELDS();
4151#undef VISIT_MD_FIELDS
4152
4153 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4154 configMacros.Val, includePath.Val, isysroot.Val));
4155 return false;
4156}
4157
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004158/// ParseDITemplateTypeParameter:
4159/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4160bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004161#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004162 OPTIONAL(name, MDStringField, ); \
4163 REQUIRED(type, MDField, );
4164 PARSE_MD_FIELDS();
4165#undef VISIT_MD_FIELDS
4166
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004167 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004168 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004169 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004170}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004171
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004172/// ParseDITemplateValueParameter:
4173/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004174/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004175bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004176#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004177 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004178 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004179 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004180 REQUIRED(value, MDField, );
4181 PARSE_MD_FIELDS();
4182#undef VISIT_MD_FIELDS
4183
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004184 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004185 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004186 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004187}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004188
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004189/// ParseDIGlobalVariable:
4190/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004191/// file: !1, line: 7, type: !2, isLocal: false,
4192/// isDefinition: true, variable: i32* @foo,
4193/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004194bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004196 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004197 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004198 OPTIONAL(linkageName, MDStringField, ); \
4199 OPTIONAL(file, MDField, ); \
4200 OPTIONAL(line, LineField, ); \
4201 OPTIONAL(type, MDField, ); \
4202 OPTIONAL(isLocal, MDBoolField, ); \
4203 OPTIONAL(isDefinition, MDBoolField, (true)); \
4204 OPTIONAL(variable, MDConstant, ); \
4205 OPTIONAL(declaration, MDField, );
4206 PARSE_MD_FIELDS();
4207#undef VISIT_MD_FIELDS
4208
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004209 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004210 (Context, scope.Val, name.Val, linkageName.Val,
4211 file.Val, line.Val, type.Val, isLocal.Val,
4212 isDefinition.Val, variable.Val, declaration.Val));
4213 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004214}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004215
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004216/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004217/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4218/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4219/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004220/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004221bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004222#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004223 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004224 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004225 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004226 OPTIONAL(file, MDField, ); \
4227 OPTIONAL(line, LineField, ); \
4228 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004229 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004230 PARSE_MD_FIELDS();
4231#undef VISIT_MD_FIELDS
4232
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004233 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004234 (Context, scope.Val, name.Val, file.Val, line.Val,
4235 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004236 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004237}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004238
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004239/// ParseDIExpression:
4240/// ::= !DIExpression(0, 7, -1)
4241bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004242 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4243 Lex.Lex();
4244
4245 if (ParseToken(lltok::lparen, "expected '(' here"))
4246 return true;
4247
4248 SmallVector<uint64_t, 8> Elements;
4249 if (Lex.getKind() != lltok::rparen)
4250 do {
4251 if (Lex.getKind() == lltok::DwarfOp) {
4252 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4253 Lex.Lex();
4254 Elements.push_back(Op);
4255 continue;
4256 }
4257 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4258 }
4259
4260 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4261 return TokError("expected unsigned integer");
4262
4263 auto &U = Lex.getAPSIntVal();
4264 if (U.ugt(UINT64_MAX))
4265 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4266 Elements.push_back(U.getZExtValue());
4267 Lex.Lex();
4268 } while (EatIfPresent(lltok::comma));
4269
4270 if (ParseToken(lltok::rparen, "expected ')' here"))
4271 return true;
4272
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004273 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004274 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004275}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004276
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004277/// ParseDIObjCProperty:
4278/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004279/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004280bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004281#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004282 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004283 OPTIONAL(file, MDField, ); \
4284 OPTIONAL(line, LineField, ); \
4285 OPTIONAL(setter, MDStringField, ); \
4286 OPTIONAL(getter, MDStringField, ); \
4287 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4288 OPTIONAL(type, MDField, );
4289 PARSE_MD_FIELDS();
4290#undef VISIT_MD_FIELDS
4291
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004292 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004293 (Context, name.Val, file.Val, line.Val, setter.Val,
4294 getter.Val, attributes.Val, type.Val));
4295 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004296}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004297
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004298/// ParseDIImportedEntity:
4299/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004300/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004301bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004302#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4303 REQUIRED(tag, DwarfTagField, ); \
4304 REQUIRED(scope, MDField, ); \
4305 OPTIONAL(entity, MDField, ); \
4306 OPTIONAL(line, LineField, ); \
4307 OPTIONAL(name, MDStringField, );
4308 PARSE_MD_FIELDS();
4309#undef VISIT_MD_FIELDS
4310
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004311 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004312 entity.Val, line.Val, name.Val));
4313 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004314}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004315
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004316#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004317#undef NOP_FIELD
4318#undef REQUIRE_FIELD
4319#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004320
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004321/// ParseMetadataAsValue
4322/// ::= metadata i32 %local
4323/// ::= metadata i32 @global
4324/// ::= metadata i32 7
4325/// ::= metadata !0
4326/// ::= metadata !{...}
4327/// ::= metadata !"string"
4328bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4329 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004330 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004331 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004332 return true;
4333
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004334 V = MetadataAsValue::get(Context, MD);
4335 return false;
4336}
4337
4338/// ParseValueAsMetadata
4339/// ::= i32 %local
4340/// ::= i32 @global
4341/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004342bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4343 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004344 Type *Ty;
4345 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004346 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004347 return true;
4348 if (Ty->isMetadataTy())
4349 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4350
4351 Value *V;
4352 if (ParseValue(Ty, V, PFS))
4353 return true;
4354
4355 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004356 return false;
4357}
4358
4359/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004360/// ::= i32 %local
4361/// ::= i32 @global
4362/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004363/// ::= !42
4364/// ::= !{...}
4365/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004366/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004367bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004368 if (Lex.getKind() == lltok::MetadataVar) {
4369 MDNode *N;
4370 if (ParseSpecializedMDNode(N))
4371 return true;
4372 MD = N;
4373 return false;
4374 }
4375
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004376 // ValueAsMetadata:
4377 // <type> <value>
4378 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004379 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004380
4381 // '!'.
4382 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4383 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004384
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004385 // MDString:
4386 // ::= '!' STRINGCONSTANT
4387 if (Lex.getKind() == lltok::StringConstant) {
4388 MDString *S;
4389 if (ParseMDString(S))
4390 return true;
4391 MD = S;
4392 return false;
4393 }
4394
Dan Gohman8939ba332010-07-14 18:26:50 +00004395 // MDNode:
4396 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004397 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004398 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004399 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004400 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004401 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004402 return false;
4403}
4404
Victor Hernandez9d75c962010-01-11 22:31:58 +00004405//===----------------------------------------------------------------------===//
4406// Function Parsing.
4407//===----------------------------------------------------------------------===//
4408
Chris Lattner229907c2011-07-18 04:54:35 +00004409bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004410 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004411 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004413
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004415 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004416 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004417 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004418 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004419 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004420 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004421 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004422 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004423 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004424 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004425 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004426 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4427 (ID.UIntVal >> 1) & 1,
4428 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004429 return false;
4430 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004431 case ValID::t_GlobalName:
4432 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004433 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004434 case ValID::t_GlobalID:
4435 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004436 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004437 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004438 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004440 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004441 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004442 return false;
4443 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004444 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004445 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4446 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004447
Dan Gohman518cda42011-12-17 00:04:22 +00004448 // The lexer has no type info, so builds all half, float, and double FP
4449 // constants as double. Fix this here. Long double does not need this.
4450 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004451 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004452 if (Ty->isHalfTy())
4453 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4454 &Ignored);
4455 else if (Ty->isFloatTy())
4456 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4457 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004458 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004459 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004460
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004461 if (V->getType() != Ty)
4462 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004463 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004464
Chris Lattnerac161bf2009-01-02 07:01:27 +00004465 return false;
4466 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004467 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004468 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004469 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004470 return false;
4471 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004472 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004473 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004474 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004475 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004476 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004477 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004478 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004479 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004480 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004481 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004483 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004484 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004485 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004486 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004488 case ValID::t_None:
4489 if (!Ty->isTokenTy())
4490 return Error(ID.Loc, "invalid type for none constant");
4491 V = Constant::getNullValue(Ty);
4492 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004493 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004494 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004496
Chris Lattnerac161bf2009-01-02 07:01:27 +00004497 V = ID.ConstantVal;
4498 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004499 case ValID::t_ConstantStruct:
4500 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004501 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004502 if (ST->getNumElements() != ID.UIntVal)
4503 return Error(ID.Loc,
4504 "initializer with struct type has wrong # elements");
4505 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4506 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004507
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004508 // Verify that the elements are compatible with the structtype.
4509 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4510 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4511 return Error(ID.Loc, "element " + Twine(i) +
4512 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004513
David Blaikieadbda4b2015-08-03 20:08:41 +00004514 V = ConstantStruct::get(
4515 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004516 } else
4517 return Error(ID.Loc, "constant expression type mismatch");
4518 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004519 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004520 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004521}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004522
Alex Lorenzd2255952015-07-17 22:07:03 +00004523bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4524 C = nullptr;
4525 ValID ID;
4526 auto Loc = Lex.getLoc();
4527 if (ParseValID(ID, /*PFS=*/nullptr))
4528 return true;
4529 switch (ID.Kind) {
4530 case ValID::t_APSInt:
4531 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004532 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004533 case ValID::t_Constant:
4534 case ValID::t_ConstantStruct:
4535 case ValID::t_PackedConstantStruct: {
4536 Value *V;
4537 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4538 return true;
4539 assert(isa<Constant>(V) && "Expected a constant value");
4540 C = cast<Constant>(V);
4541 return false;
4542 }
4543 default:
4544 return Error(Loc, "expected a constant value");
4545 }
4546}
4547
David Majnemer8a1c45d2015-12-12 05:38:55 +00004548bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004549 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004551 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004552}
4553
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004554bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004555 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004556 return ParseType(Ty) ||
4557 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004558}
4559
Chris Lattner3ed871f2009-10-27 19:13:16 +00004560bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4561 PerFunctionState &PFS) {
4562 Value *V;
4563 Loc = Lex.getLoc();
4564 if (ParseTypeAndValue(V, PFS)) return true;
4565 if (!isa<BasicBlock>(V))
4566 return Error(Loc, "expected a basic block");
4567 BB = cast<BasicBlock>(V);
4568 return false;
4569}
4570
Chris Lattnerac161bf2009-01-02 07:01:27 +00004571/// FunctionHeader
4572/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004573/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004574/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004575bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4576 // Parse the linkage.
4577 LocTy LinkageLoc = Lex.getLoc();
4578 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004579
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004580 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004581 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004582 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004583 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004584 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004585 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004586 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004587 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4588 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004589 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590 return true;
4591
4592 // Verify that the linkage is ok.
4593 switch ((GlobalValue::LinkageTypes)Linkage) {
4594 case GlobalValue::ExternalLinkage:
4595 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004596 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597 if (isDefine)
4598 return Error(LinkageLoc, "invalid linkage for function definition");
4599 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004600 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004602 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004603 case GlobalValue::LinkOnceAnyLinkage:
4604 case GlobalValue::LinkOnceODRLinkage:
4605 case GlobalValue::WeakAnyLinkage:
4606 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004607 if (!isDefine)
4608 return Error(LinkageLoc, "invalid linkage for function declaration");
4609 break;
4610 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004611 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004612 return Error(LinkageLoc, "invalid function linkage type");
4613 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004614
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004615 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4616 return Error(LinkageLoc,
4617 "symbol with local linkage must have default visibility");
4618
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004619 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004620 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004621
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004623
4624 std::string FunctionName;
4625 if (Lex.getKind() == lltok::GlobalVar) {
4626 FunctionName = Lex.getStrVal();
4627 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4628 unsigned NameID = Lex.getUIntVal();
4629
4630 if (NameID != NumberedVals.size())
4631 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004632 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004633 } else {
4634 return TokError("expected function name");
4635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Chris Lattner3822f632009-01-02 08:05:26 +00004637 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004638
Chris Lattner3822f632009-01-02 08:05:26 +00004639 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004640 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004641
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004642 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004644 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004645 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004646 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004649 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004650 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004651 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004652 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004653 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004654 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004655 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004656
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004657 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004658 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004659 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004660 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004661 (EatIfPresent(lltok::kw_section) &&
4662 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004663 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004664 ParseOptionalAlignment(Alignment) ||
4665 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004666 ParseStringConstant(GC)) ||
4667 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004668 ParseGlobalTypeAndValue(Prefix)) ||
4669 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004670 ParseGlobalTypeAndValue(Prologue)) ||
4671 (EatIfPresent(lltok::kw_personality) &&
4672 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004673 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674
Michael Gottesman41748d72013-06-27 00:25:01 +00004675 if (FuncAttrs.contains(Attribute::Builtin))
4676 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004677
Chris Lattnerac161bf2009-01-02 07:01:27 +00004678 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004679 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004680 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004681 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004682 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004683
Chris Lattnerac161bf2009-01-02 07:01:27 +00004684 // Okay, if we got here, the function is syntactically valid. Convert types
4685 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004686 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004687 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004688
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004689 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004690 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4691 AttributeSet::ReturnIndex,
4692 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004693
Chris Lattnerac161bf2009-01-02 07:01:27 +00004694 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004695 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004696 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4697 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004698 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4699 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 }
4701
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004702 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004703 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4704 AttributeSet::FunctionIndex,
4705 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004706
Bill Wendlinge94d8432012-12-07 23:16:57 +00004707 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004708
Bill Wendling749a43d2012-12-30 13:50:49 +00004709 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004710 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4711
Chris Lattner229907c2011-07-18 04:54:35 +00004712 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004713 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004714 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004715
Craig Topper2617dcc2014-04-15 06:32:26 +00004716 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004717 if (!FunctionName.empty()) {
4718 // If this was a definition of a forward reference, remove the definition
4719 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004720 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004721 if (FRVI != ForwardRefVals.end()) {
4722 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004723 if (!Fn)
4724 return Error(FRVI->second.second, "invalid forward reference to "
4725 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004726 if (Fn->getType() != PFT)
4727 return Error(FRVI->second.second, "invalid forward reference to "
4728 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004729
Chris Lattnerac161bf2009-01-02 07:01:27 +00004730 ForwardRefVals.erase(FRVI);
4731 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004732 // Reject redefinitions.
4733 return Error(NameLoc, "invalid redefinition of function '" +
4734 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004735 } else if (M->getNamedValue(FunctionName)) {
4736 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004738
Dan Gohman399d6ae2009-08-29 23:37:49 +00004739 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004740 // If this is a definition of a forward referenced function, make sure the
4741 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004742 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004743 if (I != ForwardRefValIDs.end()) {
4744 Fn = cast<Function>(I->second.first);
4745 if (Fn->getType() != PFT)
4746 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004747 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004748 ForwardRefValIDs.erase(I);
4749 }
4750 }
4751
Craig Topper2617dcc2014-04-15 06:32:26 +00004752 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004753 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4754 else // Move the forward-reference to the correct spot in the module.
4755 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4756
4757 if (FunctionName.empty())
4758 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004759
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4761 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004762 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763 Fn->setCallingConv(CC);
4764 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004765 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004766 Fn->setAlignment(Alignment);
4767 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004768 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004769 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004770 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004771 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004772 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004773 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004774
Chris Lattnerac161bf2009-01-02 07:01:27 +00004775 // Add all of the arguments we parsed to the function.
4776 Function::arg_iterator ArgIt = Fn->arg_begin();
4777 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4778 // If the argument has a name, insert it into the argument symbol table.
4779 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004780
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 // Set the name, if it conflicted, it will be auto-renamed.
4782 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004783
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004784 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4786 ArgList[i].Name + "'");
4787 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004788
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004789 if (isDefine)
4790 return false;
4791
Robin Morisset039781e2014-08-29 21:53:01 +00004792 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004793 ValID ID;
4794 if (FunctionName.empty()) {
4795 ID.Kind = ValID::t_GlobalID;
4796 ID.UIntVal = NumberedVals.size() - 1;
4797 } else {
4798 ID.Kind = ValID::t_GlobalName;
4799 ID.StrVal = FunctionName;
4800 }
4801 auto Blocks = ForwardRefBlockAddresses.find(ID);
4802 if (Blocks != ForwardRefBlockAddresses.end())
4803 return Error(Blocks->first.Loc,
4804 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805 return false;
4806}
4807
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004808bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4809 ValID ID;
4810 if (FunctionNumber == -1) {
4811 ID.Kind = ValID::t_GlobalName;
4812 ID.StrVal = F.getName();
4813 } else {
4814 ID.Kind = ValID::t_GlobalID;
4815 ID.UIntVal = FunctionNumber;
4816 }
4817
4818 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4819 if (Blocks == P.ForwardRefBlockAddresses.end())
4820 return false;
4821
4822 for (const auto &I : Blocks->second) {
4823 const ValID &BBID = I.first;
4824 GlobalValue *GV = I.second;
4825
4826 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4827 "Expected local id or name");
4828 BasicBlock *BB;
4829 if (BBID.Kind == ValID::t_LocalName)
4830 BB = GetBB(BBID.StrVal, BBID.Loc);
4831 else
4832 BB = GetBB(BBID.UIntVal, BBID.Loc);
4833 if (!BB)
4834 return P.Error(BBID.Loc, "referenced value is not a basic block");
4835
4836 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4837 GV->eraseFromParent();
4838 }
4839
4840 P.ForwardRefBlockAddresses.erase(Blocks);
4841 return false;
4842}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004843
4844/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004845/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004846bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004847 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 return TokError("expected '{' in function body");
4849 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004850
Chris Lattner3432c622009-10-28 03:39:23 +00004851 int FunctionNumber = -1;
4852 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004853
Chris Lattner3432c622009-10-28 03:39:23 +00004854 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004855
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004856 // Resolve block addresses and allow basic blocks to be forward-declared
4857 // within this function.
4858 if (PFS.resolveForwardRefBlockAddresses())
4859 return true;
4860 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4861
Chris Lattnerbbddd962010-01-09 19:20:07 +00004862 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004863 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004864 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004865
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004866 while (Lex.getKind() != lltok::rbrace &&
4867 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004868 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004869
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004870 while (Lex.getKind() != lltok::rbrace)
4871 if (ParseUseListOrder(&PFS))
4872 return true;
4873
Chris Lattnerac161bf2009-01-02 07:01:27 +00004874 // Eat the }.
4875 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004876
Chris Lattnerac161bf2009-01-02 07:01:27 +00004877 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004878 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879}
4880
4881/// ParseBasicBlock
4882/// ::= LabelStr? Instruction*
4883bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4884 // If this basic block starts out with a name, remember it.
4885 std::string Name;
4886 LocTy NameLoc = Lex.getLoc();
4887 if (Lex.getKind() == lltok::LabelStr) {
4888 Name = Lex.getStrVal();
4889 Lex.Lex();
4890 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004891
Chris Lattnerac161bf2009-01-02 07:01:27 +00004892 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004893 if (!BB)
4894 return Error(NameLoc,
4895 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004896
Chris Lattnerac161bf2009-01-02 07:01:27 +00004897 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004898
Chris Lattnerac161bf2009-01-02 07:01:27 +00004899 // Parse the instructions in this block until we get a terminator.
4900 Instruction *Inst;
4901 do {
4902 // This instruction may have three possibilities for a name: a) none
4903 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4904 LocTy NameLoc = Lex.getLoc();
4905 int NameID = -1;
4906 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004907
Chris Lattnerac161bf2009-01-02 07:01:27 +00004908 if (Lex.getKind() == lltok::LocalVarID) {
4909 NameID = Lex.getUIntVal();
4910 Lex.Lex();
4911 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4912 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004913 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004914 NameStr = Lex.getStrVal();
4915 Lex.Lex();
4916 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4917 return true;
4918 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004919
Chris Lattner77b89dc2009-12-30 05:23:43 +00004920 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004921 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004922 case InstError: return true;
4923 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004924 BB->getInstList().push_back(Inst);
4925
Chris Lattner77b89dc2009-12-30 05:23:43 +00004926 // With a normal result, we check to see if the instruction is followed by
4927 // a comma and metadata.
4928 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004929 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004930 return true;
4931 break;
4932 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004933 BB->getInstList().push_back(Inst);
4934
Chris Lattner77b89dc2009-12-30 05:23:43 +00004935 // If the instruction parser ate an extra comma at the end of it, it
4936 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004937 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004938 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004939 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004940 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004941
Chris Lattnerac161bf2009-01-02 07:01:27 +00004942 // Set the name on the instruction.
4943 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4944 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004945
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946 return false;
4947}
4948
4949//===----------------------------------------------------------------------===//
4950// Instruction Parsing.
4951//===----------------------------------------------------------------------===//
4952
4953/// ParseInstruction - Parse one of the many different instructions.
4954///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004955int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4956 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004957 lltok::Kind Token = Lex.getKind();
4958 if (Token == lltok::Eof)
4959 return TokError("found end of file when expecting more instructions");
4960 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004961 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004963
Chris Lattnerac161bf2009-01-02 07:01:27 +00004964 switch (Token) {
4965 default: return Error(Loc, "expected instruction opcode");
4966 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004967 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004968 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4969 case lltok::kw_br: return ParseBr(Inst, PFS);
4970 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004971 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004972 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004973 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004974 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4975 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004976 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4977 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004978 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 // Binary Operators.
4980 case lltok::kw_add:
4981 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004982 case lltok::kw_mul:
4983 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004984 bool NUW = EatIfPresent(lltok::kw_nuw);
4985 bool NSW = EatIfPresent(lltok::kw_nsw);
4986 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004987
Chris Lattnera676c0f2011-02-07 16:40:21 +00004988 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004989
Chris Lattnera676c0f2011-02-07 16:40:21 +00004990 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4991 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4992 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004993 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004994 case lltok::kw_fadd:
4995 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004996 case lltok::kw_fmul:
4997 case lltok::kw_fdiv:
4998 case lltok::kw_frem: {
4999 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5000 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5001 if (Res != 0)
5002 return Res;
5003 if (FMF.any())
5004 Inst->setFastMathFlags(FMF);
5005 return 0;
5006 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005007
Chris Lattner35315d02011-02-06 21:44:57 +00005008 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005009 case lltok::kw_udiv:
5010 case lltok::kw_lshr:
5011 case lltok::kw_ashr: {
5012 bool Exact = EatIfPresent(lltok::kw_exact);
5013
5014 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5015 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5016 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005017 }
5018
Chris Lattnerac161bf2009-01-02 07:01:27 +00005019 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005020 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 case lltok::kw_and:
5022 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005023 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005024 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5025 case lltok::kw_fcmp: {
5026 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5027 int Res = ParseCompare(Inst, PFS, KeywordVal);
5028 if (Res != 0)
5029 return Res;
5030 if (FMF.any())
5031 Inst->setFastMathFlags(FMF);
5032 return 0;
5033 }
5034
Chris Lattnerac161bf2009-01-02 07:01:27 +00005035 // Casts.
5036 case lltok::kw_trunc:
5037 case lltok::kw_zext:
5038 case lltok::kw_sext:
5039 case lltok::kw_fptrunc:
5040 case lltok::kw_fpext:
5041 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005042 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 case lltok::kw_uitofp:
5044 case lltok::kw_sitofp:
5045 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005046 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005047 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005048 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005049 // Other.
5050 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005051 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005052 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5053 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5054 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5055 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005056 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005057 // Call.
5058 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5059 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5060 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005061 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005062 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005063 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005064 case lltok::kw_load: return ParseLoad(Inst, PFS);
5065 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005066 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5067 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005068 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005069 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5070 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5071 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5072 }
5073}
5074
5075/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5076bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005077 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005078 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005079 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5081 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5082 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5083 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5084 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5085 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5086 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5087 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5088 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5089 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5090 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5091 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5092 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5093 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5094 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5095 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5096 }
5097 } else {
5098 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005099 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005100 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5101 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5102 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5103 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5104 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5105 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5106 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5107 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5108 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5109 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5110 }
5111 }
5112 Lex.Lex();
5113 return false;
5114}
5115
5116//===----------------------------------------------------------------------===//
5117// Terminator Instructions.
5118//===----------------------------------------------------------------------===//
5119
5120/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005121/// ::= 'ret' void (',' !dbg, !1)*
5122/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005123bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005124 PerFunctionState &PFS) {
5125 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005126 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005127 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005129 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005130
Chris Lattnerfdd87902009-10-05 05:54:46 +00005131 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005132 if (!ResType->isVoidTy())
5133 return Error(TypeLoc, "value doesn't match function result type '" +
5134 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005135
Owen Anderson55f1c092009-08-13 21:58:54 +00005136 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 return false;
5138 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005139
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 Value *RV;
5141 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005143 if (ResType != RV->getType())
5144 return Error(TypeLoc, "value doesn't match function result type '" +
5145 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005146
Owen Anderson55f1c092009-08-13 21:58:54 +00005147 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005148 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149}
5150
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151/// ParseBr
5152/// ::= 'br' TypeAndValue
5153/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5154bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5155 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005156 Value *Op0;
5157 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005158 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005159
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5161 Inst = BranchInst::Create(BB);
5162 return false;
5163 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005164
Owen Anderson55f1c092009-08-13 21:58:54 +00005165 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005167
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005169 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005170 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005171 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005172 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005173
Chris Lattner3ed871f2009-10-27 19:13:16 +00005174 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005175 return false;
5176}
5177
5178/// ParseSwitch
5179/// Instruction
5180/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5181/// JumpTable
5182/// ::= (TypeAndValue ',' TypeAndValue)*
5183bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5184 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005185 Value *Cond;
5186 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5188 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005189 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5191 return true;
5192
Duncan Sands19d0b472010-02-16 11:11:14 +00005193 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005195
Chris Lattnerac161bf2009-01-02 07:01:27 +00005196 // Parse the jump table pairs.
5197 SmallPtrSet<Value*, 32> SeenCases;
5198 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5199 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005200 Value *Constant;
5201 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005202
Chris Lattnerac161bf2009-01-02 07:01:27 +00005203 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5204 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005205 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005206 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005207
David Blaikie70573dc2014-11-19 07:49:26 +00005208 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 return Error(CondLoc, "duplicate case value in switch");
5210 if (!isa<ConstantInt>(Constant))
5211 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005212
Chris Lattner3ed871f2009-10-27 19:13:16 +00005213 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005215
Chris Lattnerac161bf2009-01-02 07:01:27 +00005216 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005217
Chris Lattner3ed871f2009-10-27 19:13:16 +00005218 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005219 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5220 SI->addCase(Table[i].first, Table[i].second);
5221 Inst = SI;
5222 return false;
5223}
5224
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005225/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005226/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005227/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5228bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005229 LocTy AddrLoc;
5230 Value *Address;
5231 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005232 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5233 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005234 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005235
Duncan Sands19d0b472010-02-16 11:11:14 +00005236 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005237 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005238
Chris Lattner3ed871f2009-10-27 19:13:16 +00005239 // Parse the destination list.
5240 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005241
Chris Lattner3ed871f2009-10-27 19:13:16 +00005242 if (Lex.getKind() != lltok::rsquare) {
5243 BasicBlock *DestBB;
5244 if (ParseTypeAndBasicBlock(DestBB, PFS))
5245 return true;
5246 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005247
Chris Lattner3ed871f2009-10-27 19:13:16 +00005248 while (EatIfPresent(lltok::comma)) {
5249 if (ParseTypeAndBasicBlock(DestBB, PFS))
5250 return true;
5251 DestList.push_back(DestBB);
5252 }
5253 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005254
Chris Lattner3ed871f2009-10-27 19:13:16 +00005255 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5256 return true;
5257
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005258 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005259 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5260 IBI->addDestination(DestList[i]);
5261 Inst = IBI;
5262 return false;
5263}
5264
Chris Lattnerac161bf2009-01-02 07:01:27 +00005265/// ParseInvoke
5266/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5267/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5268bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5269 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005270 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005271 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005272 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005273 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005274 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005275 LocTy RetTypeLoc;
5276 ValID CalleeID;
5277 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005278 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005279
Chris Lattner3ed871f2009-10-27 19:13:16 +00005280 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005281 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005282 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005283 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005284 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5285 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005286 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005288 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005289 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005290 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005291 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005292
Chris Lattnerac161bf2009-01-02 07:01:27 +00005293 // If RetType is a non-function pointer type, then this is the short syntax
5294 // for the call, which means that RetType is just the return type. Infer the
5295 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005296 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5297 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005299 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005300 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5301 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005302
Chris Lattnerac161bf2009-01-02 07:01:27 +00005303 if (!FunctionType::isValidReturnType(RetType))
5304 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005305
Owen Anderson4056ca92009-07-29 22:17:13 +00005306 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005307 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005308
David Blaikie41ba2b42015-07-27 23:32:19 +00005309 CalleeID.FTy = Ty;
5310
Chris Lattnerac161bf2009-01-02 07:01:27 +00005311 // Look up the callee.
5312 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005313 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5314 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005315
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005316 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005317 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005318 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005319 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5320 AttributeSet::ReturnIndex,
5321 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005322
Chris Lattnerac161bf2009-01-02 07:01:27 +00005323 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005324
Chris Lattnerac161bf2009-01-02 07:01:27 +00005325 // Loop through FunctionType's arguments and ensure they are specified
5326 // correctly. Also, gather any parameter attributes.
5327 FunctionType::param_iterator I = Ty->param_begin();
5328 FunctionType::param_iterator E = Ty->param_end();
5329 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005330 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005331 if (I != E) {
5332 ExpectedTy = *I++;
5333 } else if (!Ty->isVarArg()) {
5334 return Error(ArgList[i].Loc, "too many arguments specified");
5335 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005336
Chris Lattnerac161bf2009-01-02 07:01:27 +00005337 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5338 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005339 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005341 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5342 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005343 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5344 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005345 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005346
Chris Lattnerac161bf2009-01-02 07:01:27 +00005347 if (I != E)
5348 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005349
David Majnemer8d22abd2015-02-23 00:01:32 +00005350 if (FnAttrs.hasAttributes()) {
5351 if (FnAttrs.hasAlignmentAttr())
5352 return Error(CallLoc, "invoke instructions may not have an alignment");
5353
Bill Wendlingf5075a42013-01-27 02:24:02 +00005354 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5355 AttributeSet::FunctionIndex,
5356 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005357 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005358
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005359 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005360 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005361
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005362 InvokeInst *II =
5363 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005364 II->setCallingConv(CC);
5365 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005366 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005367 Inst = II;
5368 return false;
5369}
5370
Bill Wendlingf891bf82011-07-31 06:30:59 +00005371/// ParseResume
5372/// ::= 'resume' TypeAndValue
5373bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5374 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005375 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5376 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005377
Bill Wendlingf891bf82011-07-31 06:30:59 +00005378 ResumeInst *RI = ResumeInst::Create(Exn);
5379 Inst = RI;
5380 return false;
5381}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005382
David Majnemer654e1302015-07-31 17:58:14 +00005383bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5384 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005385 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005386 return true;
5387
5388 while (Lex.getKind() != lltok::rsquare) {
5389 // If this isn't the first argument, we need a comma.
5390 if (!Args.empty() &&
5391 ParseToken(lltok::comma, "expected ',' in argument list"))
5392 return true;
5393
5394 // Parse the argument.
5395 LocTy ArgLoc;
5396 Type *ArgTy = nullptr;
5397 if (ParseType(ArgTy, ArgLoc))
5398 return true;
5399
5400 Value *V;
5401 if (ArgTy->isMetadataTy()) {
5402 if (ParseMetadataAsValue(V, PFS))
5403 return true;
5404 } else {
5405 if (ParseValue(ArgTy, V, PFS))
5406 return true;
5407 }
5408 Args.push_back(V);
5409 }
5410
5411 Lex.Lex(); // Lex the ']'.
5412 return false;
5413}
5414
5415/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005416/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005417bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005418 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005419
David Majnemer8a1c45d2015-12-12 05:38:55 +00005420 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5421 return true;
5422
5423 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005424 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005425
5426 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5427 return true;
5428
5429 BasicBlock *UnwindBB = nullptr;
5430 if (Lex.getKind() == lltok::kw_to) {
5431 Lex.Lex();
5432 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5433 return true;
5434 } else {
5435 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5436 return true;
5437 }
5438 }
5439
David Majnemer8a1c45d2015-12-12 05:38:55 +00005440 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005441 return false;
5442}
5443
5444/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005445/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005446bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005447 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005448
David Majnemer8a1c45d2015-12-12 05:38:55 +00005449 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5450 return true;
5451
5452 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005453 return true;
5454
David Majnemer0bc0eef2015-08-15 02:46:08 +00005455 BasicBlock *BB;
5456 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5457 ParseTypeAndBasicBlock(BB, PFS))
5458 return true;
5459
David Majnemer8a1c45d2015-12-12 05:38:55 +00005460 Inst = CatchReturnInst::Create(CatchPad, BB);
5461 return false;
5462}
5463
5464/// ParseCatchSwitch
5465/// ::= 'catchswitch' within Parent
5466bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5467 Value *ParentPad;
5468 LocTy BBLoc;
5469
5470 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5471 return true;
5472
5473 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5474 Lex.getKind() != lltok::LocalVarID)
5475 return TokError("expected scope value for catchswitch");
5476
5477 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5478 return true;
5479
5480 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5481 return true;
5482
5483 SmallVector<BasicBlock *, 32> Table;
5484 do {
5485 BasicBlock *DestBB;
5486 if (ParseTypeAndBasicBlock(DestBB, PFS))
5487 return true;
5488 Table.push_back(DestBB);
5489 } while (EatIfPresent(lltok::comma));
5490
5491 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5492 return true;
5493
5494 if (ParseToken(lltok::kw_unwind,
5495 "expected 'unwind' after catchswitch scope"))
5496 return true;
5497
5498 BasicBlock *UnwindBB = nullptr;
5499 if (EatIfPresent(lltok::kw_to)) {
5500 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5501 return true;
5502 } else {
5503 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5504 return true;
5505 }
5506
5507 auto *CatchSwitch =
5508 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5509 for (BasicBlock *DestBB : Table)
5510 CatchSwitch->addHandler(DestBB);
5511 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005512 return false;
5513}
5514
5515/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005516/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005517bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005518 Value *CatchSwitch = nullptr;
5519
5520 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5521 return true;
5522
5523 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5524 return TokError("expected scope value for catchpad");
5525
5526 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5527 return true;
5528
David Majnemer654e1302015-07-31 17:58:14 +00005529 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005530 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005531 return true;
5532
David Majnemer8a1c45d2015-12-12 05:38:55 +00005533 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005534 return false;
5535}
5536
David Majnemer654e1302015-07-31 17:58:14 +00005537/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005538/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005539bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005540 Value *ParentPad = nullptr;
5541
5542 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5543 return true;
5544
5545 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5546 Lex.getKind() != lltok::LocalVarID)
5547 return TokError("expected scope value for cleanuppad");
5548
5549 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5550 return true;
5551
David Majnemer654e1302015-07-31 17:58:14 +00005552 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005553 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005554 return true;
5555
David Majnemer8a1c45d2015-12-12 05:38:55 +00005556 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005557 return false;
5558}
5559
Chris Lattnerac161bf2009-01-02 07:01:27 +00005560//===----------------------------------------------------------------------===//
5561// Binary Operators.
5562//===----------------------------------------------------------------------===//
5563
5564/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005565/// ::= ArithmeticOps TypeAndValue ',' Value
5566///
5567/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5568/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005569bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005570 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005571 LocTy Loc; Value *LHS, *RHS;
5572 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5573 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5574 ParseValue(LHS->getType(), RHS, PFS))
5575 return true;
5576
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005577 bool Valid;
5578 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005579 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005580 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005581 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5582 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005583 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005584 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5585 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005586 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005587
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005588 if (!Valid)
5589 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005590
Chris Lattnerac161bf2009-01-02 07:01:27 +00005591 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5592 return false;
5593}
5594
5595/// ParseLogical
5596/// ::= ArithmeticOps TypeAndValue ',' Value {
5597bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5598 unsigned Opc) {
5599 LocTy Loc; Value *LHS, *RHS;
5600 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5601 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5602 ParseValue(LHS->getType(), RHS, PFS))
5603 return true;
5604
Duncan Sands9dff9be2010-02-15 16:12:20 +00005605 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005606 return Error(Loc,"instruction requires integer or integer vector operands");
5607
5608 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5609 return false;
5610}
5611
Chris Lattnerac161bf2009-01-02 07:01:27 +00005612/// ParseCompare
5613/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5614/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005615bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5616 unsigned Opc) {
5617 // Parse the integer/fp comparison predicate.
5618 LocTy Loc;
5619 unsigned Pred;
5620 Value *LHS, *RHS;
5621 if (ParseCmpPredicate(Pred, Opc) ||
5622 ParseTypeAndValue(LHS, Loc, PFS) ||
5623 ParseToken(lltok::comma, "expected ',' after compare value") ||
5624 ParseValue(LHS->getType(), RHS, PFS))
5625 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005626
Chris Lattnerac161bf2009-01-02 07:01:27 +00005627 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005628 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005629 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005630 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005631 } else {
5632 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005633 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005634 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005635 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005636 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005637 }
5638 return false;
5639}
5640
5641//===----------------------------------------------------------------------===//
5642// Other Instructions.
5643//===----------------------------------------------------------------------===//
5644
5645
5646/// ParseCast
5647/// ::= CastOpc TypeAndValue 'to' Type
5648bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5649 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005650 LocTy Loc;
5651 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005652 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005653 if (ParseTypeAndValue(Op, Loc, PFS) ||
5654 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5655 ParseType(DestTy))
5656 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005657
Chris Lattner89d856e2009-03-01 00:53:13 +00005658 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5659 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005660 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005661 getTypeString(Op->getType()) + "' to '" +
5662 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005663 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5665 return false;
5666}
5667
5668/// ParseSelect
5669/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5670bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5671 LocTy Loc;
5672 Value *Op0, *Op1, *Op2;
5673 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5674 ParseToken(lltok::comma, "expected ',' after select condition") ||
5675 ParseTypeAndValue(Op1, PFS) ||
5676 ParseToken(lltok::comma, "expected ',' after select value") ||
5677 ParseTypeAndValue(Op2, PFS))
5678 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005679
Chris Lattnerac161bf2009-01-02 07:01:27 +00005680 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5681 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005682
Chris Lattnerac161bf2009-01-02 07:01:27 +00005683 Inst = SelectInst::Create(Op0, Op1, Op2);
5684 return false;
5685}
5686
Chris Lattnerb55ab542009-01-05 08:18:44 +00005687/// ParseVA_Arg
5688/// ::= 'va_arg' TypeAndValue ',' Type
5689bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005690 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005691 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005692 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 if (ParseTypeAndValue(Op, PFS) ||
5694 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005695 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005696 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005697
Chris Lattnerb55ab542009-01-05 08:18:44 +00005698 if (!EltTy->isFirstClassType())
5699 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700
5701 Inst = new VAArgInst(Op, EltTy);
5702 return false;
5703}
5704
5705/// ParseExtractElement
5706/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5707bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5708 LocTy Loc;
5709 Value *Op0, *Op1;
5710 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5711 ParseToken(lltok::comma, "expected ',' after extract value") ||
5712 ParseTypeAndValue(Op1, PFS))
5713 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005714
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5716 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005717
Eric Christopherc9742252009-07-25 02:28:41 +00005718 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719 return false;
5720}
5721
5722/// ParseInsertElement
5723/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5724bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5725 LocTy Loc;
5726 Value *Op0, *Op1, *Op2;
5727 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5728 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5729 ParseTypeAndValue(Op1, PFS) ||
5730 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5731 ParseTypeAndValue(Op2, PFS))
5732 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005733
Chris Lattnerac161bf2009-01-02 07:01:27 +00005734 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005735 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005736
Chris Lattnerac161bf2009-01-02 07:01:27 +00005737 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5738 return false;
5739}
5740
5741/// ParseShuffleVector
5742/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5743bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5744 LocTy Loc;
5745 Value *Op0, *Op1, *Op2;
5746 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5747 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5748 ParseTypeAndValue(Op1, PFS) ||
5749 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5750 ParseTypeAndValue(Op2, PFS))
5751 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005752
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005754 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005755
Chris Lattnerac161bf2009-01-02 07:01:27 +00005756 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5757 return false;
5758}
5759
5760/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005761/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005762int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005763 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005764 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005765
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005766 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005767 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5768 ParseValue(Ty, Op0, PFS) ||
5769 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005770 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005771 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5772 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005773
Chris Lattnerf4f03422009-12-30 05:27:33 +00005774 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005775 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005776
5777 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005778 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005779
Chris Lattner3822f632009-01-02 08:05:26 +00005780 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005781 break;
5782
Chris Lattnerf4f03422009-12-30 05:27:33 +00005783 if (Lex.getKind() == lltok::MetadataVar) {
5784 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005785 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005786 }
Devang Patel8f842d32009-10-16 18:45:49 +00005787
Chris Lattner3822f632009-01-02 08:05:26 +00005788 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005789 ParseValue(Ty, Op0, PFS) ||
5790 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005791 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005792 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5793 return true;
5794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005795
Chris Lattnerac161bf2009-01-02 07:01:27 +00005796 if (!Ty->isFirstClassType())
5797 return Error(TypeLoc, "phi node must have first class type");
5798
Jay Foad52131342011-03-30 11:28:46 +00005799 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5801 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5802 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005803 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005804}
5805
Bill Wendlingfae14752011-08-12 20:24:12 +00005806/// ParseLandingPad
5807/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5808/// Clause
5809/// ::= 'catch' TypeAndValue
5810/// ::= 'filter'
5811/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5812bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005813 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005814
David Majnemer7fddecc2015-06-17 20:52:32 +00005815 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005816 return true;
5817
David Majnemer7fddecc2015-06-17 20:52:32 +00005818 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005819 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5820
5821 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5822 LandingPadInst::ClauseType CT;
5823 if (EatIfPresent(lltok::kw_catch))
5824 CT = LandingPadInst::Catch;
5825 else if (EatIfPresent(lltok::kw_filter))
5826 CT = LandingPadInst::Filter;
5827 else
5828 return TokError("expected 'catch' or 'filter' clause type");
5829
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005830 Value *V;
5831 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005832 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005833 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005834
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005835 // A 'catch' type expects a non-array constant. A filter clause expects an
5836 // array constant.
5837 if (CT == LandingPadInst::Catch) {
5838 if (isa<ArrayType>(V->getType()))
5839 Error(VLoc, "'catch' clause has an invalid type");
5840 } else {
5841 if (!isa<ArrayType>(V->getType()))
5842 Error(VLoc, "'filter' clause has an invalid type");
5843 }
5844
Owen Andersonf8f259d2015-03-09 07:13:42 +00005845 Constant *CV = dyn_cast<Constant>(V);
5846 if (!CV)
5847 return Error(VLoc, "clause argument must be a constant");
5848 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005849 }
5850
Owen Andersonf8f259d2015-03-09 07:13:42 +00005851 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005852 return false;
5853}
5854
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005856/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5857/// OptionalAttrs Type Value ParameterList OptionalAttrs
5858/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5859/// OptionalAttrs Type Value ParameterList OptionalAttrs
5860/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5861/// OptionalAttrs Type Value ParameterList OptionalAttrs
5862/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5863/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005864bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005865 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005866 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005867 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005868 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005869 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005870 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005871 LocTy RetTypeLoc;
5872 ValID CalleeID;
5873 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005874 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005875 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005876
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005877 if (TCK != CallInst::TCK_None &&
5878 ParseToken(lltok::kw_call,
5879 "expected 'tail call', 'musttail call', or 'notail call'"))
5880 return true;
5881
5882 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5883
5884 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005885 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005886 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005887 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5888 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005889 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5890 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005891 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005892
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005893 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5894 return Error(CallLoc, "fast-math-flags specified for call without "
5895 "floating-point scalar or vector return type");
5896
Chris Lattnerac161bf2009-01-02 07:01:27 +00005897 // If RetType is a non-function pointer type, then this is the short syntax
5898 // for the call, which means that RetType is just the return type. Infer the
5899 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005900 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5901 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005902 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005903 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005904 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5905 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005906
Chris Lattnerac161bf2009-01-02 07:01:27 +00005907 if (!FunctionType::isValidReturnType(RetType))
5908 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005909
Owen Anderson4056ca92009-07-29 22:17:13 +00005910 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005912
David Blaikie41ba2b42015-07-27 23:32:19 +00005913 CalleeID.FTy = Ty;
5914
Chris Lattnerac161bf2009-01-02 07:01:27 +00005915 // Look up the callee.
5916 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005917 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5918 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005919
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005920 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005921 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005922 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005923 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5924 AttributeSet::ReturnIndex,
5925 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005926
Chris Lattnerac161bf2009-01-02 07:01:27 +00005927 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005928
Chris Lattnerac161bf2009-01-02 07:01:27 +00005929 // Loop through FunctionType's arguments and ensure they are specified
5930 // correctly. Also, gather any parameter attributes.
5931 FunctionType::param_iterator I = Ty->param_begin();
5932 FunctionType::param_iterator E = Ty->param_end();
5933 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005934 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005935 if (I != E) {
5936 ExpectedTy = *I++;
5937 } else if (!Ty->isVarArg()) {
5938 return Error(ArgList[i].Loc, "too many arguments specified");
5939 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005940
Chris Lattnerac161bf2009-01-02 07:01:27 +00005941 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5942 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005943 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005944 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005945 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5946 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005947 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5948 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005949 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005950
Chris Lattnerac161bf2009-01-02 07:01:27 +00005951 if (I != E)
5952 return Error(CallLoc, "not enough parameters specified for call");
5953
David Majnemer8d22abd2015-02-23 00:01:32 +00005954 if (FnAttrs.hasAttributes()) {
5955 if (FnAttrs.hasAlignmentAttr())
5956 return Error(CallLoc, "call instructions may not have an alignment");
5957
Bill Wendlingf5075a42013-01-27 02:24:02 +00005958 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5959 AttributeSet::FunctionIndex,
5960 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005961 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005962
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005963 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005964 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005965
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005966 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005967 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005968 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005969 if (FMF.any())
5970 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005971 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005972 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005973 Inst = CI;
5974 return false;
5975}
5976
5977//===----------------------------------------------------------------------===//
5978// Memory Instructions.
5979//===----------------------------------------------------------------------===//
5980
5981/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005982/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5983/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005984int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005985 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005986 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005987 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005988 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005989
5990 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005991 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005992
David Majnemera3b0eb22015-02-16 08:38:03 +00005993 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005994
David Majnemera3b0eb22015-02-16 08:38:03 +00005995 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5996 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005997
Chris Lattnerb2f39502009-12-30 05:44:30 +00005998 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005999 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006000 if (Lex.getKind() == lltok::kw_align) {
6001 if (ParseOptionalAlignment(Alignment)) return true;
6002 } else if (Lex.getKind() == lltok::MetadataVar) {
6003 AteExtraComma = true;
6004 } else {
6005 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6006 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6007 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008 }
6009 }
6010
Dan Gohman2140a742010-05-28 01:14:11 +00006011 if (Size && !Size->getType()->isIntegerTy())
6012 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006013
Reid Kleckner436c42e2014-01-17 23:58:17 +00006014 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
6015 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006016 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006017 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006018 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006019}
6020
6021/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006022/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006023/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006024/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006025int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006026 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006027 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006028 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006029 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006030 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006031 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006032
6033 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006034 isAtomic = true;
6035 Lex.Lex();
6036 }
6037
Chris Lattnerbc639292011-11-27 06:56:53 +00006038 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006039 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006040 isVolatile = true;
6041 Lex.Lex();
6042 }
6043
David Blaikie15d9a4c2015-04-06 20:59:48 +00006044 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006045 LocTy ExplicitTypeLoc = Lex.getLoc();
6046 if (ParseType(Ty) ||
6047 ParseToken(lltok::comma, "expected comma after load's type") ||
6048 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006049 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006050 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6051 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006052
David Blaikie15d9a4c2015-04-06 20:59:48 +00006053 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006054 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006055 if (isAtomic && !Alignment)
6056 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006057 if (Ordering == AtomicOrdering::Release ||
6058 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006059 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006060
David Blaikiea79ac142015-02-27 21:17:42 +00006061 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6062 return Error(ExplicitTypeLoc,
6063 "explicit pointee type doesn't match operand's pointee type");
6064
David Blaikie15d9a4c2015-04-06 20:59:48 +00006065 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006066 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006067}
6068
6069/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006070
6071/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6072/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006073/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006074int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006075 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006076 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006077 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006078 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006079 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006080 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006081
6082 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006083 isAtomic = true;
6084 Lex.Lex();
6085 }
6086
Chris Lattnerbc639292011-11-27 06:56:53 +00006087 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006088 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006089 isVolatile = true;
6090 Lex.Lex();
6091 }
6092
Chris Lattnerac161bf2009-01-02 07:01:27 +00006093 if (ParseTypeAndValue(Val, Loc, PFS) ||
6094 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006095 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006096 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006097 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006098 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006099
Duncan Sands19d0b472010-02-16 11:11:14 +00006100 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006101 return Error(PtrLoc, "store operand must be a pointer");
6102 if (!Val->getType()->isFirstClassType())
6103 return Error(Loc, "store operand must be a first class value");
6104 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6105 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006106 if (isAtomic && !Alignment)
6107 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006108 if (Ordering == AtomicOrdering::Acquire ||
6109 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006110 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006111
Eli Friedman59b66882011-08-09 23:02:53 +00006112 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006113 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006114}
6115
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006116/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006117/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6118/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006119int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006120 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6121 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006122 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6123 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006124 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006125 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006126 bool isWeak = false;
6127
6128 if (EatIfPresent(lltok::kw_weak))
6129 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006130
6131 if (EatIfPresent(lltok::kw_volatile))
6132 isVolatile = true;
6133
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006134 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6135 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6136 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6137 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6138 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006139 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6140 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006141 return true;
6142
JF Bastien800f87a2016-04-06 21:19:33 +00006143 if (SuccessOrdering == AtomicOrdering::Unordered ||
6144 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006145 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006146 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6147 return TokError("cmpxchg failure argument shall be no stronger than the "
6148 "success argument");
6149 if (FailureOrdering == AtomicOrdering::Release ||
6150 FailureOrdering == AtomicOrdering::AcquireRelease)
6151 return TokError(
6152 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006153 if (!Ptr->getType()->isPointerTy())
6154 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6155 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6156 return Error(CmpLoc, "compare value and pointer type do not match");
6157 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6158 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006159 if (!New->getType()->isFirstClassType())
6160 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006161 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6162 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006163 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006164 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006165 Inst = CXI;
6166 return AteExtraComma ? InstExtraComma : InstNormal;
6167}
6168
6169/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006170/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6171/// 'singlethread'? AtomicOrdering
6172int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006173 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6174 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006175 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006176 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006177 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006178 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006179
6180 if (EatIfPresent(lltok::kw_volatile))
6181 isVolatile = true;
6182
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006183 switch (Lex.getKind()) {
6184 default: return TokError("expected binary operation in atomicrmw");
6185 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6186 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6187 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6188 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6189 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6190 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6191 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6192 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6193 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6194 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6195 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6196 }
6197 Lex.Lex(); // Eat the operation.
6198
6199 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6200 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6201 ParseTypeAndValue(Val, ValLoc, PFS) ||
6202 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6203 return true;
6204
JF Bastien800f87a2016-04-06 21:19:33 +00006205 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006206 return TokError("atomicrmw cannot be unordered");
6207 if (!Ptr->getType()->isPointerTy())
6208 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6209 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6210 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6211 if (!Val->getType()->isIntegerTy())
6212 return Error(ValLoc, "atomicrmw operand must be an integer");
6213 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6214 if (Size < 8 || (Size & (Size - 1)))
6215 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6216 " integer");
6217
6218 AtomicRMWInst *RMWI =
6219 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6220 RMWI->setVolatile(isVolatile);
6221 Inst = RMWI;
6222 return AteExtraComma ? InstExtraComma : InstNormal;
6223}
6224
Eli Friedmanfee02c62011-07-25 23:16:38 +00006225/// ParseFence
6226/// ::= 'fence' 'singlethread'? AtomicOrdering
6227int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006228 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006229 SynchronizationScope Scope = CrossThread;
6230 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6231 return true;
6232
JF Bastien800f87a2016-04-06 21:19:33 +00006233 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006234 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006235 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006236 return TokError("fence cannot be monotonic");
6237
6238 Inst = new FenceInst(Context, Ordering, Scope);
6239 return InstNormal;
6240}
6241
Chris Lattnerac161bf2009-01-02 07:01:27 +00006242/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006243/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006244int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006245 Value *Ptr = nullptr;
6246 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006247 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006248
Dan Gohman16cbbe42009-07-29 15:58:36 +00006249 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006250
David Blaikie79e6c742015-02-27 19:29:02 +00006251 Type *Ty = nullptr;
6252 LocTy ExplicitTypeLoc = Lex.getLoc();
6253 if (ParseType(Ty) ||
6254 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6255 ParseTypeAndValue(Ptr, Loc, PFS))
6256 return true;
6257
Eli Benderskyd9806682013-04-22 17:03:42 +00006258 Type *BaseType = Ptr->getType();
6259 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6260 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006261 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006262
David Blaikie8d757942015-03-09 23:08:44 +00006263 if (Ty != BasePointerType->getElementType())
6264 return Error(ExplicitTypeLoc,
6265 "explicit pointee type doesn't match operand's pointee type");
6266
Chris Lattnerac161bf2009-01-02 07:01:27 +00006267 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006268 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006269 // GEP returns a vector of pointers if at least one of parameters is a vector.
6270 // All vector parameters should have the same vector width.
6271 unsigned GEPWidth = BaseType->isVectorTy() ?
6272 BaseType->getVectorNumElements() : 0;
6273
Chris Lattner3822f632009-01-02 08:05:26 +00006274 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006275 if (Lex.getKind() == lltok::MetadataVar) {
6276 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006277 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006278 }
Chris Lattner3822f632009-01-02 08:05:26 +00006279 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006280 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006281 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006282
Nadav Rotem3924cb02011-12-05 06:29:09 +00006283 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006284 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6285 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006286 return Error(EltLoc,
6287 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006288 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006289 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006290 Indices.push_back(Val);
6291 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006292
Craig Toppere3dcce92015-08-01 22:20:21 +00006293 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006294 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006295 return Error(Loc, "base element of getelementptr must be sized");
6296
David Blaikied33bad32015-04-17 22:32:13 +00006297 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006298 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006299 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006300 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006301 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006302 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006303}
6304
6305/// ParseExtractValue
6306/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006307int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006308 Value *Val; LocTy Loc;
6309 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006310 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006311 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006312 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006313 return true;
6314
Chris Lattner392be582010-02-12 20:49:41 +00006315 if (!Val->getType()->isAggregateType())
6316 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006317
Jay Foad57aa6362011-07-13 10:26:04 +00006318 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006319 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006320 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006321 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006322}
6323
6324/// ParseInsertValue
6325/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006326int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006327 Value *Val0, *Val1; LocTy Loc0, Loc1;
6328 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006329 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006330 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6331 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6332 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006333 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006334 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006335
Chris Lattner392be582010-02-12 20:49:41 +00006336 if (!Val0->getType()->isAggregateType())
6337 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006338
David Majnemer30074532015-02-11 07:43:58 +00006339 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6340 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006341 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006342 if (IndexedType != Val1->getType())
6343 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6344 getTypeString(Val1->getType()) + "' instead of '" +
6345 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006346 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006347 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006348}
Nick Lewycky49f89192009-04-04 07:22:01 +00006349
6350//===----------------------------------------------------------------------===//
6351// Embedded metadata.
6352//===----------------------------------------------------------------------===//
6353
6354/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006355/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006356/// Element
6357/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006358bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006359 if (ParseToken(lltok::lbrace, "expected '{' here"))
6360 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006361
Dan Gohman1e0213a2010-07-13 19:33:27 +00006362 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006363 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006364 return false;
6365
Nick Lewycky49f89192009-04-04 07:22:01 +00006366 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006367 // Null is a special case since it is typeless.
6368 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006369 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006370 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006371 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006372
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006373 Metadata *MD;
6374 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006375 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006376 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006377 } while (EatIfPresent(lltok::comma));
6378
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006379 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006380}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006381
6382//===----------------------------------------------------------------------===//
6383// Use-list order directives.
6384//===----------------------------------------------------------------------===//
6385bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6386 SMLoc Loc) {
6387 if (V->use_empty())
6388 return Error(Loc, "value has no uses");
6389
6390 unsigned NumUses = 0;
6391 SmallDenseMap<const Use *, unsigned, 16> Order;
6392 for (const Use &U : V->uses()) {
6393 if (++NumUses > Indexes.size())
6394 break;
6395 Order[&U] = Indexes[NumUses - 1];
6396 }
6397 if (NumUses < 2)
6398 return Error(Loc, "value only has one use");
6399 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6400 return Error(Loc, "wrong number of indexes, expected " +
6401 Twine(std::distance(V->use_begin(), V->use_end())));
6402
6403 V->sortUseList([&](const Use &L, const Use &R) {
6404 return Order.lookup(&L) < Order.lookup(&R);
6405 });
6406 return false;
6407}
6408
6409/// ParseUseListOrderIndexes
6410/// ::= '{' uint32 (',' uint32)+ '}'
6411bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6412 SMLoc Loc = Lex.getLoc();
6413 if (ParseToken(lltok::lbrace, "expected '{' here"))
6414 return true;
6415 if (Lex.getKind() == lltok::rbrace)
6416 return Lex.Error("expected non-empty list of uselistorder indexes");
6417
6418 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6419 // indexes should be distinct numbers in the range [0, size-1], and should
6420 // not be in order.
6421 unsigned Offset = 0;
6422 unsigned Max = 0;
6423 bool IsOrdered = true;
6424 assert(Indexes.empty() && "Expected empty order vector");
6425 do {
6426 unsigned Index;
6427 if (ParseUInt32(Index))
6428 return true;
6429
6430 // Update consistency checks.
6431 Offset += Index - Indexes.size();
6432 Max = std::max(Max, Index);
6433 IsOrdered &= Index == Indexes.size();
6434
6435 Indexes.push_back(Index);
6436 } while (EatIfPresent(lltok::comma));
6437
6438 if (ParseToken(lltok::rbrace, "expected '}' here"))
6439 return true;
6440
6441 if (Indexes.size() < 2)
6442 return Error(Loc, "expected >= 2 uselistorder indexes");
6443 if (Offset != 0 || Max >= Indexes.size())
6444 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6445 if (IsOrdered)
6446 return Error(Loc, "expected uselistorder indexes to change the order");
6447
6448 return false;
6449}
6450
6451/// ParseUseListOrder
6452/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6453bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6454 SMLoc Loc = Lex.getLoc();
6455 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6456 return true;
6457
6458 Value *V;
6459 SmallVector<unsigned, 16> Indexes;
6460 if (ParseTypeAndValue(V, PFS) ||
6461 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6462 ParseUseListOrderIndexes(Indexes))
6463 return true;
6464
6465 return sortUseListOrder(V, Indexes, Loc);
6466}
6467
6468/// ParseUseListOrderBB
6469/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6470bool LLParser::ParseUseListOrderBB() {
6471 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6472 SMLoc Loc = Lex.getLoc();
6473 Lex.Lex();
6474
6475 ValID Fn, Label;
6476 SmallVector<unsigned, 16> Indexes;
6477 if (ParseValID(Fn) ||
6478 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6479 ParseValID(Label) ||
6480 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6481 ParseUseListOrderIndexes(Indexes))
6482 return true;
6483
6484 // Check the function.
6485 GlobalValue *GV;
6486 if (Fn.Kind == ValID::t_GlobalName)
6487 GV = M->getNamedValue(Fn.StrVal);
6488 else if (Fn.Kind == ValID::t_GlobalID)
6489 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6490 else
6491 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6492 if (!GV)
6493 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6494 auto *F = dyn_cast<Function>(GV);
6495 if (!F)
6496 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6497 if (F->isDeclaration())
6498 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6499
6500 // Check the basic block.
6501 if (Label.Kind == ValID::t_LocalID)
6502 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6503 if (Label.Kind != ValID::t_LocalName)
6504 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6505 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6506 if (!V)
6507 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6508 if (!isa<BasicBlock>(V))
6509 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6510
6511 return sortUseListOrder(V, Indexes, Loc);
6512}