blob: db87fa75a5883e32d964f0734e8568ba782ccdc2 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000016#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000017#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000018#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000021#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000030#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000031#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000033#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000034#include "llvm/Support/raw_ostream.h"
35using namespace llvm;
36
Chris Lattner229907c2011-07-18 04:54:35 +000037static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000038 std::string Result;
39 raw_string_ostream Tmp(Result);
40 Tmp << *T;
41 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000042}
43
Chris Lattner3822f632009-01-02 08:05:26 +000044/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000045bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000046 // Prime the lexer.
47 Lex.Lex();
48
Mehdi Amini50af49f2016-04-02 03:46:17 +000049 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000050 return Error(
51 Lex.getLoc(),
52 "Can't read textual IR with a Context that discards named Values");
53
Chris Lattnerad6f3352009-01-04 20:44:11 +000054 return ParseTopLevelEntities() ||
55 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000056}
57
Alex Lorenz1de2acd2015-08-21 21:32:39 +000058bool LLParser::parseStandaloneConstantValue(Constant *&C,
59 const SlotMapping *Slots) {
60 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000061 Lex.Lex();
62
63 Type *Ty = nullptr;
64 if (ParseType(Ty) || parseConstantValue(Ty, C))
65 return true;
66 if (Lex.getKind() != lltok::Eof)
67 return Error(Lex.getLoc(), "expected end of string");
68 return false;
69}
70
Quentin Colombetdafed5d2016-03-08 00:37:07 +000071bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
72 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000073 restoreParsingState(Slots);
74 Lex.Lex();
75
Quentin Colombetdafed5d2016-03-08 00:37:07 +000076 Read = 0;
77 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000078 Ty = nullptr;
79 if (ParseType(Ty))
80 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000081 SMLoc End = Lex.getLoc();
82 Read = End.getPointer() - Start.getPointer();
83
Quentin Colombet81e72b42016-03-07 22:09:05 +000084 return false;
85}
86
Alex Lorenz1de2acd2015-08-21 21:32:39 +000087void LLParser::restoreParsingState(const SlotMapping *Slots) {
88 if (!Slots)
89 return;
90 NumberedVals = Slots->GlobalValues;
91 NumberedMetadata = Slots->MetadataNodes;
92 for (const auto &I : Slots->NamedTypes)
93 NamedTypes.insert(
94 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
95 for (const auto &I : Slots->Types)
96 NumberedTypes.insert(
97 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
98}
99
Chris Lattnerac161bf2009-01-02 07:01:27 +0000100/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
101/// module.
102bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000103 // Handle any function attribute group forward references.
104 for (std::map<Value*, std::vector<unsigned> >::iterator
105 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
106 I != E; ++I) {
107 Value *V = I->first;
108 std::vector<unsigned> &Vec = I->second;
109 AttrBuilder B;
110
111 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
112 VI != VE; ++VI)
113 B.merge(NumberedAttrBuilders[*VI]);
114
115 if (Function *Fn = dyn_cast<Function>(V)) {
116 AttributeSet AS = Fn->getAttributes();
117 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
118 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
119 AS.getFnAttributes());
120
121 FnAttrs.merge(B);
122
123 // If the alignment was parsed as an attribute, move to the alignment
124 // field.
125 if (FnAttrs.hasAlignmentAttr()) {
126 Fn->setAlignment(FnAttrs.getAlignment());
127 FnAttrs.removeAttribute(Attribute::Alignment);
128 }
129
130 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
131 AttributeSet::get(Context,
132 AttributeSet::FunctionIndex,
133 FnAttrs));
134 Fn->setAttributes(AS);
135 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
136 AttributeSet AS = CI->getAttributes();
137 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
138 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
139 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000140 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000141 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
142 AttributeSet::get(Context,
143 AttributeSet::FunctionIndex,
144 FnAttrs));
145 CI->setAttributes(AS);
146 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
147 AttributeSet AS = II->getAttributes();
148 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
149 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
150 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000151 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000152 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
153 AttributeSet::get(Context,
154 AttributeSet::FunctionIndex,
155 FnAttrs));
156 II->setAttributes(AS);
157 } else {
158 llvm_unreachable("invalid object with forward attribute group reference");
159 }
160 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000161
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000162 // If there are entries in ForwardRefBlockAddresses at this point, the
163 // function was never defined.
164 if (!ForwardRefBlockAddresses.empty())
165 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
166 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000167
David Majnemer19b51052015-02-11 07:43:56 +0000168 for (const auto &NT : NumberedTypes)
169 if (NT.second.second.isValid())
170 return Error(NT.second.second,
171 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000172
173 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
174 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
175 if (I->second.second.isValid())
176 return Error(I->second.second,
177 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000178
David Majnemerdad0a642014-06-27 18:19:56 +0000179 if (!ForwardRefComdats.empty())
180 return Error(ForwardRefComdats.begin()->second,
181 "use of undefined comdat '$" +
182 ForwardRefComdats.begin()->first + "'");
183
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184 if (!ForwardRefVals.empty())
185 return Error(ForwardRefVals.begin()->second.second,
186 "use of undefined value '@" + ForwardRefVals.begin()->first +
187 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000188
Chris Lattnerac161bf2009-01-02 07:01:27 +0000189 if (!ForwardRefValIDs.empty())
190 return Error(ForwardRefValIDs.begin()->second.second,
191 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000192 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000193
Devang Pateld2541152009-07-08 19:23:54 +0000194 if (!ForwardRefMDNodes.empty())
195 return Error(ForwardRefMDNodes.begin()->second.second,
196 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000197 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000198
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000199 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000200 for (auto &N : NumberedMetadata) {
201 if (N.second && !N.second->isResolved())
202 N.second->resolveCycles();
203 }
Devang Pateld2541152009-07-08 19:23:54 +0000204
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000205 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
206 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
207
Chris Lattnerac161bf2009-01-02 07:01:27 +0000208 // Look for intrinsic functions and CallInst that need to be upgraded
209 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000210 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000211
Manman Ren8b4306c2013-12-02 21:29:56 +0000212 UpgradeDebugInfo(*M);
213
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000214 if (!Slots)
215 return false;
216 // Initialize the slot mapping.
217 // Because by this point we've parsed and validated everything, we can "steal"
218 // the mapping from LLParser as it doesn't need it anymore.
219 Slots->GlobalValues = std::move(NumberedVals);
220 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000221 for (const auto &I : NamedTypes)
222 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
223 for (const auto &I : NumberedTypes)
224 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000225
Chris Lattnerac161bf2009-01-02 07:01:27 +0000226 return false;
227}
228
229//===----------------------------------------------------------------------===//
230// Top-Level Entities
231//===----------------------------------------------------------------------===//
232
233bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000234 while (1) {
235 switch (Lex.getKind()) {
236 default: return TokError("expected top-level entity");
237 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000238 case lltok::kw_declare: if (ParseDeclare()) return true; break;
239 case lltok::kw_define: if (ParseDefine()) return true; break;
240 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
241 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000242 case lltok::kw_source_filename:
243 if (ParseSourceFileName())
244 return true;
245 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000246 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000247 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000248 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000249 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000250 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000251 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000252 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000253 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000254
255 // The Global variable production with no name can have many different
256 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000257 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000258 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000259 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000260 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000261 case lltok::kw_internal: // OptionalLinkage
262 case lltok::kw_weak: // OptionalLinkage
263 case lltok::kw_weak_odr: // OptionalLinkage
264 case lltok::kw_linkonce: // OptionalLinkage
265 case lltok::kw_linkonce_odr: // OptionalLinkage
266 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000267 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000268 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000269 case lltok::kw_external: // OptionalLinkage
270 case lltok::kw_default: // OptionalVisibility
271 case lltok::kw_hidden: // OptionalVisibility
272 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000273 case lltok::kw_dllimport: // OptionalDLLStorageClass
274 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000275 case lltok::kw_thread_local: // OptionalThreadLocal
276 case lltok::kw_addrspace: // OptionalAddrSpace
277 case lltok::kw_constant: // GlobalType
278 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000279 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000280 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000281 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000282 bool HasLinkage;
283 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000284 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000285 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000286 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000287 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000288 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000289 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return true;
291 break;
292 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000293
294 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000295 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
296 case lltok::kw_uselistorder_bb:
297 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000298 }
299 }
300}
301
302
303/// toplevelentity
304/// ::= 'module' 'asm' STRINGCONSTANT
305bool LLParser::ParseModuleAsm() {
306 assert(Lex.getKind() == lltok::kw_module);
307 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000308
309 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000310 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
311 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000312
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000313 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 return false;
315}
316
317/// toplevelentity
318/// ::= 'target' 'triple' '=' STRINGCONSTANT
319/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
320bool LLParser::ParseTargetDefinition() {
321 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000322 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323 switch (Lex.Lex()) {
324 default: return TokError("unknown target property");
325 case lltok::kw_triple:
326 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000327 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
328 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000330 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000331 return false;
332 case lltok::kw_datalayout:
333 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000334 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
335 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000336 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000337 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000338 return false;
339 }
340}
341
Bill Wendling706d3d62012-11-28 08:41:48 +0000342/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000343/// ::= 'source_filename' '=' STRINGCONSTANT
344bool LLParser::ParseSourceFileName() {
345 assert(Lex.getKind() == lltok::kw_source_filename);
346 std::string Str;
347 Lex.Lex();
348 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
349 ParseStringConstant(Str))
350 return true;
351 M->setSourceFileName(Str);
352 return false;
353}
354
355/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000356/// ::= 'deplibs' '=' '[' ']'
357/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
358/// FIXME: Remove in 4.0. Currently parse, but ignore.
359bool LLParser::ParseDepLibs() {
360 assert(Lex.getKind() == lltok::kw_deplibs);
361 Lex.Lex();
362 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
363 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
364 return true;
365
366 if (EatIfPresent(lltok::rsquare))
367 return false;
368
369 do {
370 std::string Str;
371 if (ParseStringConstant(Str)) return true;
372 } while (EatIfPresent(lltok::comma));
373
374 return ParseToken(lltok::rsquare, "expected ']' at end of list");
375}
376
Dan Gohman466876b2009-08-12 23:32:33 +0000377/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000378/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000379bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000380 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000381 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000382 Lex.Lex(); // eat LocalVarID;
383
384 if (ParseToken(lltok::equal, "expected '=' after name") ||
385 ParseToken(lltok::kw_type, "expected 'type' after '='"))
386 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000387
Craig Topper2617dcc2014-04-15 06:32:26 +0000388 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000389 if (ParseStructDefinition(TypeLoc, "",
390 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000391
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000392 if (!isa<StructType>(Result)) {
393 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
394 if (Entry.first)
395 return Error(TypeLoc, "non-struct types may not be recursive");
396 Entry.first = Result;
397 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000398 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Chris Lattnerac161bf2009-01-02 07:01:27 +0000400 return false;
401}
402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404/// toplevelentity
405/// ::= LocalVar '=' 'type' type
406bool LLParser::ParseNamedType() {
407 std::string Name = Lex.getStrVal();
408 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000409 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000410
Chris Lattner3822f632009-01-02 08:05:26 +0000411 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000412 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000413 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000414
Craig Topper2617dcc2014-04-15 06:32:26 +0000415 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000416 if (ParseStructDefinition(NameLoc, Name,
417 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 if (!isa<StructType>(Result)) {
420 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
421 if (Entry.first)
422 return Error(NameLoc, "non-struct types may not be recursive");
423 Entry.first = Result;
424 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000425 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000426
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000427 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000428}
429
430
431/// toplevelentity
432/// ::= 'declare' FunctionHeader
433bool LLParser::ParseDeclare() {
434 assert(Lex.getKind() == lltok::kw_declare);
435 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000436
Chris Lattnerac161bf2009-01-02 07:01:27 +0000437 Function *F;
438 return ParseFunctionHeader(F, false);
439}
440
441/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000442/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443bool LLParser::ParseDefine() {
444 assert(Lex.getKind() == lltok::kw_define);
445 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000446
Chris Lattnerac161bf2009-01-02 07:01:27 +0000447 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000448 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000449 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000450 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451}
452
Chris Lattner3822f632009-01-02 08:05:26 +0000453/// ParseGlobalType
454/// ::= 'constant'
455/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000456bool LLParser::ParseGlobalType(bool &IsConstant) {
457 if (Lex.getKind() == lltok::kw_constant)
458 IsConstant = true;
459 else if (Lex.getKind() == lltok::kw_global)
460 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000461 else {
462 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000463 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000464 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 Lex.Lex();
466 return false;
467}
468
Dan Gohman466876b2009-08-12 23:32:33 +0000469/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000470/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000471/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000473/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000474/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000476bool LLParser::ParseUnnamedGlobal() {
477 unsigned VarID = NumberedVals.size();
478 std::string Name;
479 LocTy NameLoc = Lex.getLoc();
480
481 // Handle the GlobalID form.
482 if (Lex.getKind() == lltok::GlobalID) {
483 if (Lex.getUIntVal() != VarID)
484 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000485 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000486 Lex.Lex(); // eat GlobalID;
487
488 if (ParseToken(lltok::equal, "expected '=' after name"))
489 return true;
490 }
491
492 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000493 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000494 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000495 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000496 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000497 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000498 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000499 ParseOptionalThreadLocal(TLM) ||
500 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000501 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000503 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000504 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000505 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000506
507 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
508 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000509}
510
Chris Lattnerac161bf2009-01-02 07:01:27 +0000511/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000512/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000513/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
514/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000515bool LLParser::ParseNamedGlobal() {
516 assert(Lex.getKind() == lltok::GlobalVar);
517 LocTy NameLoc = Lex.getLoc();
518 std::string Name = Lex.getStrVal();
519 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000520
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000522 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000523 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000524 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
526 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000527 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000528 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000529 ParseOptionalThreadLocal(TLM) ||
530 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000531 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000532
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000533 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000534 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000535 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000536
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000537 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
538 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000539}
540
David Majnemerdad0a642014-06-27 18:19:56 +0000541bool LLParser::parseComdat() {
542 assert(Lex.getKind() == lltok::ComdatVar);
543 std::string Name = Lex.getStrVal();
544 LocTy NameLoc = Lex.getLoc();
545 Lex.Lex();
546
547 if (ParseToken(lltok::equal, "expected '=' here"))
548 return true;
549
550 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
551 return TokError("expected comdat type");
552
553 Comdat::SelectionKind SK;
554 switch (Lex.getKind()) {
555 default:
556 return TokError("unknown selection kind");
557 case lltok::kw_any:
558 SK = Comdat::Any;
559 break;
560 case lltok::kw_exactmatch:
561 SK = Comdat::ExactMatch;
562 break;
563 case lltok::kw_largest:
564 SK = Comdat::Largest;
565 break;
566 case lltok::kw_noduplicates:
567 SK = Comdat::NoDuplicates;
568 break;
569 case lltok::kw_samesize:
570 SK = Comdat::SameSize;
571 break;
572 }
573 Lex.Lex();
574
575 // See if the comdat was forward referenced, if so, use the comdat.
576 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
577 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
578 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
579 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
580
581 Comdat *C;
582 if (I != ComdatSymTab.end())
583 C = &I->second;
584 else
585 C = M->getOrInsertComdat(Name);
586 C->setSelectionKind(SK);
587
588 return false;
589}
590
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000591// MDString:
592// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000593bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000594 std::string Str;
595 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000596 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000597 return false;
598}
599
600// MDNode:
601// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000602bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000604 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000605 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000606 if (ParseUInt32(MID))
607 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000608
Chris Lattner8eff0152010-04-01 05:14:45 +0000609 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000610 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000611 Result = NumberedMetadata[MID];
612 return false;
613 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000614
Chris Lattner8eff0152010-04-01 05:14:45 +0000615 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000616 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000617 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000618
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000619 Result = FwdRef.first.get();
620 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000621 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000622}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000623
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000624/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000625/// !foo = !{ !1, !2 }
626bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000627 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000628 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000629 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000630
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000631 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000632 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000633 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000634 return true;
635
Dan Gohman2637cc12010-07-21 23:38:33 +0000636 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000637 if (Lex.getKind() != lltok::rbrace)
638 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000639 if (ParseToken(lltok::exclaim, "Expected '!' here"))
640 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000641
Craig Topper2617dcc2014-04-15 06:32:26 +0000642 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000643 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000644 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000645 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000646
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000647 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000648}
649
Devang Patel39e64d42009-07-01 19:21:12 +0000650/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000651/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000652bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000653 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000654 Lex.Lex();
655 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000656
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000657 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000658 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000659 ParseToken(lltok::equal, "expected '=' here"))
660 return true;
661
662 // Detect common error, from old metadata syntax.
663 if (Lex.getKind() == lltok::Type)
664 return TokError("unexpected type in metadata definition");
665
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000666 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000667 if (Lex.getKind() == lltok::MetadataVar) {
668 if (ParseSpecializedMDNode(Init, IsDistinct))
669 return true;
670 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
671 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000672 return true;
673
Chris Lattnerfc58af22009-12-30 04:51:58 +0000674 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000675 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000676 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000677 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000678 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000679
Chris Lattnerfc58af22009-12-30 04:51:58 +0000680 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
681 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000682 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000683 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000684 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000685 }
686
Devang Patel39e64d42009-07-01 19:21:12 +0000687 return false;
688}
689
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000690static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
691 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
692 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
693}
694
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000695/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000696/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
697/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000698/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000699///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000700/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000701/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000702///
Eric Christopher536f0a92015-05-28 23:07:39 +0000703/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000704///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000705bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
706 unsigned L, unsigned Visibility,
707 unsigned DLLStorageClass,
708 GlobalVariable::ThreadLocalMode TLM,
709 bool UnnamedAddr) {
710 bool IsAlias;
711 if (Lex.getKind() == lltok::kw_alias)
712 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000713 else if (Lex.getKind() == lltok::kw_ifunc)
714 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000715 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000716 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000717 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000718
Rafael Espindola78527052013-10-06 15:10:43 +0000719 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
720
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000721 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000722 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000724 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000725 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000726 "symbol with local linkage must have default visibility");
727
David Blaikie2f408302015-09-11 03:22:04 +0000728 Type *Ty;
729 LocTy ExplicitTypeLoc = Lex.getLoc();
730 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000731 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000732 return true;
733
Rafael Espindola64c1e182014-06-03 02:41:57 +0000734 Constant *Aliasee;
735 LocTy AliaseeLoc = Lex.getLoc();
736 if (Lex.getKind() != lltok::kw_bitcast &&
737 Lex.getKind() != lltok::kw_getelementptr &&
738 Lex.getKind() != lltok::kw_addrspacecast &&
739 Lex.getKind() != lltok::kw_inttoptr) {
740 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000741 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000742 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000743 // The bitcast dest type is not present, it is implied by the dest type.
744 ValID ID;
745 if (ParseValID(ID))
746 return true;
747 if (ID.Kind != ValID::t_Constant)
748 return Error(AliaseeLoc, "invalid aliasee");
749 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000751
Rafael Espindola64c1e182014-06-03 02:41:57 +0000752 Type *AliaseeType = Aliasee->getType();
753 auto *PTy = dyn_cast<PointerType>(AliaseeType);
754 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000755 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000756 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000757
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000758 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000759 return Error(
760 ExplicitTypeLoc,
761 "explicit pointee type doesn't match operand's pointee type");
762
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000763 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
764 return Error(
765 ExplicitTypeLoc,
766 "explicit pointee type should be a function type");
767
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000768 GlobalValue *GVal = nullptr;
769
770 // See if the alias was forward referenced, if so, prepare to replace the
771 // forward reference.
772 if (!Name.empty()) {
773 GVal = M->getNamedValue(Name);
774 if (GVal) {
775 if (!ForwardRefVals.erase(Name))
776 return Error(NameLoc, "redefinition of global '@" + Name + "'");
777 }
778 } else {
779 auto I = ForwardRefValIDs.find(NumberedVals.size());
780 if (I != ForwardRefValIDs.end()) {
781 GVal = I->second.first;
782 ForwardRefValIDs.erase(I);
783 }
784 }
785
Chris Lattnerac161bf2009-01-02 07:01:27 +0000786 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000787 std::unique_ptr<GlobalIndirectSymbol> GA;
788 if (IsAlias)
789 GA.reset(GlobalAlias::create(Ty, AddrSpace,
790 (GlobalValue::LinkageTypes)Linkage, Name,
791 Aliasee, /*Parent*/ nullptr));
792 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000793 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
794 (GlobalValue::LinkageTypes)Linkage, Name,
795 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000796 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000797 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000798 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000799 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000800
Rafael Espindola54fc2982015-06-17 17:53:31 +0000801 if (Name.empty())
802 NumberedVals.push_back(GA.get());
803
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000804 if (GVal) {
805 // Verify that types agree.
806 if (GVal->getType() != GA->getType())
807 return Error(
808 ExplicitTypeLoc,
809 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000810
Chris Lattnerac161bf2009-01-02 07:01:27 +0000811 // If they agree, just RAUW the old value with the alias and remove the
812 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000813 GVal->replaceAllUsesWith(GA.get());
814 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000815 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000818 if (IsAlias)
819 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
820 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000821 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000822 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000823
Rafael Espindolaaa273822014-05-09 21:49:17 +0000824 // The module owns this now
825 GA.release();
826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 return false;
828}
829
830/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000831/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000832/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000833/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000834/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000835/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000836/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000837///
Eric Christopher536f0a92015-05-28 23:07:39 +0000838/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000839/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000840///
841bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
842 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000843 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000844 GlobalVariable::ThreadLocalMode TLM,
845 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000846 if (!isValidVisibilityForLinkage(Visibility, Linkage))
847 return Error(NameLoc,
848 "symbol with local linkage must have default visibility");
849
Chris Lattnerac161bf2009-01-02 07:01:27 +0000850 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000851 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000852 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000853 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000854
Craig Topper2617dcc2014-04-15 06:32:26 +0000855 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000856 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000857 ParseOptionalToken(lltok::kw_externally_initialized,
858 IsExternallyInitialized,
859 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000860 ParseGlobalType(IsConstant) ||
861 ParseType(Ty, TyLoc))
862 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000863
Chris Lattnerac161bf2009-01-02 07:01:27 +0000864 // If the linkage is specified and is external, then no initializer is
865 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000866 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000867 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 Linkage != GlobalValue::ExternalLinkage)) {
869 if (ParseGlobalValue(Ty, Init))
870 return true;
871 }
872
David Majnemer49b3d9b2015-02-16 08:41:08 +0000873 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000874 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000875
David Majnemer598bd052014-12-09 05:56:09 +0000876 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000877
878 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000879 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000880 GVal = M->getNamedValue(Name);
881 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000882 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000883 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000884 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000885 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000886 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000887 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000888 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000889 ForwardRefValIDs.erase(I);
890 }
891 }
892
David Majnemer598bd052014-12-09 05:56:09 +0000893 GlobalVariable *GV;
894 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000895 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
896 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000897 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000898 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000899 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 return Error(TyLoc,
901 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000902
David Majnemer598bd052014-12-09 05:56:09 +0000903 GV = cast<GlobalVariable>(GVal);
904
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 // Move the forward-reference to the correct spot in the module.
906 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
907 }
908
909 if (Name.empty())
910 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000911
Chris Lattnerac161bf2009-01-02 07:01:27 +0000912 // Set the parsed properties on the global.
913 if (Init)
914 GV->setInitializer(Init);
915 GV->setConstant(IsConstant);
916 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
917 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000918 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000919 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000920 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000921 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000922
Chris Lattnerac161bf2009-01-02 07:01:27 +0000923 // Parse attributes on the global.
924 while (Lex.getKind() == lltok::comma) {
925 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000926
Chris Lattnerac161bf2009-01-02 07:01:27 +0000927 if (Lex.getKind() == lltok::kw_section) {
928 Lex.Lex();
929 GV->setSection(Lex.getStrVal());
930 if (ParseToken(lltok::StringConstant, "expected global section string"))
931 return true;
932 } else if (Lex.getKind() == lltok::kw_align) {
933 unsigned Alignment;
934 if (ParseOptionalAlignment(Alignment)) return true;
935 GV->setAlignment(Alignment);
936 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000937 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000938 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000939 return true;
940 if (C)
941 GV->setComdat(C);
942 else
943 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000944 }
945 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000946
Chris Lattnerac161bf2009-01-02 07:01:27 +0000947 return false;
948}
949
Bill Wendling63b88192013-02-06 06:52:58 +0000950/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000951/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000952bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000953 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000954 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000955 Lex.Lex();
956
David Majnemerb39e22b2014-12-09 18:33:57 +0000957 if (Lex.getKind() != lltok::AttrGrpID)
958 return TokError("expected attribute group id");
959
Bill Wendling63b88192013-02-06 06:52:58 +0000960 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000961 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000962 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000963 Lex.Lex();
964
965 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000966 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000967 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000968 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000969 ParseToken(lltok::rbrace, "expected end of attribute group"))
970 return true;
971
Bill Wendlingb32b0412013-02-08 06:32:06 +0000972 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000973 return Error(AttrGrpLoc, "attribute group has no attributes");
974
975 return false;
976}
977
Bill Wendling8b0321d2013-02-08 00:52:31 +0000978/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000979/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000980bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
981 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000982 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000983 bool HaveError = false;
984
985 B.clear();
986
Bill Wendling63b88192013-02-06 06:52:58 +0000987 while (true) {
988 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000989 if (Token == lltok::kw_builtin)
990 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000991 switch (Token) {
992 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000993 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000994 return Error(Lex.getLoc(), "unterminated attribute group");
995 case lltok::rbrace:
996 // Finished.
997 return false;
998
Bill Wendlingb32b0412013-02-08 06:32:06 +0000999 case lltok::AttrGrpID: {
1000 // Allow a function to reference an attribute group:
1001 //
1002 // define void @foo() #1 { ... }
1003 if (inAttrGrp)
1004 HaveError |=
1005 Error(Lex.getLoc(),
1006 "cannot have an attribute group reference in an attribute group");
1007
1008 unsigned AttrGrpNum = Lex.getUIntVal();
1009 if (inAttrGrp) break;
1010
1011 // Save the reference to the attribute group. We'll fill it in later.
1012 FwdRefAttrGrps.push_back(AttrGrpNum);
1013 break;
1014 }
Bill Wendling63b88192013-02-06 06:52:58 +00001015 // Target-dependent attributes:
1016 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001017 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001018 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001019 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001020 }
1021
1022 // Target-independent attributes:
1023 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001024 // As a hack, we allow function alignment to be initially parsed as an
1025 // attribute on a function declaration/definition or added to an attribute
1026 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001027 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001028 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001029 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001030 if (ParseToken(lltok::equal, "expected '=' here") ||
1031 ParseUInt32(Alignment))
1032 return true;
1033 } else {
1034 if (ParseOptionalAlignment(Alignment))
1035 return true;
1036 }
Bill Wendling63b88192013-02-06 06:52:58 +00001037 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001038 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001039 }
1040 case lltok::kw_alignstack: {
1041 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001042 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001043 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001044 if (ParseToken(lltok::equal, "expected '=' here") ||
1045 ParseUInt32(Alignment))
1046 return true;
1047 } else {
1048 if (ParseOptionalStackAlignment(Alignment))
1049 return true;
1050 }
Bill Wendling63b88192013-02-06 06:52:58 +00001051 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001052 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001053 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001054 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1055 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1056 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1057 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1058 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001059 case lltok::kw_inaccessiblememonly:
1060 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1061 case lltok::kw_inaccessiblemem_or_argmemonly:
1062 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001063 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1064 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1065 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1066 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1067 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1068 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1069 case lltok::kw_noimplicitfloat:
1070 B.addAttribute(Attribute::NoImplicitFloat); break;
1071 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1072 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1073 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1074 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001075 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001076 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1077 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1078 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1079 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1080 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1081 case lltok::kw_returns_twice:
1082 B.addAttribute(Attribute::ReturnsTwice); break;
1083 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1084 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1085 case lltok::kw_sspstrong:
1086 B.addAttribute(Attribute::StackProtectStrong); break;
1087 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1088 case lltok::kw_sanitize_address:
1089 B.addAttribute(Attribute::SanitizeAddress); break;
1090 case lltok::kw_sanitize_thread:
1091 B.addAttribute(Attribute::SanitizeThread); break;
1092 case lltok::kw_sanitize_memory:
1093 B.addAttribute(Attribute::SanitizeMemory); break;
1094 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001095
1096 // Error handling.
1097 case lltok::kw_inreg:
1098 case lltok::kw_signext:
1099 case lltok::kw_zeroext:
1100 HaveError |=
1101 Error(Lex.getLoc(),
1102 "invalid use of attribute on a function");
1103 break;
1104 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001105 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001106 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001107 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001108 case lltok::kw_nest:
1109 case lltok::kw_noalias:
1110 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001111 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001112 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001113 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001114 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001115 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001116 HaveError |=
1117 Error(Lex.getLoc(),
1118 "invalid use of parameter-only attribute on a function");
1119 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001120 }
1121
1122 Lex.Lex();
1123 }
1124}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001125
1126//===----------------------------------------------------------------------===//
1127// GlobalValue Reference/Resolution Routines.
1128//===----------------------------------------------------------------------===//
1129
Karl Schimpf77729782015-09-03 18:06:44 +00001130static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1131 const std::string &Name) {
1132 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1133 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1134 else
1135 return new GlobalVariable(*M, PTy->getElementType(), false,
1136 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1137 nullptr, GlobalVariable::NotThreadLocal,
1138 PTy->getAddressSpace());
1139}
1140
Chris Lattnerac161bf2009-01-02 07:01:27 +00001141/// GetGlobalVal - Get a value with the specified name or ID, creating a
1142/// forward reference record if needed. This can return null if the value
1143/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001144GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001146 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001147 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001148 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001149 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001151
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 // Look this name up in the normal function symbol table.
1153 GlobalValue *Val =
1154 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001155
Chris Lattnerac161bf2009-01-02 07:01:27 +00001156 // If this is a forward reference for the value, see if we already created a
1157 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001158 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001159 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160 if (I != ForwardRefVals.end())
1161 Val = I->second.first;
1162 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001163
Chris Lattnerac161bf2009-01-02 07:01:27 +00001164 // If we have the value in the symbol table or fwd-ref table, return it.
1165 if (Val) {
1166 if (Val->getType() == Ty) return Val;
1167 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001168 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001169 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001171
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001173 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001174 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1175 return FwdVal;
1176}
1177
Chris Lattner229907c2011-07-18 04:54:35 +00001178GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1179 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001182 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001184
Craig Topper2617dcc2014-04-15 06:32:26 +00001185 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001186
Chris Lattnerac161bf2009-01-02 07:01:27 +00001187 // If this is a forward reference for the value, see if we already created a
1188 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001189 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001190 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 if (I != ForwardRefValIDs.end())
1192 Val = I->second.first;
1193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001194
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195 // If we have the value in the symbol table or fwd-ref table, return it.
1196 if (Val) {
1197 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001198 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001199 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001200 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001202
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001204 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1206 return FwdVal;
1207}
1208
1209
1210//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001211// Comdat Reference/Resolution Routines.
1212//===----------------------------------------------------------------------===//
1213
1214Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1215 // Look this name up in the comdat symbol table.
1216 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1217 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1218 if (I != ComdatSymTab.end())
1219 return &I->second;
1220
1221 // Otherwise, create a new forward reference for this value and remember it.
1222 Comdat *C = M->getOrInsertComdat(Name);
1223 ForwardRefComdats[Name] = Loc;
1224 return C;
1225}
1226
1227
1228//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001229// Helper Routines.
1230//===----------------------------------------------------------------------===//
1231
1232/// ParseToken - If the current token has the specified kind, eat it and return
1233/// success. Otherwise, emit the specified error and return failure.
1234bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1235 if (Lex.getKind() != T)
1236 return TokError(ErrMsg);
1237 Lex.Lex();
1238 return false;
1239}
1240
Chris Lattner3822f632009-01-02 08:05:26 +00001241/// ParseStringConstant
1242/// ::= StringConstant
1243bool LLParser::ParseStringConstant(std::string &Result) {
1244 if (Lex.getKind() != lltok::StringConstant)
1245 return TokError("expected string constant");
1246 Result = Lex.getStrVal();
1247 Lex.Lex();
1248 return false;
1249}
1250
1251/// ParseUInt32
1252/// ::= uint32
1253bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001254 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1255 return TokError("expected integer");
1256 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1257 if (Val64 != unsigned(Val64))
1258 return TokError("expected 32-bit integer (too large)");
1259 Val = Val64;
1260 Lex.Lex();
1261 return false;
1262}
1263
Hal Finkelb0407ba2014-07-18 15:51:28 +00001264/// ParseUInt64
1265/// ::= uint64
1266bool LLParser::ParseUInt64(uint64_t &Val) {
1267 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1268 return TokError("expected integer");
1269 Val = Lex.getAPSIntVal().getLimitedValue();
1270 Lex.Lex();
1271 return false;
1272}
1273
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001274/// ParseTLSModel
1275/// := 'localdynamic'
1276/// := 'initialexec'
1277/// := 'localexec'
1278bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1279 switch (Lex.getKind()) {
1280 default:
1281 return TokError("expected localdynamic, initialexec or localexec");
1282 case lltok::kw_localdynamic:
1283 TLM = GlobalVariable::LocalDynamicTLSModel;
1284 break;
1285 case lltok::kw_initialexec:
1286 TLM = GlobalVariable::InitialExecTLSModel;
1287 break;
1288 case lltok::kw_localexec:
1289 TLM = GlobalVariable::LocalExecTLSModel;
1290 break;
1291 }
1292
1293 Lex.Lex();
1294 return false;
1295}
1296
1297/// ParseOptionalThreadLocal
1298/// := /*empty*/
1299/// := 'thread_local'
1300/// := 'thread_local' '(' tlsmodel ')'
1301bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1302 TLM = GlobalVariable::NotThreadLocal;
1303 if (!EatIfPresent(lltok::kw_thread_local))
1304 return false;
1305
1306 TLM = GlobalVariable::GeneralDynamicTLSModel;
1307 if (Lex.getKind() == lltok::lparen) {
1308 Lex.Lex();
1309 return ParseTLSModel(TLM) ||
1310 ParseToken(lltok::rparen, "expected ')' after thread local model");
1311 }
1312 return false;
1313}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001314
1315/// ParseOptionalAddrSpace
1316/// := /*empty*/
1317/// := 'addrspace' '(' uint32 ')'
1318bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1319 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001320 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001321 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001322 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001323 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001324 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001325}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001326
Artur Pilipenko17376c42015-08-03 14:31:49 +00001327/// ParseStringAttribute
1328/// := StringConstant
1329/// := StringConstant '=' StringConstant
1330bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1331 std::string Attr = Lex.getStrVal();
1332 Lex.Lex();
1333 std::string Val;
1334 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1335 return true;
1336 B.addAttribute(Attr, Val);
1337 return false;
1338}
1339
Bill Wendling34c2eb22012-12-04 23:40:58 +00001340/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1341bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1342 bool HaveError = false;
1343
1344 B.clear();
1345
1346 while (1) {
1347 lltok::Kind Token = Lex.getKind();
1348 switch (Token) {
1349 default: // End of attributes.
1350 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001351 case lltok::StringConstant: {
1352 if (ParseStringAttribute(B))
1353 return true;
1354 continue;
1355 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356 case lltok::kw_align: {
1357 unsigned Alignment;
1358 if (ParseOptionalAlignment(Alignment))
1359 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001360 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361 continue;
1362 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001363 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001364 case lltok::kw_dereferenceable: {
1365 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001366 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001367 return true;
1368 B.addDereferenceableAttr(Bytes);
1369 continue;
1370 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001371 case lltok::kw_dereferenceable_or_null: {
1372 uint64_t Bytes;
1373 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1374 return true;
1375 B.addDereferenceableOrNullAttr(Bytes);
1376 continue;
1377 }
Reid Klecknera534a382013-12-19 02:14:12 +00001378 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001379 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1380 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1381 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1382 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001383 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001384 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1385 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001386 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001387 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1388 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001389 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001390 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001391 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001392
Stephen Lin7577ed52013-04-20 13:16:13 +00001393 case lltok::kw_alignstack:
1394 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001395 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001396 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001397 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001398 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001399 case lltok::kw_minsize:
1400 case lltok::kw_naked:
1401 case lltok::kw_nobuiltin:
1402 case lltok::kw_noduplicate:
1403 case lltok::kw_noimplicitfloat:
1404 case lltok::kw_noinline:
1405 case lltok::kw_nonlazybind:
1406 case lltok::kw_noredzone:
1407 case lltok::kw_noreturn:
1408 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001409 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001410 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001411 case lltok::kw_returns_twice:
1412 case lltok::kw_sanitize_address:
1413 case lltok::kw_sanitize_memory:
1414 case lltok::kw_sanitize_thread:
1415 case lltok::kw_ssp:
1416 case lltok::kw_sspreq:
1417 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001418 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001419 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001420 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1421 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001422 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001423
Bill Wendling34c2eb22012-12-04 23:40:58 +00001424 Lex.Lex();
1425 }
1426}
1427
1428/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1429bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1430 bool HaveError = false;
1431
1432 B.clear();
1433
1434 while (1) {
1435 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001436 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001437 default: // End of attributes.
1438 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001439 case lltok::StringConstant: {
1440 if (ParseStringAttribute(B))
1441 return true;
1442 continue;
1443 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001444 case lltok::kw_dereferenceable: {
1445 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001446 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001447 return true;
1448 B.addDereferenceableAttr(Bytes);
1449 continue;
1450 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001451 case lltok::kw_dereferenceable_or_null: {
1452 uint64_t Bytes;
1453 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1454 return true;
1455 B.addDereferenceableOrNullAttr(Bytes);
1456 continue;
1457 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001458 case lltok::kw_align: {
1459 unsigned Alignment;
1460 if (ParseOptionalAlignment(Alignment))
1461 return true;
1462 B.addAlignmentAttr(Alignment);
1463 continue;
1464 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001465 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1466 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001467 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001468 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1469 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001470
Bill Wendling34c2eb22012-12-04 23:40:58 +00001471 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001472 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001473 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001474 case lltok::kw_nest:
1475 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001476 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001477 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001478 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001479 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001480 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001481 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001482
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001483 case lltok::kw_alignstack:
1484 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001485 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001486 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001487 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001488 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001489 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001490 case lltok::kw_minsize:
1491 case lltok::kw_naked:
1492 case lltok::kw_nobuiltin:
1493 case lltok::kw_noduplicate:
1494 case lltok::kw_noimplicitfloat:
1495 case lltok::kw_noinline:
1496 case lltok::kw_nonlazybind:
1497 case lltok::kw_noredzone:
1498 case lltok::kw_noreturn:
1499 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001500 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001501 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001502 case lltok::kw_returns_twice:
1503 case lltok::kw_sanitize_address:
1504 case lltok::kw_sanitize_memory:
1505 case lltok::kw_sanitize_thread:
1506 case lltok::kw_ssp:
1507 case lltok::kw_sspreq:
1508 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001509 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001510 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001511 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001512 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001513
1514 case lltok::kw_readnone:
1515 case lltok::kw_readonly:
1516 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001517 }
1518
Chris Lattnerac161bf2009-01-02 07:01:27 +00001519 Lex.Lex();
1520 }
1521}
1522
1523/// ParseOptionalLinkage
1524/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001525/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001526/// ::= 'internal'
1527/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001528/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001529/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001530/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001531/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001532/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001533/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001534/// ::= 'extern_weak'
1535/// ::= 'external'
1536bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1537 HasLinkage = false;
1538 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001539 default: Res=GlobalValue::ExternalLinkage; return false;
1540 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001541 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1542 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1543 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1544 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1545 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001546 case lltok::kw_available_externally:
1547 Res = GlobalValue::AvailableExternallyLinkage;
1548 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001549 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001550 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001551 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1552 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001553 }
1554 Lex.Lex();
1555 HasLinkage = true;
1556 return false;
1557}
1558
1559/// ParseOptionalVisibility
1560/// ::= /*empty*/
1561/// ::= 'default'
1562/// ::= 'hidden'
1563/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001564///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001565bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1566 switch (Lex.getKind()) {
1567 default: Res = GlobalValue::DefaultVisibility; return false;
1568 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1569 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1570 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1571 }
1572 Lex.Lex();
1573 return false;
1574}
1575
Nico Rieck7157bb72014-01-14 15:22:47 +00001576/// ParseOptionalDLLStorageClass
1577/// ::= /*empty*/
1578/// ::= 'dllimport'
1579/// ::= 'dllexport'
1580///
1581bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1582 switch (Lex.getKind()) {
1583 default: Res = GlobalValue::DefaultStorageClass; return false;
1584 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1585 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1586 }
1587 Lex.Lex();
1588 return false;
1589}
1590
Chris Lattnerac161bf2009-01-02 07:01:27 +00001591/// ParseOptionalCallingConv
1592/// ::= /*empty*/
1593/// ::= 'ccc'
1594/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001595/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001596/// ::= 'coldcc'
1597/// ::= 'x86_stdcallcc'
1598/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001599/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001600/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001601/// ::= 'arm_apcscc'
1602/// ::= 'arm_aapcscc'
1603/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001604/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001605/// ::= 'avr_intrcc'
1606/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001607/// ::= 'ptx_kernel'
1608/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001609/// ::= 'spir_func'
1610/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001611/// ::= 'x86_64_sysvcc'
1612/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001613/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001614/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001615/// ::= 'preserve_mostcc'
1616/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001617/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001618/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001619/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001620/// ::= 'hhvmcc'
1621/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001622/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001623/// ::= 'amdgpu_vs'
1624/// ::= 'amdgpu_tcs'
1625/// ::= 'amdgpu_tes'
1626/// ::= 'amdgpu_gs'
1627/// ::= 'amdgpu_ps'
1628/// ::= 'amdgpu_cs'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001629/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001630///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001631bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001632 switch (Lex.getKind()) {
1633 default: CC = CallingConv::C; return false;
1634 case lltok::kw_ccc: CC = CallingConv::C; break;
1635 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1636 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1637 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1638 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001639 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001640 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001641 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1642 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1643 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001644 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001645 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1646 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001647 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1648 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001649 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1650 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001651 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001652 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1653 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001654 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001655 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001656 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1657 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001658 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001659 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001660 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001661 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1662 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001663 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001664 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1665 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1666 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1667 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001668 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001669 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001670 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001671 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001672 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001673
Chris Lattnerac161bf2009-01-02 07:01:27 +00001674 Lex.Lex();
1675 return false;
1676}
1677
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001678/// ParseMetadataAttachment
1679/// ::= !dbg !42
1680bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1681 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1682
1683 std::string Name = Lex.getStrVal();
1684 Kind = M->getMDKindID(Name);
1685 Lex.Lex();
1686
1687 return ParseMDNode(MD);
1688}
1689
Chris Lattner5c427632009-12-30 05:31:19 +00001690/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001691/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001692bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001693 do {
1694 if (Lex.getKind() != lltok::MetadataVar)
1695 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001696
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001697 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001698 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001699 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001700 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001701
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001702 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001703 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001704 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001705
Chris Lattner596760d2009-12-29 21:25:40 +00001706 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001707 } while (EatIfPresent(lltok::comma));
1708 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001709}
1710
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001711/// ParseOptionalFunctionMetadata
1712/// ::= (!dbg !57)*
1713bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1714 while (Lex.getKind() == lltok::MetadataVar) {
1715 unsigned MDK;
1716 MDNode *N;
1717 if (ParseMetadataAttachment(MDK, N))
1718 return true;
1719
1720 F.setMetadata(MDK, N);
1721 }
1722 return false;
1723}
1724
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725/// ParseOptionalAlignment
1726/// ::= /* empty */
1727/// ::= 'align' 4
1728bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1729 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001730 if (!EatIfPresent(lltok::kw_align))
1731 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001732 LocTy AlignLoc = Lex.getLoc();
1733 if (ParseUInt32(Alignment)) return true;
1734 if (!isPowerOf2_32(Alignment))
1735 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001736 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001737 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001738 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739}
1740
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001741/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001742/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001743/// ::= AttrKind '(' 4 ')'
1744///
1745/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1746bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1747 uint64_t &Bytes) {
1748 assert((AttrKind == lltok::kw_dereferenceable ||
1749 AttrKind == lltok::kw_dereferenceable_or_null) &&
1750 "contract!");
1751
Hal Finkelb0407ba2014-07-18 15:51:28 +00001752 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001753 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001754 return false;
1755 LocTy ParenLoc = Lex.getLoc();
1756 if (!EatIfPresent(lltok::lparen))
1757 return Error(ParenLoc, "expected '('");
1758 LocTy DerefLoc = Lex.getLoc();
1759 if (ParseUInt64(Bytes)) return true;
1760 ParenLoc = Lex.getLoc();
1761 if (!EatIfPresent(lltok::rparen))
1762 return Error(ParenLoc, "expected ')'");
1763 if (!Bytes)
1764 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1765 return false;
1766}
1767
Chris Lattnerb2f39502009-12-30 05:44:30 +00001768/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001769/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001770/// ::= ',' align 4
1771///
1772/// This returns with AteExtraComma set to true if it ate an excess comma at the
1773/// end.
1774bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1775 bool &AteExtraComma) {
1776 AteExtraComma = false;
1777 while (EatIfPresent(lltok::comma)) {
1778 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001779 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001780 AteExtraComma = true;
1781 return false;
1782 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001783
Chris Lattner95b0ff42010-04-23 00:50:50 +00001784 if (Lex.getKind() != lltok::kw_align)
1785 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001786
Chris Lattner95b0ff42010-04-23 00:50:50 +00001787 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001788 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001789
Devang Patelea8a4b92009-09-17 23:04:48 +00001790 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001791}
1792
Eli Friedmanfee02c62011-07-25 23:16:38 +00001793/// ParseScopeAndOrdering
1794/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1795/// else: ::=
1796///
1797/// This sets Scope and Ordering to the parsed values.
1798bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1799 AtomicOrdering &Ordering) {
1800 if (!isAtomic)
1801 return false;
1802
1803 Scope = CrossThread;
1804 if (EatIfPresent(lltok::kw_singlethread))
1805 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001806
1807 return ParseOrdering(Ordering);
1808}
1809
1810/// ParseOrdering
1811/// ::= AtomicOrdering
1812///
1813/// This sets Ordering to the parsed value.
1814bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001815 switch (Lex.getKind()) {
1816 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001817 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1818 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1819 // Not specified yet:
1820 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1821 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1822 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1823 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1824 case lltok::kw_seq_cst:
1825 Ordering = AtomicOrdering::SequentiallyConsistent;
1826 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001827 }
1828 Lex.Lex();
1829 return false;
1830}
1831
Charles Davisbe5557e2010-02-12 00:31:15 +00001832/// ParseOptionalStackAlignment
1833/// ::= /* empty */
1834/// ::= 'alignstack' '(' 4 ')'
1835bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1836 Alignment = 0;
1837 if (!EatIfPresent(lltok::kw_alignstack))
1838 return false;
1839 LocTy ParenLoc = Lex.getLoc();
1840 if (!EatIfPresent(lltok::lparen))
1841 return Error(ParenLoc, "expected '('");
1842 LocTy AlignLoc = Lex.getLoc();
1843 if (ParseUInt32(Alignment)) return true;
1844 ParenLoc = Lex.getLoc();
1845 if (!EatIfPresent(lltok::rparen))
1846 return Error(ParenLoc, "expected ')'");
1847 if (!isPowerOf2_32(Alignment))
1848 return Error(AlignLoc, "stack alignment is not a power of two");
1849 return false;
1850}
Devang Patelea8a4b92009-09-17 23:04:48 +00001851
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001852/// ParseIndexList - This parses the index list for an insert/extractvalue
1853/// instruction. This sets AteExtraComma in the case where we eat an extra
1854/// comma at the end of the line and find that it is followed by metadata.
1855/// Clients that don't allow metadata can call the version of this function that
1856/// only takes one argument.
1857///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858/// ParseIndexList
1859/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001860///
1861bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1862 bool &AteExtraComma) {
1863 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001864
Chris Lattnerac161bf2009-01-02 07:01:27 +00001865 if (Lex.getKind() != lltok::comma)
1866 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001867
Chris Lattner3822f632009-01-02 08:05:26 +00001868 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001869 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001870 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001871 AteExtraComma = true;
1872 return false;
1873 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001874 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001875 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876 Indices.push_back(Idx);
1877 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001878
Chris Lattnerac161bf2009-01-02 07:01:27 +00001879 return false;
1880}
1881
1882//===----------------------------------------------------------------------===//
1883// Type Parsing.
1884//===----------------------------------------------------------------------===//
1885
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001886/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001887bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 switch (Lex.getKind()) {
1890 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001891 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001892 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001893 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001895 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001896 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001897 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001898 // Type ::= StructType
1899 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900 return true;
1901 break;
1902 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001903 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001904 Lex.Lex(); // eat the lsquare.
1905 if (ParseArrayVectorType(Result, false))
1906 return true;
1907 break;
1908 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001909 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001910 Lex.Lex();
1911 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001912 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001913 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001915 } else if (ParseArrayVectorType(Result, true))
1916 return true;
1917 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001918 case lltok::LocalVar: {
1919 // Type ::= %foo
1920 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001921
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001922 // If the type hasn't been defined yet, create a forward definition and
1923 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001924 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001925 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001928 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 Lex.Lex();
1930 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933 case lltok::LocalVarID: {
1934 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001935 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001936
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001937 // If the type hasn't been defined yet, create a forward definition and
1938 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001939 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001940 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001941 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001943 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001944 Lex.Lex();
1945 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001946 }
1947 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001948
1949 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001950 while (1) {
1951 switch (Lex.getKind()) {
1952 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001953 default:
1954 if (!AllowVoid && Result->isVoidTy())
1955 return Error(TypeLoc, "void type only allowed for function results");
1956 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001961 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 if (Result->isVoidTy())
1963 return TokError("pointers to void are invalid - use i8* instead");
1964 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001965 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001966 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 Lex.Lex();
1968 break;
1969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001972 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001974 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001975 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001976 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001977 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 unsigned AddrSpace;
1979 if (ParseOptionalAddrSpace(AddrSpace) ||
1980 ParseToken(lltok::star, "expected '*' in address space"))
1981 return true;
1982
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001983 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001984 break;
1985 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Chris Lattnerac161bf2009-01-02 07:01:27 +00001987 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1988 case lltok::lparen:
1989 if (ParseFunctionType(Result))
1990 return true;
1991 break;
1992 }
1993 }
1994}
1995
1996/// ParseParameterList
1997/// ::= '(' ')'
1998/// ::= '(' Arg (',' Arg)* ')'
1999/// Arg
2000/// ::= Type OptionalAttributes Value OptionalAttributes
2001bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002002 PerFunctionState &PFS, bool IsMustTailCall,
2003 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 if (ParseToken(lltok::lparen, "expected '(' in call"))
2005 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002006
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002007 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 while (Lex.getKind() != lltok::rparen) {
2009 // If this isn't the first argument, we need a comma.
2010 if (!ArgList.empty() &&
2011 ParseToken(lltok::comma, "expected ',' in argument list"))
2012 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002013
Reid Kleckner83498642014-08-26 00:33:28 +00002014 // Parse an ellipsis if this is a musttail call in a variadic function.
2015 if (Lex.getKind() == lltok::dotdotdot) {
2016 const char *Msg = "unexpected ellipsis in argument list for ";
2017 if (!IsMustTailCall)
2018 return TokError(Twine(Msg) + "non-musttail call");
2019 if (!InVarArgsFunc)
2020 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2021 Lex.Lex(); // Lex the '...', it is purely for readability.
2022 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2023 }
2024
Chris Lattnerac161bf2009-01-02 07:01:27 +00002025 // Parse the argument.
2026 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002027 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002028 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002030 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002032
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002033 if (ArgTy->isMetadataTy()) {
2034 if (ParseMetadataAsValue(V, PFS))
2035 return true;
2036 } else {
2037 // Otherwise, handle normal operands.
2038 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2039 return true;
2040 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002041 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2042 AttrIndex++,
2043 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044 }
2045
Reid Kleckner83498642014-08-26 00:33:28 +00002046 if (IsMustTailCall && InVarArgsFunc)
2047 return TokError("expected '...' at end of argument list for musttail call "
2048 "in varargs function");
2049
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 Lex.Lex(); // Lex the ')'.
2051 return false;
2052}
2053
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002054/// ParseOptionalOperandBundles
2055/// ::= /*empty*/
2056/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2057///
2058/// OperandBundle
2059/// ::= bundle-tag '(' ')'
2060/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2061///
2062/// bundle-tag ::= String Constant
2063bool LLParser::ParseOptionalOperandBundles(
2064 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2065 LocTy BeginLoc = Lex.getLoc();
2066 if (!EatIfPresent(lltok::lsquare))
2067 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002069 while (Lex.getKind() != lltok::rsquare) {
2070 // If this isn't the first operand bundle, we need a comma.
2071 if (!BundleList.empty() &&
2072 ParseToken(lltok::comma, "expected ',' in input list"))
2073 return true;
2074
2075 std::string Tag;
2076 if (ParseStringConstant(Tag))
2077 return true;
2078
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002079 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2080 return true;
2081
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002082 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002083 while (Lex.getKind() != lltok::rparen) {
2084 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002085 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002086 ParseToken(lltok::comma, "expected ',' in input list"))
2087 return true;
2088
2089 Type *Ty = nullptr;
2090 Value *Input = nullptr;
2091 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2092 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002093 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002094 }
2095
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002096 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2097
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002098 Lex.Lex(); // Lex the ')'.
2099 }
2100
2101 if (BundleList.empty())
2102 return Error(BeginLoc, "operand bundle set must not be empty");
2103
2104 Lex.Lex(); // Lex the ']'.
2105 return false;
2106}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107
Chris Lattner2ed06b42009-01-05 18:34:07 +00002108/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002109/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110/// ::= '(' ArgTypeListI ')'
2111/// ArgTypeListI
2112/// ::= /*empty*/
2113/// ::= '...'
2114/// ::= ArgTypeList ',' '...'
2115/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002116///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002117bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2118 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 isVarArg = false;
2120 assert(Lex.getKind() == lltok::lparen);
2121 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 if (Lex.getKind() == lltok::rparen) {
2124 // empty
2125 } else if (Lex.getKind() == lltok::dotdotdot) {
2126 isVarArg = true;
2127 Lex.Lex();
2128 } else {
2129 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002130 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002131 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002133
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002134 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002135 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002136
Chris Lattnerfdd87902009-10-05 05:54:46 +00002137 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002138 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002139
Chris Lattnerdef19492011-06-17 06:36:20 +00002140 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002141 Name = Lex.getStrVal();
2142 Lex.Lex();
2143 }
Chris Lattner3822f632009-01-02 08:05:26 +00002144
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002145 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002146 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002147
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002148 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002149 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2150 AttrIndex++, Attrs),
2151 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002152
Chris Lattner3822f632009-01-02 08:05:26 +00002153 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002155 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 break;
2158 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002159
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 // Otherwise must be an argument type.
2161 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002162 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002163
Chris Lattnerfdd87902009-10-05 05:54:46 +00002164 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002165 return Error(TypeLoc, "argument can not have void type");
2166
Chris Lattnerdef19492011-06-17 06:36:20 +00002167 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 Name = Lex.getStrVal();
2169 Lex.Lex();
2170 } else {
2171 Name = "";
2172 }
Chris Lattner3822f632009-01-02 08:05:26 +00002173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002174 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002175 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002176
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002177 ArgList.emplace_back(
2178 TypeLoc, ArgTy,
2179 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2180 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002181 }
2182 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002183
Chris Lattner3822f632009-01-02 08:05:26 +00002184 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002186
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187/// ParseFunctionType
2188/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002189bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 assert(Lex.getKind() == lltok::lparen);
2191
Chris Lattnerce473c72009-01-05 08:04:33 +00002192 if (!FunctionType::isValidReturnType(Result))
2193 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002194
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002195 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002197 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002199
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200 // Reject names on the arguments lists.
2201 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2202 if (!ArgList[i].Name.empty())
2203 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002204 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002205 return Error(ArgList[i].Loc,
2206 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Jay Foadb804a2b2011-07-12 14:06:48 +00002209 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002211 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002213 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 return false;
2215}
2216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002217/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2218/// other structs.
2219bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2220 SmallVector<Type*, 8> Elts;
2221 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002222
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002223 Result = StructType::get(Context, Elts, Packed);
2224 return false;
2225}
2226
2227/// ParseStructDefinition - Parse a struct in a 'type' definition.
2228bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2229 std::pair<Type*, LocTy> &Entry,
2230 Type *&ResultTy) {
2231 // If the type was already defined, diagnose the redefinition.
2232 if (Entry.first && !Entry.second.isValid())
2233 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002234
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002235 // If we have opaque, just return without filling in the definition for the
2236 // struct. This counts as a definition as far as the .ll file goes.
2237 if (EatIfPresent(lltok::kw_opaque)) {
2238 // This type is being defined, so clear the location to indicate this.
2239 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002240
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002241 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002242 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002243 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002244 ResultTy = Entry.first;
2245 return false;
2246 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002248 // If the type starts with '<', then it is either a packed struct or a vector.
2249 bool isPacked = EatIfPresent(lltok::less);
2250
2251 // If we don't have a struct, then we have a random type alias, which we
2252 // accept for compatibility with old files. These types are not allowed to be
2253 // forward referenced and not allowed to be recursive.
2254 if (Lex.getKind() != lltok::lbrace) {
2255 if (Entry.first)
2256 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002257
Craig Topper2617dcc2014-04-15 06:32:26 +00002258 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002259 if (isPacked)
2260 return ParseArrayVectorType(ResultTy, true);
2261 return ParseType(ResultTy);
2262 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002263
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264 // This type is being defined, so clear the location to indicate this.
2265 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002266
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002267 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002268 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002269 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002270
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002271 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002272
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002273 SmallVector<Type*, 8> Body;
2274 if (ParseStructBody(Body) ||
2275 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2276 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002277
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002278 STy->setBody(Body, isPacked);
2279 ResultTy = STy;
2280 return false;
2281}
2282
2283
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002285/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002287/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289/// ::= '<' '{' Type (',' Type)* '}' '>'
2290bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 assert(Lex.getKind() == lltok::lbrace);
2292 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002294 // Handle the empty struct.
2295 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297
Chris Lattnerf880ca22009-03-09 04:49:14 +00002298 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002299 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 if (ParseType(Ty)) return true;
2301 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002303 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002304 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002305
Chris Lattner3822f632009-01-02 08:05:26 +00002306 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002307 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002309
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002310 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002311 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002313 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002316 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317}
2318
2319/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2320/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322/// ::= '[' APSINTVAL 'x' Types ']'
2323/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002324bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2326 Lex.getAPSIntVal().getBitWidth() > 64)
2327 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002328
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329 LocTy SizeLoc = Lex.getLoc();
2330 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002331 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332
Chris Lattner3822f632009-01-02 08:05:26 +00002333 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2334 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335
2336 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002337 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002339
Chris Lattner3822f632009-01-02 08:05:26 +00002340 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2341 "expected end of sequential type"))
2342 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002343
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002345 if (Size == 0)
2346 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002347 if ((unsigned)Size != Size)
2348 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002349 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002350 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002351 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002353 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002355 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 }
2357 return false;
2358}
2359
2360//===----------------------------------------------------------------------===//
2361// Function Semantic Analysis.
2362//===----------------------------------------------------------------------===//
2363
Chris Lattner3432c622009-10-28 03:39:23 +00002364LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2365 int functionNumber)
2366 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367
2368 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002369 for (Argument &A : F.args())
2370 if (!A.hasName())
2371 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372}
2373
2374LLParser::PerFunctionState::~PerFunctionState() {
2375 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002376
David Blaikie9ebdc692015-09-21 21:07:50 +00002377 for (const auto &P : ForwardRefVals) {
2378 if (isa<BasicBlock>(P.second.first))
2379 continue;
2380 P.second.first->replaceAllUsesWith(
2381 UndefValue::get(P.second.first->getType()));
2382 delete P.second.first;
2383 }
2384
2385 for (const auto &P : ForwardRefValIDs) {
2386 if (isa<BasicBlock>(P.second.first))
2387 continue;
2388 P.second.first->replaceAllUsesWith(
2389 UndefValue::get(P.second.first->getType()));
2390 delete P.second.first;
2391 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392}
2393
Chris Lattner3432c622009-10-28 03:39:23 +00002394bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 if (!ForwardRefVals.empty())
2396 return P.Error(ForwardRefVals.begin()->second.second,
2397 "use of undefined value '%" + ForwardRefVals.begin()->first +
2398 "'");
2399 if (!ForwardRefValIDs.empty())
2400 return P.Error(ForwardRefValIDs.begin()->second.second,
2401 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002402 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 return false;
2404}
2405
2406
2407/// GetVal - Get a value with the specified name or ID, creating a
2408/// forward reference record if needed. This can return null if the value
2409/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002410Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002411 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412 // Look this name up in the normal function symbol table.
2413 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002414
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 // If this is a forward reference for the value, see if we already created a
2416 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002417 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002418 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 if (I != ForwardRefVals.end())
2420 Val = I->second.first;
2421 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002422
Chris Lattnerac161bf2009-01-02 07:01:27 +00002423 // If we have the value in the symbol table or fwd-ref table, return it.
2424 if (Val) {
2425 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002426 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 P.Error(Loc, "'%" + Name + "' is not a basic block");
2428 else
2429 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002430 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002431 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002435 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002437 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002439
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 // Otherwise, create a new forward reference for this value and remember it.
2441 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002442 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002443 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002444 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002445 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002446 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002447
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2449 return FwdVal;
2450}
2451
David Majnemer8a1c45d2015-12-12 05:38:55 +00002452Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002454 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002455
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 // If this is a forward reference for the value, see if we already created a
2457 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002458 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002459 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 if (I != ForwardRefValIDs.end())
2461 Val = I->second.first;
2462 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 // If we have the value in the symbol table or fwd-ref table, return it.
2465 if (Val) {
2466 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002467 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002468 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002470 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002471 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002472 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002475 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002477 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002479
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480 // Otherwise, create a new forward reference for this value and remember it.
2481 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002482 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002483 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002484 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002485 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002486 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2489 return FwdVal;
2490}
2491
2492/// SetInstName - After an instruction is parsed and inserted into its
2493/// basic block, this installs its name.
2494bool LLParser::PerFunctionState::SetInstName(int NameID,
2495 const std::string &NameStr,
2496 LocTy NameLoc, Instruction *Inst) {
2497 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002498 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002499 if (NameID != -1 || !NameStr.empty())
2500 return P.Error(NameLoc, "instructions returning void cannot have a name");
2501 return false;
2502 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002503
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 // If this was a numbered instruction, verify that the instruction is the
2505 // expected value and resolve any forward references.
2506 if (NameStr.empty()) {
2507 // If neither a name nor an ID was specified, just use the next ID.
2508 if (NameID == -1)
2509 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002510
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 if (unsigned(NameID) != NumberedVals.size())
2512 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002513 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
David Blaikie9ebdc692015-09-21 21:07:50 +00002515 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002517 Value *Sentinel = FI->second.first;
2518 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002519 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002520 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002521
2522 Sentinel->replaceAllUsesWith(Inst);
2523 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 ForwardRefValIDs.erase(FI);
2525 }
2526
2527 NumberedVals.push_back(Inst);
2528 return false;
2529 }
2530
2531 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002532 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002534 Value *Sentinel = FI->second.first;
2535 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002537 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002538
2539 Sentinel->replaceAllUsesWith(Inst);
2540 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 ForwardRefVals.erase(FI);
2542 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002543
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 // Set the name on the instruction.
2545 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002546
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002547 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002548 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 NameStr + "'");
2550 return false;
2551}
2552
2553/// GetBB - Get a basic block with the specified name or ID, creating a
2554/// forward reference record if needed.
2555BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2556 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002557 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2558 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559}
2560
2561BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002562 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2563 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564}
2565
2566/// DefineBB - Define the specified basic block, which is either named or
2567/// unnamed. If there is an error, this returns null otherwise it returns
2568/// the block being defined.
2569BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2570 LocTy Loc) {
2571 BasicBlock *BB;
2572 if (Name.empty())
2573 BB = GetBB(NumberedVals.size(), Loc);
2574 else
2575 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002576 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002577
Chris Lattnerac161bf2009-01-02 07:01:27 +00002578 // Move the block to the end of the function. Forward ref'd blocks are
2579 // inserted wherever they happen to be referenced.
2580 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002581
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 // Remove the block from forward ref sets.
2583 if (Name.empty()) {
2584 ForwardRefValIDs.erase(NumberedVals.size());
2585 NumberedVals.push_back(BB);
2586 } else {
2587 // BB forward references are already in the function symbol table.
2588 ForwardRefVals.erase(Name);
2589 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002590
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591 return BB;
2592}
2593
2594//===----------------------------------------------------------------------===//
2595// Constants.
2596//===----------------------------------------------------------------------===//
2597
2598/// ParseValID - Parse an abstract value that doesn't necessarily have a
2599/// type implied. For example, if we parse "4" we don't know what integer type
2600/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002601/// sanity. PFS is used to convert function-local operands of metadata (since
2602/// metadata operands are not just parsed here but also converted to values).
2603/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002604bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 ID.Loc = Lex.getLoc();
2606 switch (Lex.getKind()) {
2607 default: return TokError("expected value token");
2608 case lltok::GlobalID: // @42
2609 ID.UIntVal = Lex.getUIntVal();
2610 ID.Kind = ValID::t_GlobalID;
2611 break;
2612 case lltok::GlobalVar: // @foo
2613 ID.StrVal = Lex.getStrVal();
2614 ID.Kind = ValID::t_GlobalName;
2615 break;
2616 case lltok::LocalVarID: // %42
2617 ID.UIntVal = Lex.getUIntVal();
2618 ID.Kind = ValID::t_LocalID;
2619 break;
2620 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 ID.StrVal = Lex.getStrVal();
2622 ID.Kind = ValID::t_LocalName;
2623 break;
2624 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002625 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 ID.Kind = ValID::t_APSInt;
2627 break;
2628 case lltok::APFloat:
2629 ID.APFloatVal = Lex.getAPFloatVal();
2630 ID.Kind = ValID::t_APFloat;
2631 break;
2632 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002633 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002634 ID.Kind = ValID::t_Constant;
2635 break;
2636 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002637 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 ID.Kind = ValID::t_Constant;
2639 break;
2640 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2641 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2642 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002643 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002644
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 case lltok::lbrace: {
2646 // ValID ::= '{' ConstVector '}'
2647 Lex.Lex();
2648 SmallVector<Constant*, 16> Elts;
2649 if (ParseGlobalValueVector(Elts) ||
2650 ParseToken(lltok::rbrace, "expected end of struct constant"))
2651 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
David Blaikieadbda4b2015-08-03 20:08:41 +00002653 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002654 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002655 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2656 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002657 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 return false;
2659 }
2660 case lltok::less: {
2661 // ValID ::= '<' ConstVector '>' --> Vector.
2662 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2663 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002664 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002665
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 SmallVector<Constant*, 16> Elts;
2667 LocTy FirstEltLoc = Lex.getLoc();
2668 if (ParseGlobalValueVector(Elts) ||
2669 (isPackedStruct &&
2670 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2671 ParseToken(lltok::greater, "expected end of constant"))
2672 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002675 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2676 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2677 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002678 ID.UIntVal = Elts.size();
2679 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 return false;
2681 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002682
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 if (Elts.empty())
2684 return Error(ID.Loc, "constant vector must not be empty");
2685
Duncan Sands9dff9be2010-02-15 16:12:20 +00002686 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002687 !Elts[0]->getType()->isFloatingPointTy() &&
2688 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002689 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002690 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002691
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 // Verify that all the vector elements have the same type.
2693 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2694 if (Elts[i]->getType() != Elts[0]->getType())
2695 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002696 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002697 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002698
Chris Lattner69229312011-02-15 00:14:00 +00002699 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 ID.Kind = ValID::t_Constant;
2701 return false;
2702 }
2703 case lltok::lsquare: { // Array Constant
2704 Lex.Lex();
2705 SmallVector<Constant*, 16> Elts;
2706 LocTy FirstEltLoc = Lex.getLoc();
2707 if (ParseGlobalValueVector(Elts) ||
2708 ParseToken(lltok::rsquare, "expected end of array constant"))
2709 return true;
2710
2711 // Handle empty element.
2712 if (Elts.empty()) {
2713 // Use undef instead of an array because it's inconvenient to determine
2714 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002715 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 return false;
2717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002718
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002720 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002721 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002722
Owen Anderson4056ca92009-07-29 22:17:13 +00002723 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002724
Chris Lattnerac161bf2009-01-02 07:01:27 +00002725 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002726 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 if (Elts[i]->getType() != Elts[0]->getType())
2728 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002729 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002730 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002731 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002732
Jay Foad83be3612011-06-22 09:24:39 +00002733 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 ID.Kind = ValID::t_Constant;
2735 return false;
2736 }
2737 case lltok::kw_c: // c "foo"
2738 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002739 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2740 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2742 ID.Kind = ValID::t_Constant;
2743 return false;
2744
2745 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002746 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2747 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002748 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 Lex.Lex();
2750 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002751 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002752 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002753 ParseStringConstant(ID.StrVal) ||
2754 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 ParseToken(lltok::StringConstant, "expected constraint string"))
2756 return true;
2757 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002758 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002759 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002760 ID.Kind = ValID::t_InlineAsm;
2761 return false;
2762 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002763
Chris Lattner3432c622009-10-28 03:39:23 +00002764 case lltok::kw_blockaddress: {
2765 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2766 Lex.Lex();
2767
2768 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002769
Chris Lattner3432c622009-10-28 03:39:23 +00002770 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2771 ParseValID(Fn) ||
2772 ParseToken(lltok::comma, "expected comma in block address expression")||
2773 ParseValID(Label) ||
2774 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2775 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002776
Chris Lattner3432c622009-10-28 03:39:23 +00002777 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2778 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002779 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002780 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002781
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002782 // Try to find the function (but skip it if it's forward-referenced).
2783 GlobalValue *GV = nullptr;
2784 if (Fn.Kind == ValID::t_GlobalID) {
2785 if (Fn.UIntVal < NumberedVals.size())
2786 GV = NumberedVals[Fn.UIntVal];
2787 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2788 GV = M->getNamedValue(Fn.StrVal);
2789 }
2790 Function *F = nullptr;
2791 if (GV) {
2792 // Confirm that it's actually a function with a definition.
2793 if (!isa<Function>(GV))
2794 return Error(Fn.Loc, "expected function name in blockaddress");
2795 F = cast<Function>(GV);
2796 if (F->isDeclaration())
2797 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2798 }
2799
2800 if (!F) {
2801 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002802 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002803 ForwardRefBlockAddresses.insert(std::make_pair(
2804 std::move(Fn),
2805 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002806 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2807 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002808 if (!FwdRef)
2809 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2810 GlobalValue::InternalLinkage, nullptr, "");
2811 ID.ConstantVal = FwdRef;
2812 ID.Kind = ValID::t_Constant;
2813 return false;
2814 }
2815
2816 // We found the function; now find the basic block. Don't use PFS, since we
2817 // might be inside a constant expression.
2818 BasicBlock *BB;
2819 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2820 if (Label.Kind == ValID::t_LocalID)
2821 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2822 else
2823 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2824 if (!BB)
2825 return Error(Label.Loc, "referenced value is not a basic block");
2826 } else {
2827 if (Label.Kind == ValID::t_LocalID)
2828 return Error(Label.Loc, "cannot take address of numeric label after "
2829 "the function is defined");
2830 BB = dyn_cast_or_null<BasicBlock>(
2831 F->getValueSymbolTable().lookup(Label.StrVal));
2832 if (!BB)
2833 return Error(Label.Loc, "referenced value is not a basic block");
2834 }
2835
2836 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002837 ID.Kind = ValID::t_Constant;
2838 return false;
2839 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002840
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 case lltok::kw_trunc:
2842 case lltok::kw_zext:
2843 case lltok::kw_sext:
2844 case lltok::kw_fptrunc:
2845 case lltok::kw_fpext:
2846 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002847 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002848 case lltok::kw_uitofp:
2849 case lltok::kw_sitofp:
2850 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002851 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002853 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002854 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002855 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 Constant *SrcVal;
2857 Lex.Lex();
2858 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2859 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002860 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002861 ParseType(DestTy) ||
2862 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2863 return true;
2864 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2865 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002866 getTypeString(SrcVal->getType()) + "' to '" +
2867 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002869 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002870 ID.Kind = ValID::t_Constant;
2871 return false;
2872 }
2873 case lltok::kw_extractvalue: {
2874 Lex.Lex();
2875 Constant *Val;
2876 SmallVector<unsigned, 4> Indices;
2877 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2878 ParseGlobalTypeAndValue(Val) ||
2879 ParseIndexList(Indices) ||
2880 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2881 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002882
Chris Lattner392be582010-02-12 20:49:41 +00002883 if (!Val->getType()->isAggregateType())
2884 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002885 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002886 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002887 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002888 ID.Kind = ValID::t_Constant;
2889 return false;
2890 }
2891 case lltok::kw_insertvalue: {
2892 Lex.Lex();
2893 Constant *Val0, *Val1;
2894 SmallVector<unsigned, 4> Indices;
2895 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2896 ParseGlobalTypeAndValue(Val0) ||
2897 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2898 ParseGlobalTypeAndValue(Val1) ||
2899 ParseIndexList(Indices) ||
2900 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2901 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002902 if (!Val0->getType()->isAggregateType())
2903 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002904 Type *IndexedType =
2905 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2906 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002907 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002908 if (IndexedType != Val1->getType())
2909 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2910 getTypeString(Val1->getType()) +
2911 "' instead of '" + getTypeString(IndexedType) +
2912 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002913 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 ID.Kind = ValID::t_Constant;
2915 return false;
2916 }
2917 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002918 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002919 unsigned PredVal, Opc = Lex.getUIntVal();
2920 Constant *Val0, *Val1;
2921 Lex.Lex();
2922 if (ParseCmpPredicate(PredVal, Opc) ||
2923 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2924 ParseGlobalTypeAndValue(Val0) ||
2925 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2926 ParseGlobalTypeAndValue(Val1) ||
2927 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2928 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002929
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 if (Val0->getType() != Val1->getType())
2931 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002932
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002934
Chris Lattnerac161bf2009-01-02 07:01:27 +00002935 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002936 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002937 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002938 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002939 } else {
2940 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002941 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002942 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002943 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002944 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002945 }
2946 ID.Kind = ValID::t_Constant;
2947 return false;
2948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002949
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950 // Binary Operators.
2951 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002952 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002953 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002954 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002955 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002956 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002957 case lltok::kw_udiv:
2958 case lltok::kw_sdiv:
2959 case lltok::kw_fdiv:
2960 case lltok::kw_urem:
2961 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002962 case lltok::kw_frem:
2963 case lltok::kw_shl:
2964 case lltok::kw_lshr:
2965 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002966 bool NUW = false;
2967 bool NSW = false;
2968 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 unsigned Opc = Lex.getUIntVal();
2970 Constant *Val0, *Val1;
2971 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002972 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002973 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2974 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002975 if (EatIfPresent(lltok::kw_nuw))
2976 NUW = true;
2977 if (EatIfPresent(lltok::kw_nsw)) {
2978 NSW = true;
2979 if (EatIfPresent(lltok::kw_nuw))
2980 NUW = true;
2981 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002982 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2983 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002984 if (EatIfPresent(lltok::kw_exact))
2985 Exact = true;
2986 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002987 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2988 ParseGlobalTypeAndValue(Val0) ||
2989 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2990 ParseGlobalTypeAndValue(Val1) ||
2991 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2992 return true;
2993 if (Val0->getType() != Val1->getType())
2994 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002995 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002996 if (NUW)
2997 return Error(ModifierLoc, "nuw only applies to integer operations");
2998 if (NSW)
2999 return Error(ModifierLoc, "nsw only applies to integer operations");
3000 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003001 // Check that the type is valid for the operator.
3002 switch (Opc) {
3003 case Instruction::Add:
3004 case Instruction::Sub:
3005 case Instruction::Mul:
3006 case Instruction::UDiv:
3007 case Instruction::SDiv:
3008 case Instruction::URem:
3009 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003010 case Instruction::Shl:
3011 case Instruction::AShr:
3012 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003013 if (!Val0->getType()->isIntOrIntVectorTy())
3014 return Error(ID.Loc, "constexpr requires integer operands");
3015 break;
3016 case Instruction::FAdd:
3017 case Instruction::FSub:
3018 case Instruction::FMul:
3019 case Instruction::FDiv:
3020 case Instruction::FRem:
3021 if (!Val0->getType()->isFPOrFPVectorTy())
3022 return Error(ID.Loc, "constexpr requires fp operands");
3023 break;
3024 default: llvm_unreachable("Unknown binary operator!");
3025 }
Dan Gohman1b849082009-09-07 23:54:19 +00003026 unsigned Flags = 0;
3027 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3028 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003029 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003030 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003031 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 ID.Kind = ValID::t_Constant;
3033 return false;
3034 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003035
Chris Lattnerac161bf2009-01-02 07:01:27 +00003036 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 case lltok::kw_and:
3038 case lltok::kw_or:
3039 case lltok::kw_xor: {
3040 unsigned Opc = Lex.getUIntVal();
3041 Constant *Val0, *Val1;
3042 Lex.Lex();
3043 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3044 ParseGlobalTypeAndValue(Val0) ||
3045 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3046 ParseGlobalTypeAndValue(Val1) ||
3047 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3048 return true;
3049 if (Val0->getType() != Val1->getType())
3050 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003051 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 return Error(ID.Loc,
3053 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003054 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055 ID.Kind = ValID::t_Constant;
3056 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003057 }
3058
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 case lltok::kw_getelementptr:
3060 case lltok::kw_shufflevector:
3061 case lltok::kw_insertelement:
3062 case lltok::kw_extractelement:
3063 case lltok::kw_select: {
3064 unsigned Opc = Lex.getUIntVal();
3065 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003066 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003067 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003069
Dan Gohman1639c392009-07-27 21:53:46 +00003070 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003071 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003072
3073 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3074 return true;
3075
3076 LocTy ExplicitTypeLoc = Lex.getLoc();
3077 if (Opc == Instruction::GetElementPtr) {
3078 if (ParseType(Ty) ||
3079 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3080 return true;
3081 }
3082
3083 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003084 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3085 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003086
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003088 if (Elts.size() == 0 ||
3089 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003090 return Error(ID.Loc, "base of getelementptr must be a pointer");
3091
3092 Type *BaseType = Elts[0]->getType();
3093 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003094 if (Ty != BasePointerType->getElementType())
3095 return Error(
3096 ExplicitTypeLoc,
3097 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003098
Jay Foaded8db7d2011-07-21 14:31:17 +00003099 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003100 for (Constant *Val : Indices) {
3101 Type *ValTy = Val->getType();
3102 if (!ValTy->getScalarType()->isIntegerTy())
3103 return Error(ID.Loc, "getelementptr index must be an integer");
3104 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3105 return Error(ID.Loc, "getelementptr index type missmatch");
3106 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003107 unsigned ValNumEl = ValTy->getVectorNumElements();
3108 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003109 if (ValNumEl != PtrNumEl)
3110 return Error(
3111 ID.Loc,
3112 "getelementptr vector index has a wrong number of elements");
3113 }
3114 }
3115
Craig Toppere3dcce92015-08-01 22:20:21 +00003116 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003117 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003118 return Error(ID.Loc, "base element of getelementptr must be sized");
3119
David Blaikie4a2e73b2015-04-02 18:55:32 +00003120 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003121 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003122 ID.ConstantVal =
3123 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 } else if (Opc == Instruction::Select) {
3125 if (Elts.size() != 3)
3126 return Error(ID.Loc, "expected three operands to select");
3127 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3128 Elts[2]))
3129 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003130 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003131 } else if (Opc == Instruction::ShuffleVector) {
3132 if (Elts.size() != 3)
3133 return Error(ID.Loc, "expected three operands to shufflevector");
3134 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3135 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003136 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003137 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003138 } else if (Opc == Instruction::ExtractElement) {
3139 if (Elts.size() != 2)
3140 return Error(ID.Loc, "expected two operands to extractelement");
3141 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3142 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003143 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144 } else {
3145 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3146 if (Elts.size() != 3)
3147 return Error(ID.Loc, "expected three operands to insertelement");
3148 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3149 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003150 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003151 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003152 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003153
Chris Lattnerac161bf2009-01-02 07:01:27 +00003154 ID.Kind = ValID::t_Constant;
3155 return false;
3156 }
3157 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003158
Chris Lattnerac161bf2009-01-02 07:01:27 +00003159 Lex.Lex();
3160 return false;
3161}
3162
3163/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003164bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003165 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003166 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003167 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003168 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003169 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003170 if (V && !(C = dyn_cast<Constant>(V)))
3171 return Error(ID.Loc, "global values must be constants");
3172 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003173}
3174
Victor Hernandez9d75c962010-01-11 22:31:58 +00003175bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003176 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003177 return ParseType(Ty) ||
3178 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003179}
3180
Rafael Espindola83a362c2015-01-06 22:55:16 +00003181bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003182 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003183
3184 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003185 if (!EatIfPresent(lltok::kw_comdat))
3186 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003187
3188 if (EatIfPresent(lltok::lparen)) {
3189 if (Lex.getKind() != lltok::ComdatVar)
3190 return TokError("expected comdat variable");
3191 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3192 Lex.Lex();
3193 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3194 return true;
3195 } else {
3196 if (GlobalName.empty())
3197 return TokError("comdat cannot be unnamed");
3198 C = getComdat(GlobalName, KwLoc);
3199 }
3200
David Majnemerdad0a642014-06-27 18:19:56 +00003201 return false;
3202}
3203
Victor Hernandez9d75c962010-01-11 22:31:58 +00003204/// ParseGlobalValueVector
3205/// ::= /*empty*/
3206/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003207bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003208 // Empty list.
3209 if (Lex.getKind() == lltok::rbrace ||
3210 Lex.getKind() == lltok::rsquare ||
3211 Lex.getKind() == lltok::greater ||
3212 Lex.getKind() == lltok::rparen)
3213 return false;
3214
3215 Constant *C;
3216 if (ParseGlobalTypeAndValue(C)) return true;
3217 Elts.push_back(C);
3218
3219 while (EatIfPresent(lltok::comma)) {
3220 if (ParseGlobalTypeAndValue(C)) return true;
3221 Elts.push_back(C);
3222 }
3223
3224 return false;
3225}
3226
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003227bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003228 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003229 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003230 return true;
3231
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003232 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003233 return false;
3234}
3235
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003236/// MDNode:
3237/// ::= !{ ... }
3238/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003239/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003240bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003241 if (Lex.getKind() == lltok::MetadataVar)
3242 return ParseSpecializedMDNode(N);
3243
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003244 return ParseToken(lltok::exclaim, "expected '!' here") ||
3245 ParseMDNodeTail(N);
3246}
3247
3248bool LLParser::ParseMDNodeTail(MDNode *&N) {
3249 // !{ ... }
3250 if (Lex.getKind() == lltok::lbrace)
3251 return ParseMDTuple(N);
3252
3253 // !42
3254 return ParseMDNodeID(N);
3255}
3256
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003257namespace {
3258
3259/// Structure to represent an optional metadata field.
3260template <class FieldTy> struct MDFieldImpl {
3261 typedef MDFieldImpl ImplTy;
3262 FieldTy Val;
3263 bool Seen;
3264
3265 void assign(FieldTy Val) {
3266 Seen = true;
3267 this->Val = std::move(Val);
3268 }
3269
3270 explicit MDFieldImpl(FieldTy Default)
3271 : Val(std::move(Default)), Seen(false) {}
3272};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003273
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003274struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3275 uint64_t Max;
3276
3277 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3278 : ImplTy(Default), Max(Max) {}
3279};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003280struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003281 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003282};
3283struct ColumnField : public MDUnsignedField {
3284 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3285};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003286struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003287 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003288 DwarfTagField(dwarf::Tag DefaultTag)
3289 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003290};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003291struct DwarfMacinfoTypeField : public MDUnsignedField {
3292 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3293 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3294 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3295};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003296struct DwarfAttEncodingField : public MDUnsignedField {
3297 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3298};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003299struct DwarfVirtualityField : public MDUnsignedField {
3300 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3301};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003302struct DwarfLangField : public MDUnsignedField {
3303 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3304};
Adrian Prantlb939a252016-03-31 23:56:58 +00003305struct EmissionKindField : public MDUnsignedField {
3306 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3307};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003308
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003309struct DIFlagField : public MDUnsignedField {
3310 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3311};
3312
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003313struct MDSignedField : public MDFieldImpl<int64_t> {
3314 int64_t Min;
3315 int64_t Max;
3316
3317 MDSignedField(int64_t Default = 0)
3318 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3319 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3320 : ImplTy(Default), Min(Min), Max(Max) {}
3321};
3322
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003323struct MDBoolField : public MDFieldImpl<bool> {
3324 MDBoolField(bool Default = false) : ImplTy(Default) {}
3325};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003326struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003327 bool AllowNull;
3328
3329 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003330};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003331struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3332 MDConstant() : ImplTy(nullptr) {}
3333};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003334struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003335 bool AllowEmpty;
3336 MDStringField(bool AllowEmpty = true)
3337 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003338};
3339struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3340 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3341};
3342
3343} // end namespace
3344
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003345namespace llvm {
3346
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003347template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003348bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003349 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003350 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3351 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003352
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003353 auto &U = Lex.getAPSIntVal();
3354 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003355 return TokError("value for '" + Name + "' too large, limit is " +
3356 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003357 Result.assign(U.getZExtValue());
3358 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003359 Lex.Lex();
3360 return false;
3361}
3362
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003363template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003364bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3365 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3366}
3367template <>
3368bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3369 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3370}
3371
3372template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003373bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3374 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003375 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003376
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003377 if (Lex.getKind() != lltok::DwarfTag)
3378 return TokError("expected DWARF tag");
3379
3380 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3381 if (Tag == dwarf::DW_TAG_invalid)
3382 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003383 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003384
3385 Result.assign(Tag);
3386 Lex.Lex();
3387 return false;
3388}
3389
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003390template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003391bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003392 DwarfMacinfoTypeField &Result) {
3393 if (Lex.getKind() == lltok::APSInt)
3394 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3395
3396 if (Lex.getKind() != lltok::DwarfMacinfo)
3397 return TokError("expected DWARF macinfo type");
3398
3399 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3400 if (Macinfo == dwarf::DW_MACINFO_invalid)
3401 return TokError(
3402 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3403 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3404
3405 Result.assign(Macinfo);
3406 Lex.Lex();
3407 return false;
3408}
3409
3410template <>
3411bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003412 DwarfVirtualityField &Result) {
3413 if (Lex.getKind() == lltok::APSInt)
3414 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3415
3416 if (Lex.getKind() != lltok::DwarfVirtuality)
3417 return TokError("expected DWARF virtuality code");
3418
3419 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003420 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003421 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3422 Lex.getStrVal() + "'");
3423 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3424 Result.assign(Virtuality);
3425 Lex.Lex();
3426 return false;
3427}
3428
3429template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003430bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3431 if (Lex.getKind() == lltok::APSInt)
3432 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3433
3434 if (Lex.getKind() != lltok::DwarfLang)
3435 return TokError("expected DWARF language");
3436
3437 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3438 if (!Lang)
3439 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3440 "'");
3441 assert(Lang <= Result.Max && "Expected valid DWARF language");
3442 Result.assign(Lang);
3443 Lex.Lex();
3444 return false;
3445}
3446
3447template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003448bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3449 if (Lex.getKind() == lltok::APSInt)
3450 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3451
3452 if (Lex.getKind() != lltok::EmissionKind)
3453 return TokError("expected emission kind");
3454
3455 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3456 if (!Kind)
3457 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3458 "'");
3459 assert(*Kind <= Result.Max && "Expected valid emission kind");
3460 Result.assign(*Kind);
3461 Lex.Lex();
3462 return false;
3463}
3464
3465template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003466bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003467 DwarfAttEncodingField &Result) {
3468 if (Lex.getKind() == lltok::APSInt)
3469 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3470
3471 if (Lex.getKind() != lltok::DwarfAttEncoding)
3472 return TokError("expected DWARF type attribute encoding");
3473
3474 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3475 if (!Encoding)
3476 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3477 Lex.getStrVal() + "'");
3478 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3479 Result.assign(Encoding);
3480 Lex.Lex();
3481 return false;
3482}
3483
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003484/// DIFlagField
3485/// ::= uint32
3486/// ::= DIFlagVector
3487/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3488template <>
3489bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3490 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3491
3492 // Parser for a single flag.
3493 auto parseFlag = [&](unsigned &Val) {
3494 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3495 return ParseUInt32(Val);
3496
3497 if (Lex.getKind() != lltok::DIFlag)
3498 return TokError("expected debug info flag");
3499
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003500 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003501 if (!Val)
3502 return TokError(Twine("invalid debug info flag flag '") +
3503 Lex.getStrVal() + "'");
3504 Lex.Lex();
3505 return false;
3506 };
3507
3508 // Parse the flags and combine them together.
3509 unsigned Combined = 0;
3510 do {
3511 unsigned Val;
3512 if (parseFlag(Val))
3513 return true;
3514 Combined |= Val;
3515 } while (EatIfPresent(lltok::bar));
3516
3517 Result.assign(Combined);
3518 return false;
3519}
3520
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003521template <>
3522bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003523 MDSignedField &Result) {
3524 if (Lex.getKind() != lltok::APSInt)
3525 return TokError("expected signed integer");
3526
3527 auto &S = Lex.getAPSIntVal();
3528 if (S < Result.Min)
3529 return TokError("value for '" + Name + "' too small, limit is " +
3530 Twine(Result.Min));
3531 if (S > Result.Max)
3532 return TokError("value for '" + Name + "' too large, limit is " +
3533 Twine(Result.Max));
3534 Result.assign(S.getExtValue());
3535 assert(Result.Val >= Result.Min && "Expected value in range");
3536 assert(Result.Val <= Result.Max && "Expected value in range");
3537 Lex.Lex();
3538 return false;
3539}
3540
3541template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003542bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3543 switch (Lex.getKind()) {
3544 default:
3545 return TokError("expected 'true' or 'false'");
3546 case lltok::kw_true:
3547 Result.assign(true);
3548 break;
3549 case lltok::kw_false:
3550 Result.assign(false);
3551 break;
3552 }
3553 Lex.Lex();
3554 return false;
3555}
3556
3557template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003558bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003559 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003560 if (!Result.AllowNull)
3561 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003562 Lex.Lex();
3563 Result.assign(nullptr);
3564 return false;
3565 }
3566
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003567 Metadata *MD;
3568 if (ParseMetadata(MD, nullptr))
3569 return true;
3570
3571 Result.assign(MD);
3572 return false;
3573}
3574
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003575template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003576bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3577 Metadata *MD;
3578 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3579 return true;
3580
3581 Result.assign(cast<ConstantAsMetadata>(MD));
3582 return false;
3583}
3584
3585template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003586bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003587 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003588 std::string S;
3589 if (ParseStringConstant(S))
3590 return true;
3591
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003592 if (!Result.AllowEmpty && S.empty())
3593 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3594
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003595 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003596 return false;
3597}
3598
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003599template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003600bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3601 SmallVector<Metadata *, 4> MDs;
3602 if (ParseMDNodeVector(MDs))
3603 return true;
3604
3605 Result.assign(std::move(MDs));
3606 return false;
3607}
3608
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003609} // end namespace llvm
3610
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003611template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003612bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003613 do {
3614 if (Lex.getKind() != lltok::LabelStr)
3615 return TokError("expected field label here");
3616
3617 if (parseField())
3618 return true;
3619 } while (EatIfPresent(lltok::comma));
3620
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003621 return false;
3622}
3623
3624template <class ParserTy>
3625bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3626 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3627 Lex.Lex();
3628
3629 if (ParseToken(lltok::lparen, "expected '(' here"))
3630 return true;
3631 if (Lex.getKind() != lltok::rparen)
3632 if (ParseMDFieldsImplBody(parseField))
3633 return true;
3634
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003635 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003636 return ParseToken(lltok::rparen, "expected ')' here");
3637}
3638
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003639template <class FieldTy>
3640bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3641 if (Result.Seen)
3642 return TokError("field '" + Name + "' cannot be specified more than once");
3643
3644 LocTy Loc = Lex.getLoc();
3645 Lex.Lex();
3646 return ParseMDField(Loc, Name, Result);
3647}
3648
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003649bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3650 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003651
3652#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003653 if (Lex.getStrVal() == #CLASS) \
3654 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003655#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003656
3657 return TokError("expected metadata type");
3658}
3659
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003660#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3661#define NOP_FIELD(NAME, TYPE, INIT)
3662#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3663 if (!NAME.Seen) \
3664 return Error(ClosingLoc, "missing required field '" #NAME "'");
3665#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003666 if (Lex.getStrVal() == #NAME) \
3667 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003668#define PARSE_MD_FIELDS() \
3669 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3670 do { \
3671 LocTy ClosingLoc; \
3672 if (ParseMDFieldsImpl([&]() -> bool { \
3673 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3674 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3675 }, ClosingLoc)) \
3676 return true; \
3677 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3678 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003679#define GET_OR_DISTINCT(CLASS, ARGS) \
3680 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003681
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003682/// ParseDILocationFields:
3683/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3684bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003685#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003686 OPTIONAL(line, LineField, ); \
3687 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003688 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003689 OPTIONAL(inlinedAt, MDField, );
3690 PARSE_MD_FIELDS();
3691#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003692
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003693 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003694 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003695 return false;
3696}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003697
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003698/// ParseGenericDINode:
3699/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3700bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003701#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003702 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003703 OPTIONAL(header, MDStringField, ); \
3704 OPTIONAL(operands, MDFieldList, );
3705 PARSE_MD_FIELDS();
3706#undef VISIT_MD_FIELDS
3707
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003708 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003709 (Context, tag.Val, header.Val, operands.Val));
3710 return false;
3711}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003712
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003713/// ParseDISubrange:
3714/// ::= !DISubrange(count: 30, lowerBound: 2)
3715bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003716#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003717 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003718 OPTIONAL(lowerBound, MDSignedField, );
3719 PARSE_MD_FIELDS();
3720#undef VISIT_MD_FIELDS
3721
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003722 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003723 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003724}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003725
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003726/// ParseDIEnumerator:
3727/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3728bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003729#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003730 REQUIRED(name, MDStringField, ); \
3731 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003732 PARSE_MD_FIELDS();
3733#undef VISIT_MD_FIELDS
3734
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003735 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003736 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003737}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003738
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003739/// ParseDIBasicType:
3740/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3741bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003742#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003743 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003744 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003745 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3746 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003747 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003748 PARSE_MD_FIELDS();
3749#undef VISIT_MD_FIELDS
3750
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003751 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003752 align.Val, encoding.Val));
3753 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003754}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003755
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003756/// ParseDIDerivedType:
3757/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003758/// line: 7, scope: !1, baseType: !2, size: 32,
3759/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003760bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003761#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3762 REQUIRED(tag, DwarfTagField, ); \
3763 OPTIONAL(name, MDStringField, ); \
3764 OPTIONAL(file, MDField, ); \
3765 OPTIONAL(line, LineField, ); \
3766 OPTIONAL(scope, MDField, ); \
3767 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003768 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3769 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3770 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003771 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003772 OPTIONAL(extraData, MDField, );
3773 PARSE_MD_FIELDS();
3774#undef VISIT_MD_FIELDS
3775
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003776 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003777 (Context, tag.Val, name.Val, file.Val, line.Val,
3778 scope.Val, baseType.Val, size.Val, align.Val,
3779 offset.Val, flags.Val, extraData.Val));
3780 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003781}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003782
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003784#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3785 REQUIRED(tag, DwarfTagField, ); \
3786 OPTIONAL(name, MDStringField, ); \
3787 OPTIONAL(file, MDField, ); \
3788 OPTIONAL(line, LineField, ); \
3789 OPTIONAL(scope, MDField, ); \
3790 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003791 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3792 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3793 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003794 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003795 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003796 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003797 OPTIONAL(vtableHolder, MDField, ); \
3798 OPTIONAL(templateParams, MDField, ); \
3799 OPTIONAL(identifier, MDStringField, );
3800 PARSE_MD_FIELDS();
3801#undef VISIT_MD_FIELDS
3802
3803 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003804 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003805 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3806 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3807 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3808 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003809}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003810
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003811bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003812#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003813 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003814 REQUIRED(types, MDField, );
3815 PARSE_MD_FIELDS();
3816#undef VISIT_MD_FIELDS
3817
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003818 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003819 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003820}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003821
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003822/// ParseDIFileType:
3823/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3824bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3826 REQUIRED(filename, MDStringField, ); \
3827 REQUIRED(directory, MDStringField, );
3828 PARSE_MD_FIELDS();
3829#undef VISIT_MD_FIELDS
3830
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003831 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003832 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003833}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003834
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003835/// ParseDICompileUnit:
3836/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003837/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003838/// splitDebugFilename: "abc.debug",
3839/// emissionKind: FullDebug,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003840/// enums: !1, retainedTypes: !2, subprograms: !3,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003841/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003842bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003843 if (!IsDistinct)
3844 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3845
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003846#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3847 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003848 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003849 OPTIONAL(producer, MDStringField, ); \
3850 OPTIONAL(isOptimized, MDBoolField, ); \
3851 OPTIONAL(flags, MDStringField, ); \
3852 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3853 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003854 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003855 OPTIONAL(enums, MDField, ); \
3856 OPTIONAL(retainedTypes, MDField, ); \
3857 OPTIONAL(subprograms, MDField, ); \
3858 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003859 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003860 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003861 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003862 PARSE_MD_FIELDS();
3863#undef VISIT_MD_FIELDS
3864
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003865 Result = DICompileUnit::getDistinct(
3866 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3867 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003868 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, macros.Val,
3869 dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003870 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003871}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003872
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003873/// ParseDISubprogram:
3874/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003875/// file: !1, line: 7, type: !2, isLocal: false,
3876/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003877/// virtuality: DW_VIRTUALTIY_pure_virtual,
3878/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003879/// isOptimized: false, templateParams: !4, declaration: !5,
3880/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003881bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003882 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003883#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3884 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003885 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003886 OPTIONAL(linkageName, MDStringField, ); \
3887 OPTIONAL(file, MDField, ); \
3888 OPTIONAL(line, LineField, ); \
3889 OPTIONAL(type, MDField, ); \
3890 OPTIONAL(isLocal, MDBoolField, ); \
3891 OPTIONAL(isDefinition, MDBoolField, (true)); \
3892 OPTIONAL(scopeLine, LineField, ); \
3893 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003894 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003895 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003896 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003897 OPTIONAL(isOptimized, MDBoolField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003898 OPTIONAL(templateParams, MDField, ); \
3899 OPTIONAL(declaration, MDField, ); \
3900 OPTIONAL(variables, MDField, );
3901 PARSE_MD_FIELDS();
3902#undef VISIT_MD_FIELDS
3903
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003904 if (isDefinition.Val && !IsDistinct)
3905 return Lex.Error(
3906 Loc,
3907 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3908
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003909 Result = GET_OR_DISTINCT(
Peter Collingbourned4bff302015-11-05 22:03:56 +00003910 DISubprogram,
3911 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
3912 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
3913 containingType.Val, virtuality.Val, virtualIndex.Val, flags.Val,
3914 isOptimized.Val, templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003915 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003916}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003917
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003918/// ParseDILexicalBlock:
3919/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3920bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003921#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003922 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003923 OPTIONAL(file, MDField, ); \
3924 OPTIONAL(line, LineField, ); \
3925 OPTIONAL(column, ColumnField, );
3926 PARSE_MD_FIELDS();
3927#undef VISIT_MD_FIELDS
3928
3929 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003930 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003931 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003932}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003933
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003934/// ParseDILexicalBlockFile:
3935/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3936bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003937#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003938 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003939 OPTIONAL(file, MDField, ); \
3940 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3941 PARSE_MD_FIELDS();
3942#undef VISIT_MD_FIELDS
3943
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003944 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003945 (Context, scope.Val, file.Val, discriminator.Val));
3946 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003947}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003948
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003949/// ParseDINamespace:
3950/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3951bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003952#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3953 REQUIRED(scope, MDField, ); \
3954 OPTIONAL(file, MDField, ); \
3955 OPTIONAL(name, MDStringField, ); \
3956 OPTIONAL(line, LineField, );
3957 PARSE_MD_FIELDS();
3958#undef VISIT_MD_FIELDS
3959
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003960 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003961 (Context, scope.Val, file.Val, name.Val, line.Val));
3962 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003963}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003964
Amjad Abouda9bcf162015-12-10 12:56:35 +00003965/// ParseDIMacro:
3966/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3967bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3968#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3969 REQUIRED(type, DwarfMacinfoTypeField, ); \
3970 REQUIRED(line, LineField, ); \
3971 REQUIRED(name, MDStringField, ); \
3972 OPTIONAL(value, MDStringField, );
3973 PARSE_MD_FIELDS();
3974#undef VISIT_MD_FIELDS
3975
3976 Result = GET_OR_DISTINCT(DIMacro,
3977 (Context, type.Val, line.Val, name.Val, value.Val));
3978 return false;
3979}
3980
3981/// ParseDIMacroFile:
3982/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
3983bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
3984#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3985 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
3986 REQUIRED(line, LineField, ); \
3987 REQUIRED(file, MDField, ); \
3988 OPTIONAL(nodes, MDField, );
3989 PARSE_MD_FIELDS();
3990#undef VISIT_MD_FIELDS
3991
3992 Result = GET_OR_DISTINCT(DIMacroFile,
3993 (Context, type.Val, line.Val, file.Val, nodes.Val));
3994 return false;
3995}
3996
3997
Adrian Prantlab1243f2015-06-29 23:03:47 +00003998/// ParseDIModule:
3999/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4000/// includePath: "/usr/include", isysroot: "/")
4001bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4003 REQUIRED(scope, MDField, ); \
4004 REQUIRED(name, MDStringField, ); \
4005 OPTIONAL(configMacros, MDStringField, ); \
4006 OPTIONAL(includePath, MDStringField, ); \
4007 OPTIONAL(isysroot, MDStringField, );
4008 PARSE_MD_FIELDS();
4009#undef VISIT_MD_FIELDS
4010
4011 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4012 configMacros.Val, includePath.Val, isysroot.Val));
4013 return false;
4014}
4015
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004016/// ParseDITemplateTypeParameter:
4017/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4018bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004019#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004020 OPTIONAL(name, MDStringField, ); \
4021 REQUIRED(type, MDField, );
4022 PARSE_MD_FIELDS();
4023#undef VISIT_MD_FIELDS
4024
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004025 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004026 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004027 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004028}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004029
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004030/// ParseDITemplateValueParameter:
4031/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004032/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004033bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004034#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004035 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004036 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004037 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004038 REQUIRED(value, MDField, );
4039 PARSE_MD_FIELDS();
4040#undef VISIT_MD_FIELDS
4041
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004042 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004043 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004044 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004045}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004046
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004047/// ParseDIGlobalVariable:
4048/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004049/// file: !1, line: 7, type: !2, isLocal: false,
4050/// isDefinition: true, variable: i32* @foo,
4051/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004052bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004053#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004054 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004055 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004056 OPTIONAL(linkageName, MDStringField, ); \
4057 OPTIONAL(file, MDField, ); \
4058 OPTIONAL(line, LineField, ); \
4059 OPTIONAL(type, MDField, ); \
4060 OPTIONAL(isLocal, MDBoolField, ); \
4061 OPTIONAL(isDefinition, MDBoolField, (true)); \
4062 OPTIONAL(variable, MDConstant, ); \
4063 OPTIONAL(declaration, MDField, );
4064 PARSE_MD_FIELDS();
4065#undef VISIT_MD_FIELDS
4066
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004067 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004068 (Context, scope.Val, name.Val, linkageName.Val,
4069 file.Val, line.Val, type.Val, isLocal.Val,
4070 isDefinition.Val, variable.Val, declaration.Val));
4071 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004072}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004073
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004074/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004075/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4076/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4077/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004078/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004079bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004080#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004081 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004082 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004083 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004084 OPTIONAL(file, MDField, ); \
4085 OPTIONAL(line, LineField, ); \
4086 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004087 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004088 PARSE_MD_FIELDS();
4089#undef VISIT_MD_FIELDS
4090
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004091 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004092 (Context, scope.Val, name.Val, file.Val, line.Val,
4093 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004094 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004095}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004096
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004097/// ParseDIExpression:
4098/// ::= !DIExpression(0, 7, -1)
4099bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004100 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4101 Lex.Lex();
4102
4103 if (ParseToken(lltok::lparen, "expected '(' here"))
4104 return true;
4105
4106 SmallVector<uint64_t, 8> Elements;
4107 if (Lex.getKind() != lltok::rparen)
4108 do {
4109 if (Lex.getKind() == lltok::DwarfOp) {
4110 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4111 Lex.Lex();
4112 Elements.push_back(Op);
4113 continue;
4114 }
4115 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4116 }
4117
4118 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4119 return TokError("expected unsigned integer");
4120
4121 auto &U = Lex.getAPSIntVal();
4122 if (U.ugt(UINT64_MAX))
4123 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4124 Elements.push_back(U.getZExtValue());
4125 Lex.Lex();
4126 } while (EatIfPresent(lltok::comma));
4127
4128 if (ParseToken(lltok::rparen, "expected ')' here"))
4129 return true;
4130
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004131 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004132 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004133}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004134
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004135/// ParseDIObjCProperty:
4136/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004137/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004138bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004139#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004140 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004141 OPTIONAL(file, MDField, ); \
4142 OPTIONAL(line, LineField, ); \
4143 OPTIONAL(setter, MDStringField, ); \
4144 OPTIONAL(getter, MDStringField, ); \
4145 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4146 OPTIONAL(type, MDField, );
4147 PARSE_MD_FIELDS();
4148#undef VISIT_MD_FIELDS
4149
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004150 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004151 (Context, name.Val, file.Val, line.Val, setter.Val,
4152 getter.Val, attributes.Val, type.Val));
4153 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004154}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004155
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004156/// ParseDIImportedEntity:
4157/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004158/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004159bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004160#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4161 REQUIRED(tag, DwarfTagField, ); \
4162 REQUIRED(scope, MDField, ); \
4163 OPTIONAL(entity, MDField, ); \
4164 OPTIONAL(line, LineField, ); \
4165 OPTIONAL(name, MDStringField, );
4166 PARSE_MD_FIELDS();
4167#undef VISIT_MD_FIELDS
4168
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004169 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004170 entity.Val, line.Val, name.Val));
4171 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004172}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004173
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004174#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004175#undef NOP_FIELD
4176#undef REQUIRE_FIELD
4177#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004178
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004179/// ParseMetadataAsValue
4180/// ::= metadata i32 %local
4181/// ::= metadata i32 @global
4182/// ::= metadata i32 7
4183/// ::= metadata !0
4184/// ::= metadata !{...}
4185/// ::= metadata !"string"
4186bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4187 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004188 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004189 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004190 return true;
4191
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004192 V = MetadataAsValue::get(Context, MD);
4193 return false;
4194}
4195
4196/// ParseValueAsMetadata
4197/// ::= i32 %local
4198/// ::= i32 @global
4199/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004200bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4201 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004202 Type *Ty;
4203 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004204 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004205 return true;
4206 if (Ty->isMetadataTy())
4207 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4208
4209 Value *V;
4210 if (ParseValue(Ty, V, PFS))
4211 return true;
4212
4213 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004214 return false;
4215}
4216
4217/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004218/// ::= i32 %local
4219/// ::= i32 @global
4220/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004221/// ::= !42
4222/// ::= !{...}
4223/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004224/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004225bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004226 if (Lex.getKind() == lltok::MetadataVar) {
4227 MDNode *N;
4228 if (ParseSpecializedMDNode(N))
4229 return true;
4230 MD = N;
4231 return false;
4232 }
4233
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004234 // ValueAsMetadata:
4235 // <type> <value>
4236 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004237 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004238
4239 // '!'.
4240 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4241 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004242
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004243 // MDString:
4244 // ::= '!' STRINGCONSTANT
4245 if (Lex.getKind() == lltok::StringConstant) {
4246 MDString *S;
4247 if (ParseMDString(S))
4248 return true;
4249 MD = S;
4250 return false;
4251 }
4252
Dan Gohman8939ba332010-07-14 18:26:50 +00004253 // MDNode:
4254 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004255 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004256 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004257 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004258 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004259 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004260 return false;
4261}
4262
Victor Hernandez9d75c962010-01-11 22:31:58 +00004263
4264//===----------------------------------------------------------------------===//
4265// Function Parsing.
4266//===----------------------------------------------------------------------===//
4267
Chris Lattner229907c2011-07-18 04:54:35 +00004268bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004269 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004270 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004271 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004272
Chris Lattnerac161bf2009-01-02 07:01:27 +00004273 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004274 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004275 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004276 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004277 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004278 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004279 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004280 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004281 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004282 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004283 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004284 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004285 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4286 (ID.UIntVal >> 1) & 1,
4287 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004288 return false;
4289 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004290 case ValID::t_GlobalName:
4291 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004292 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004293 case ValID::t_GlobalID:
4294 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004295 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004296 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004297 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004298 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004299 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004300 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004301 return false;
4302 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004303 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4305 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004306
Dan Gohman518cda42011-12-17 00:04:22 +00004307 // The lexer has no type info, so builds all half, float, and double FP
4308 // constants as double. Fix this here. Long double does not need this.
4309 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004310 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004311 if (Ty->isHalfTy())
4312 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4313 &Ignored);
4314 else if (Ty->isFloatTy())
4315 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4316 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004317 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004318 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004319
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004320 if (V->getType() != Ty)
4321 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004322 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004323
Chris Lattnerac161bf2009-01-02 07:01:27 +00004324 return false;
4325 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004326 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004327 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004328 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004329 return false;
4330 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004331 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004332 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004333 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004334 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004335 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004336 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004337 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004338 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004339 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004340 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004341 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004342 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004343 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004344 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004345 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004346 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004347 case ValID::t_None:
4348 if (!Ty->isTokenTy())
4349 return Error(ID.Loc, "invalid type for none constant");
4350 V = Constant::getNullValue(Ty);
4351 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004352 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004353 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004354 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004355
Chris Lattnerac161bf2009-01-02 07:01:27 +00004356 V = ID.ConstantVal;
4357 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004358 case ValID::t_ConstantStruct:
4359 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004360 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004361 if (ST->getNumElements() != ID.UIntVal)
4362 return Error(ID.Loc,
4363 "initializer with struct type has wrong # elements");
4364 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4365 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004366
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004367 // Verify that the elements are compatible with the structtype.
4368 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4369 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4370 return Error(ID.Loc, "element " + Twine(i) +
4371 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004372
David Blaikieadbda4b2015-08-03 20:08:41 +00004373 V = ConstantStruct::get(
4374 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004375 } else
4376 return Error(ID.Loc, "constant expression type mismatch");
4377 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004378 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004379 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004380}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004381
Alex Lorenzd2255952015-07-17 22:07:03 +00004382bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4383 C = nullptr;
4384 ValID ID;
4385 auto Loc = Lex.getLoc();
4386 if (ParseValID(ID, /*PFS=*/nullptr))
4387 return true;
4388 switch (ID.Kind) {
4389 case ValID::t_APSInt:
4390 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004391 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004392 case ValID::t_Constant:
4393 case ValID::t_ConstantStruct:
4394 case ValID::t_PackedConstantStruct: {
4395 Value *V;
4396 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4397 return true;
4398 assert(isa<Constant>(V) && "Expected a constant value");
4399 C = cast<Constant>(V);
4400 return false;
4401 }
4402 default:
4403 return Error(Loc, "expected a constant value");
4404 }
4405}
4406
David Majnemer8a1c45d2015-12-12 05:38:55 +00004407bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004408 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004409 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004410 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004411}
4412
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004413bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004414 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004415 return ParseType(Ty) ||
4416 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004417}
4418
Chris Lattner3ed871f2009-10-27 19:13:16 +00004419bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4420 PerFunctionState &PFS) {
4421 Value *V;
4422 Loc = Lex.getLoc();
4423 if (ParseTypeAndValue(V, PFS)) return true;
4424 if (!isa<BasicBlock>(V))
4425 return Error(Loc, "expected a basic block");
4426 BB = cast<BasicBlock>(V);
4427 return false;
4428}
4429
4430
Chris Lattnerac161bf2009-01-02 07:01:27 +00004431/// FunctionHeader
4432/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004433/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004434/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004435bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4436 // Parse the linkage.
4437 LocTy LinkageLoc = Lex.getLoc();
4438 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004439
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004440 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004441 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004442 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004443 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004444 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004445 LocTy RetTypeLoc = Lex.getLoc();
4446 if (ParseOptionalLinkage(Linkage) ||
4447 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004448 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004450 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004451 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004452 return true;
4453
4454 // Verify that the linkage is ok.
4455 switch ((GlobalValue::LinkageTypes)Linkage) {
4456 case GlobalValue::ExternalLinkage:
4457 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004458 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459 if (isDefine)
4460 return Error(LinkageLoc, "invalid linkage for function definition");
4461 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004462 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004464 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004465 case GlobalValue::LinkOnceAnyLinkage:
4466 case GlobalValue::LinkOnceODRLinkage:
4467 case GlobalValue::WeakAnyLinkage:
4468 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469 if (!isDefine)
4470 return Error(LinkageLoc, "invalid linkage for function declaration");
4471 break;
4472 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004473 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004474 return Error(LinkageLoc, "invalid function linkage type");
4475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004476
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004477 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4478 return Error(LinkageLoc,
4479 "symbol with local linkage must have default visibility");
4480
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004481 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004483
Chris Lattnerac161bf2009-01-02 07:01:27 +00004484 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004485
4486 std::string FunctionName;
4487 if (Lex.getKind() == lltok::GlobalVar) {
4488 FunctionName = Lex.getStrVal();
4489 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4490 unsigned NameID = Lex.getUIntVal();
4491
4492 if (NameID != NumberedVals.size())
4493 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004494 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004495 } else {
4496 return TokError("expected function name");
4497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004498
Chris Lattner3822f632009-01-02 08:05:26 +00004499 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004500
Chris Lattner3822f632009-01-02 08:05:26 +00004501 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004502 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004503
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004504 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004505 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004506 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004507 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004508 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004509 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004510 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004511 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004512 bool UnnamedAddr;
4513 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004514 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004515 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004516 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004517 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004518
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004519 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004520 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4521 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004522 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004523 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004524 (EatIfPresent(lltok::kw_section) &&
4525 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004526 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004527 ParseOptionalAlignment(Alignment) ||
4528 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004529 ParseStringConstant(GC)) ||
4530 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004531 ParseGlobalTypeAndValue(Prefix)) ||
4532 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004533 ParseGlobalTypeAndValue(Prologue)) ||
4534 (EatIfPresent(lltok::kw_personality) &&
4535 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004536 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537
Michael Gottesman41748d72013-06-27 00:25:01 +00004538 if (FuncAttrs.contains(Attribute::Builtin))
4539 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004540
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004542 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004543 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004544 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004546
Chris Lattnerac161bf2009-01-02 07:01:27 +00004547 // Okay, if we got here, the function is syntactically valid. Convert types
4548 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004549 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004550 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004551
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004552 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004553 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4554 AttributeSet::ReturnIndex,
4555 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004556
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004558 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004559 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4560 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004561 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4562 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 }
4564
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004565 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004566 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4567 AttributeSet::FunctionIndex,
4568 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569
Bill Wendlinge94d8432012-12-07 23:16:57 +00004570 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004571
Bill Wendling749a43d2012-12-30 13:50:49 +00004572 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004573 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4574
Chris Lattner229907c2011-07-18 04:54:35 +00004575 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004576 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004577 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578
Craig Topper2617dcc2014-04-15 06:32:26 +00004579 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004580 if (!FunctionName.empty()) {
4581 // If this was a definition of a forward reference, remove the definition
4582 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004583 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 if (FRVI != ForwardRefVals.end()) {
4585 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004586 if (!Fn)
4587 return Error(FRVI->second.second, "invalid forward reference to "
4588 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004589 if (Fn->getType() != PFT)
4590 return Error(FRVI->second.second, "invalid forward reference to "
4591 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004592
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593 ForwardRefVals.erase(FRVI);
4594 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004595 // Reject redefinitions.
4596 return Error(NameLoc, "invalid redefinition of function '" +
4597 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004598 } else if (M->getNamedValue(FunctionName)) {
4599 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004601
Dan Gohman399d6ae2009-08-29 23:37:49 +00004602 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 // If this is a definition of a forward referenced function, make sure the
4604 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004605 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004606 if (I != ForwardRefValIDs.end()) {
4607 Fn = cast<Function>(I->second.first);
4608 if (Fn->getType() != PFT)
4609 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004610 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004611 ForwardRefValIDs.erase(I);
4612 }
4613 }
4614
Craig Topper2617dcc2014-04-15 06:32:26 +00004615 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004616 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4617 else // Move the forward-reference to the correct spot in the module.
4618 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4619
4620 if (FunctionName.empty())
4621 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004622
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4624 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004625 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004626 Fn->setCallingConv(CC);
4627 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004628 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629 Fn->setAlignment(Alignment);
4630 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004631 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004632 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004633 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004634 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004635 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004636 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004637
Chris Lattnerac161bf2009-01-02 07:01:27 +00004638 // Add all of the arguments we parsed to the function.
4639 Function::arg_iterator ArgIt = Fn->arg_begin();
4640 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4641 // If the argument has a name, insert it into the argument symbol table.
4642 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004643
Chris Lattnerac161bf2009-01-02 07:01:27 +00004644 // Set the name, if it conflicted, it will be auto-renamed.
4645 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004646
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004647 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4649 ArgList[i].Name + "'");
4650 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004651
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004652 if (isDefine)
4653 return false;
4654
Robin Morisset039781e2014-08-29 21:53:01 +00004655 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004656 ValID ID;
4657 if (FunctionName.empty()) {
4658 ID.Kind = ValID::t_GlobalID;
4659 ID.UIntVal = NumberedVals.size() - 1;
4660 } else {
4661 ID.Kind = ValID::t_GlobalName;
4662 ID.StrVal = FunctionName;
4663 }
4664 auto Blocks = ForwardRefBlockAddresses.find(ID);
4665 if (Blocks != ForwardRefBlockAddresses.end())
4666 return Error(Blocks->first.Loc,
4667 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004668 return false;
4669}
4670
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004671bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4672 ValID ID;
4673 if (FunctionNumber == -1) {
4674 ID.Kind = ValID::t_GlobalName;
4675 ID.StrVal = F.getName();
4676 } else {
4677 ID.Kind = ValID::t_GlobalID;
4678 ID.UIntVal = FunctionNumber;
4679 }
4680
4681 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4682 if (Blocks == P.ForwardRefBlockAddresses.end())
4683 return false;
4684
4685 for (const auto &I : Blocks->second) {
4686 const ValID &BBID = I.first;
4687 GlobalValue *GV = I.second;
4688
4689 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4690 "Expected local id or name");
4691 BasicBlock *BB;
4692 if (BBID.Kind == ValID::t_LocalName)
4693 BB = GetBB(BBID.StrVal, BBID.Loc);
4694 else
4695 BB = GetBB(BBID.UIntVal, BBID.Loc);
4696 if (!BB)
4697 return P.Error(BBID.Loc, "referenced value is not a basic block");
4698
4699 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4700 GV->eraseFromParent();
4701 }
4702
4703 P.ForwardRefBlockAddresses.erase(Blocks);
4704 return false;
4705}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004706
4707/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004708/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004709bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004710 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004711 return TokError("expected '{' in function body");
4712 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004713
Chris Lattner3432c622009-10-28 03:39:23 +00004714 int FunctionNumber = -1;
4715 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004716
Chris Lattner3432c622009-10-28 03:39:23 +00004717 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004718
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004719 // Resolve block addresses and allow basic blocks to be forward-declared
4720 // within this function.
4721 if (PFS.resolveForwardRefBlockAddresses())
4722 return true;
4723 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4724
Chris Lattnerbbddd962010-01-09 19:20:07 +00004725 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004726 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004727 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004728
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004729 while (Lex.getKind() != lltok::rbrace &&
4730 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004732
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004733 while (Lex.getKind() != lltok::rbrace)
4734 if (ParseUseListOrder(&PFS))
4735 return true;
4736
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 // Eat the }.
4738 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004739
Chris Lattnerac161bf2009-01-02 07:01:27 +00004740 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004741 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004742}
4743
4744/// ParseBasicBlock
4745/// ::= LabelStr? Instruction*
4746bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4747 // If this basic block starts out with a name, remember it.
4748 std::string Name;
4749 LocTy NameLoc = Lex.getLoc();
4750 if (Lex.getKind() == lltok::LabelStr) {
4751 Name = Lex.getStrVal();
4752 Lex.Lex();
4753 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Chris Lattnerac161bf2009-01-02 07:01:27 +00004755 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004756 if (!BB)
4757 return Error(NameLoc,
4758 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004759
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 // Parse the instructions in this block until we get a terminator.
4763 Instruction *Inst;
4764 do {
4765 // This instruction may have three possibilities for a name: a) none
4766 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4767 LocTy NameLoc = Lex.getLoc();
4768 int NameID = -1;
4769 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004770
Chris Lattnerac161bf2009-01-02 07:01:27 +00004771 if (Lex.getKind() == lltok::LocalVarID) {
4772 NameID = Lex.getUIntVal();
4773 Lex.Lex();
4774 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4775 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004776 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004777 NameStr = Lex.getStrVal();
4778 Lex.Lex();
4779 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4780 return true;
4781 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004782
Chris Lattner77b89dc2009-12-30 05:23:43 +00004783 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004784 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004785 case InstError: return true;
4786 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004787 BB->getInstList().push_back(Inst);
4788
Chris Lattner77b89dc2009-12-30 05:23:43 +00004789 // With a normal result, we check to see if the instruction is followed by
4790 // a comma and metadata.
4791 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004792 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004793 return true;
4794 break;
4795 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004796 BB->getInstList().push_back(Inst);
4797
Chris Lattner77b89dc2009-12-30 05:23:43 +00004798 // If the instruction parser ate an extra comma at the end of it, it
4799 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004800 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004801 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004802 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004803 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004804
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805 // Set the name on the instruction.
4806 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4807 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004808
Chris Lattnerac161bf2009-01-02 07:01:27 +00004809 return false;
4810}
4811
4812//===----------------------------------------------------------------------===//
4813// Instruction Parsing.
4814//===----------------------------------------------------------------------===//
4815
4816/// ParseInstruction - Parse one of the many different instructions.
4817///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004818int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4819 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004820 lltok::Kind Token = Lex.getKind();
4821 if (Token == lltok::Eof)
4822 return TokError("found end of file when expecting more instructions");
4823 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004824 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004825 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 switch (Token) {
4828 default: return Error(Loc, "expected instruction opcode");
4829 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004830 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004831 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4832 case lltok::kw_br: return ParseBr(Inst, PFS);
4833 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004834 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004835 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004836 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004837 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4838 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004839 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4840 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004841 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 // Binary Operators.
4843 case lltok::kw_add:
4844 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004845 case lltok::kw_mul:
4846 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004847 bool NUW = EatIfPresent(lltok::kw_nuw);
4848 bool NSW = EatIfPresent(lltok::kw_nsw);
4849 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004850
Chris Lattnera676c0f2011-02-07 16:40:21 +00004851 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004852
Chris Lattnera676c0f2011-02-07 16:40:21 +00004853 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4854 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4855 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004856 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004857 case lltok::kw_fadd:
4858 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004859 case lltok::kw_fmul:
4860 case lltok::kw_fdiv:
4861 case lltok::kw_frem: {
4862 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4863 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4864 if (Res != 0)
4865 return Res;
4866 if (FMF.any())
4867 Inst->setFastMathFlags(FMF);
4868 return 0;
4869 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004870
Chris Lattner35315d02011-02-06 21:44:57 +00004871 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004872 case lltok::kw_udiv:
4873 case lltok::kw_lshr:
4874 case lltok::kw_ashr: {
4875 bool Exact = EatIfPresent(lltok::kw_exact);
4876
4877 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4878 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4879 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004880 }
4881
Chris Lattnerac161bf2009-01-02 07:01:27 +00004882 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004883 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004884 case lltok::kw_and:
4885 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004886 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004887 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4888 case lltok::kw_fcmp: {
4889 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4890 int Res = ParseCompare(Inst, PFS, KeywordVal);
4891 if (Res != 0)
4892 return Res;
4893 if (FMF.any())
4894 Inst->setFastMathFlags(FMF);
4895 return 0;
4896 }
4897
Chris Lattnerac161bf2009-01-02 07:01:27 +00004898 // Casts.
4899 case lltok::kw_trunc:
4900 case lltok::kw_zext:
4901 case lltok::kw_sext:
4902 case lltok::kw_fptrunc:
4903 case lltok::kw_fpext:
4904 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004905 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004906 case lltok::kw_uitofp:
4907 case lltok::kw_sitofp:
4908 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004909 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004910 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004911 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004912 // Other.
4913 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004914 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004915 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4916 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4917 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4918 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004919 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004920 // Call.
4921 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4922 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4923 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004924 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004926 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004927 case lltok::kw_load: return ParseLoad(Inst, PFS);
4928 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004929 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4930 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004931 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004932 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4933 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4934 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4935 }
4936}
4937
4938/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4939bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004940 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004942 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4944 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4945 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4946 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4947 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4948 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4949 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4950 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4951 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4952 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4953 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4954 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4955 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4956 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4957 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4958 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4959 }
4960 } else {
4961 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004962 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4964 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4965 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4966 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4967 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4968 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4969 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4970 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4971 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4972 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4973 }
4974 }
4975 Lex.Lex();
4976 return false;
4977}
4978
4979//===----------------------------------------------------------------------===//
4980// Terminator Instructions.
4981//===----------------------------------------------------------------------===//
4982
4983/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004984/// ::= 'ret' void (',' !dbg, !1)*
4985/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004986bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004987 PerFunctionState &PFS) {
4988 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004989 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004990 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004992 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004993
Chris Lattnerfdd87902009-10-05 05:54:46 +00004994 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004995 if (!ResType->isVoidTy())
4996 return Error(TypeLoc, "value doesn't match function result type '" +
4997 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004998
Owen Anderson55f1c092009-08-13 21:58:54 +00004999 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005000 return false;
5001 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005002
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 Value *RV;
5004 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005005
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005006 if (ResType != RV->getType())
5007 return Error(TypeLoc, "value doesn't match function result type '" +
5008 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005009
Owen Anderson55f1c092009-08-13 21:58:54 +00005010 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005011 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005012}
5013
5014
5015/// ParseBr
5016/// ::= 'br' TypeAndValue
5017/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5018bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5019 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005020 Value *Op0;
5021 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005022 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005023
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5025 Inst = BranchInst::Create(BB);
5026 return false;
5027 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005028
Owen Anderson55f1c092009-08-13 21:58:54 +00005029 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005030 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005031
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005033 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005034 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005035 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005037
Chris Lattner3ed871f2009-10-27 19:13:16 +00005038 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 return false;
5040}
5041
5042/// ParseSwitch
5043/// Instruction
5044/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5045/// JumpTable
5046/// ::= (TypeAndValue ',' TypeAndValue)*
5047bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5048 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005049 Value *Cond;
5050 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005051 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5052 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005053 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005054 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5055 return true;
5056
Duncan Sands19d0b472010-02-16 11:11:14 +00005057 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005058 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005059
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 // Parse the jump table pairs.
5061 SmallPtrSet<Value*, 32> SeenCases;
5062 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5063 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005064 Value *Constant;
5065 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005066
Chris Lattnerac161bf2009-01-02 07:01:27 +00005067 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5068 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005069 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005070 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005071
David Blaikie70573dc2014-11-19 07:49:26 +00005072 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005073 return Error(CondLoc, "duplicate case value in switch");
5074 if (!isa<ConstantInt>(Constant))
5075 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005076
Chris Lattner3ed871f2009-10-27 19:13:16 +00005077 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005078 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005079
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Chris Lattner3ed871f2009-10-27 19:13:16 +00005082 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5084 SI->addCase(Table[i].first, Table[i].second);
5085 Inst = SI;
5086 return false;
5087}
5088
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005089/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005090/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005091/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5092bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005093 LocTy AddrLoc;
5094 Value *Address;
5095 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005096 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5097 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005098 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005099
Duncan Sands19d0b472010-02-16 11:11:14 +00005100 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005101 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005102
Chris Lattner3ed871f2009-10-27 19:13:16 +00005103 // Parse the destination list.
5104 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005105
Chris Lattner3ed871f2009-10-27 19:13:16 +00005106 if (Lex.getKind() != lltok::rsquare) {
5107 BasicBlock *DestBB;
5108 if (ParseTypeAndBasicBlock(DestBB, PFS))
5109 return true;
5110 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005111
Chris Lattner3ed871f2009-10-27 19:13:16 +00005112 while (EatIfPresent(lltok::comma)) {
5113 if (ParseTypeAndBasicBlock(DestBB, PFS))
5114 return true;
5115 DestList.push_back(DestBB);
5116 }
5117 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005118
Chris Lattner3ed871f2009-10-27 19:13:16 +00005119 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5120 return true;
5121
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005122 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005123 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5124 IBI->addDestination(DestList[i]);
5125 Inst = IBI;
5126 return false;
5127}
5128
5129
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130/// ParseInvoke
5131/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5132/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5133bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5134 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005135 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005136 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005137 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005138 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005139 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 LocTy RetTypeLoc;
5141 ValID CalleeID;
5142 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005143 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144
Chris Lattner3ed871f2009-10-27 19:13:16 +00005145 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005146 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005147 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005148 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005149 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5150 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005151 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005152 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005153 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005154 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005155 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005156 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005157
Chris Lattnerac161bf2009-01-02 07:01:27 +00005158 // If RetType is a non-function pointer type, then this is the short syntax
5159 // for the call, which means that RetType is just the return type. Infer the
5160 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005161 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5162 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005163 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005164 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005165 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5166 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005167
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 if (!FunctionType::isValidReturnType(RetType))
5169 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005170
Owen Anderson4056ca92009-07-29 22:17:13 +00005171 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005173
David Blaikie41ba2b42015-07-27 23:32:19 +00005174 CalleeID.FTy = Ty;
5175
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 // Look up the callee.
5177 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005178 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5179 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005180
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005181 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005182 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005183 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005184 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5185 AttributeSet::ReturnIndex,
5186 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005187
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005189
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 // Loop through FunctionType's arguments and ensure they are specified
5191 // correctly. Also, gather any parameter attributes.
5192 FunctionType::param_iterator I = Ty->param_begin();
5193 FunctionType::param_iterator E = Ty->param_end();
5194 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005195 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005196 if (I != E) {
5197 ExpectedTy = *I++;
5198 } else if (!Ty->isVarArg()) {
5199 return Error(ArgList[i].Loc, "too many arguments specified");
5200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005201
Chris Lattnerac161bf2009-01-02 07:01:27 +00005202 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5203 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005204 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005205 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005206 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5207 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005208 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5209 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005211
Chris Lattnerac161bf2009-01-02 07:01:27 +00005212 if (I != E)
5213 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005214
David Majnemer8d22abd2015-02-23 00:01:32 +00005215 if (FnAttrs.hasAttributes()) {
5216 if (FnAttrs.hasAlignmentAttr())
5217 return Error(CallLoc, "invoke instructions may not have an alignment");
5218
Bill Wendlingf5075a42013-01-27 02:24:02 +00005219 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5220 AttributeSet::FunctionIndex,
5221 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005222 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005223
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005224 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005225 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005226
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005227 InvokeInst *II =
5228 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005229 II->setCallingConv(CC);
5230 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005231 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 Inst = II;
5233 return false;
5234}
5235
Bill Wendlingf891bf82011-07-31 06:30:59 +00005236/// ParseResume
5237/// ::= 'resume' TypeAndValue
5238bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5239 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005240 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5241 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242
Bill Wendlingf891bf82011-07-31 06:30:59 +00005243 ResumeInst *RI = ResumeInst::Create(Exn);
5244 Inst = RI;
5245 return false;
5246}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247
David Majnemer654e1302015-07-31 17:58:14 +00005248bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5249 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005250 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005251 return true;
5252
5253 while (Lex.getKind() != lltok::rsquare) {
5254 // If this isn't the first argument, we need a comma.
5255 if (!Args.empty() &&
5256 ParseToken(lltok::comma, "expected ',' in argument list"))
5257 return true;
5258
5259 // Parse the argument.
5260 LocTy ArgLoc;
5261 Type *ArgTy = nullptr;
5262 if (ParseType(ArgTy, ArgLoc))
5263 return true;
5264
5265 Value *V;
5266 if (ArgTy->isMetadataTy()) {
5267 if (ParseMetadataAsValue(V, PFS))
5268 return true;
5269 } else {
5270 if (ParseValue(ArgTy, V, PFS))
5271 return true;
5272 }
5273 Args.push_back(V);
5274 }
5275
5276 Lex.Lex(); // Lex the ']'.
5277 return false;
5278}
5279
5280/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005281/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005282bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005283 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005284
David Majnemer8a1c45d2015-12-12 05:38:55 +00005285 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5286 return true;
5287
5288 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005289 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005290
5291 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5292 return true;
5293
5294 BasicBlock *UnwindBB = nullptr;
5295 if (Lex.getKind() == lltok::kw_to) {
5296 Lex.Lex();
5297 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5298 return true;
5299 } else {
5300 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5301 return true;
5302 }
5303 }
5304
David Majnemer8a1c45d2015-12-12 05:38:55 +00005305 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005306 return false;
5307}
5308
5309/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005310/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005311bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005312 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005313
David Majnemer8a1c45d2015-12-12 05:38:55 +00005314 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5315 return true;
5316
5317 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005318 return true;
5319
David Majnemer0bc0eef2015-08-15 02:46:08 +00005320 BasicBlock *BB;
5321 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5322 ParseTypeAndBasicBlock(BB, PFS))
5323 return true;
5324
David Majnemer8a1c45d2015-12-12 05:38:55 +00005325 Inst = CatchReturnInst::Create(CatchPad, BB);
5326 return false;
5327}
5328
5329/// ParseCatchSwitch
5330/// ::= 'catchswitch' within Parent
5331bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5332 Value *ParentPad;
5333 LocTy BBLoc;
5334
5335 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5336 return true;
5337
5338 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5339 Lex.getKind() != lltok::LocalVarID)
5340 return TokError("expected scope value for catchswitch");
5341
5342 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5343 return true;
5344
5345 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5346 return true;
5347
5348 SmallVector<BasicBlock *, 32> Table;
5349 do {
5350 BasicBlock *DestBB;
5351 if (ParseTypeAndBasicBlock(DestBB, PFS))
5352 return true;
5353 Table.push_back(DestBB);
5354 } while (EatIfPresent(lltok::comma));
5355
5356 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5357 return true;
5358
5359 if (ParseToken(lltok::kw_unwind,
5360 "expected 'unwind' after catchswitch scope"))
5361 return true;
5362
5363 BasicBlock *UnwindBB = nullptr;
5364 if (EatIfPresent(lltok::kw_to)) {
5365 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5366 return true;
5367 } else {
5368 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5369 return true;
5370 }
5371
5372 auto *CatchSwitch =
5373 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5374 for (BasicBlock *DestBB : Table)
5375 CatchSwitch->addHandler(DestBB);
5376 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005377 return false;
5378}
5379
5380/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005381/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005382bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005383 Value *CatchSwitch = nullptr;
5384
5385 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5386 return true;
5387
5388 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5389 return TokError("expected scope value for catchpad");
5390
5391 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5392 return true;
5393
David Majnemer654e1302015-07-31 17:58:14 +00005394 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005395 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005396 return true;
5397
David Majnemer8a1c45d2015-12-12 05:38:55 +00005398 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005399 return false;
5400}
5401
David Majnemer654e1302015-07-31 17:58:14 +00005402/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005403/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005404bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005405 Value *ParentPad = nullptr;
5406
5407 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5408 return true;
5409
5410 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5411 Lex.getKind() != lltok::LocalVarID)
5412 return TokError("expected scope value for cleanuppad");
5413
5414 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5415 return true;
5416
David Majnemer654e1302015-07-31 17:58:14 +00005417 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005418 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005419 return true;
5420
David Majnemer8a1c45d2015-12-12 05:38:55 +00005421 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005422 return false;
5423}
5424
Chris Lattnerac161bf2009-01-02 07:01:27 +00005425//===----------------------------------------------------------------------===//
5426// Binary Operators.
5427//===----------------------------------------------------------------------===//
5428
5429/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005430/// ::= ArithmeticOps TypeAndValue ',' Value
5431///
5432/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5433/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005434bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005435 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005436 LocTy Loc; Value *LHS, *RHS;
5437 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5438 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5439 ParseValue(LHS->getType(), RHS, PFS))
5440 return true;
5441
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005442 bool Valid;
5443 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005444 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005445 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005446 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5447 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005448 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005449 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5450 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005451 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005452
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005453 if (!Valid)
5454 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005455
Chris Lattnerac161bf2009-01-02 07:01:27 +00005456 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5457 return false;
5458}
5459
5460/// ParseLogical
5461/// ::= ArithmeticOps TypeAndValue ',' Value {
5462bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5463 unsigned Opc) {
5464 LocTy Loc; Value *LHS, *RHS;
5465 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5466 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5467 ParseValue(LHS->getType(), RHS, PFS))
5468 return true;
5469
Duncan Sands9dff9be2010-02-15 16:12:20 +00005470 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005471 return Error(Loc,"instruction requires integer or integer vector operands");
5472
5473 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5474 return false;
5475}
5476
5477
5478/// ParseCompare
5479/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5480/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005481bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5482 unsigned Opc) {
5483 // Parse the integer/fp comparison predicate.
5484 LocTy Loc;
5485 unsigned Pred;
5486 Value *LHS, *RHS;
5487 if (ParseCmpPredicate(Pred, Opc) ||
5488 ParseTypeAndValue(LHS, Loc, PFS) ||
5489 ParseToken(lltok::comma, "expected ',' after compare value") ||
5490 ParseValue(LHS->getType(), RHS, PFS))
5491 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005492
Chris Lattnerac161bf2009-01-02 07:01:27 +00005493 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005494 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005495 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005496 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005497 } else {
5498 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005499 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005500 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005501 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005502 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005503 }
5504 return false;
5505}
5506
5507//===----------------------------------------------------------------------===//
5508// Other Instructions.
5509//===----------------------------------------------------------------------===//
5510
5511
5512/// ParseCast
5513/// ::= CastOpc TypeAndValue 'to' Type
5514bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5515 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005516 LocTy Loc;
5517 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005518 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005519 if (ParseTypeAndValue(Op, Loc, PFS) ||
5520 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5521 ParseType(DestTy))
5522 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005523
Chris Lattner89d856e2009-03-01 00:53:13 +00005524 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5525 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005526 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005527 getTypeString(Op->getType()) + "' to '" +
5528 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005529 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005530 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5531 return false;
5532}
5533
5534/// ParseSelect
5535/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5536bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5537 LocTy Loc;
5538 Value *Op0, *Op1, *Op2;
5539 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5540 ParseToken(lltok::comma, "expected ',' after select condition") ||
5541 ParseTypeAndValue(Op1, PFS) ||
5542 ParseToken(lltok::comma, "expected ',' after select value") ||
5543 ParseTypeAndValue(Op2, PFS))
5544 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005545
Chris Lattnerac161bf2009-01-02 07:01:27 +00005546 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5547 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005548
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 Inst = SelectInst::Create(Op0, Op1, Op2);
5550 return false;
5551}
5552
Chris Lattnerb55ab542009-01-05 08:18:44 +00005553/// ParseVA_Arg
5554/// ::= 'va_arg' TypeAndValue ',' Type
5555bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005556 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005557 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005558 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005559 if (ParseTypeAndValue(Op, PFS) ||
5560 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005561 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005563
Chris Lattnerb55ab542009-01-05 08:18:44 +00005564 if (!EltTy->isFirstClassType())
5565 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005566
5567 Inst = new VAArgInst(Op, EltTy);
5568 return false;
5569}
5570
5571/// ParseExtractElement
5572/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5573bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5574 LocTy Loc;
5575 Value *Op0, *Op1;
5576 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5577 ParseToken(lltok::comma, "expected ',' after extract value") ||
5578 ParseTypeAndValue(Op1, PFS))
5579 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005580
Chris Lattnerac161bf2009-01-02 07:01:27 +00005581 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5582 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005583
Eric Christopherc9742252009-07-25 02:28:41 +00005584 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005585 return false;
5586}
5587
5588/// ParseInsertElement
5589/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5590bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5591 LocTy Loc;
5592 Value *Op0, *Op1, *Op2;
5593 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5594 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5595 ParseTypeAndValue(Op1, PFS) ||
5596 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5597 ParseTypeAndValue(Op2, PFS))
5598 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005599
Chris Lattnerac161bf2009-01-02 07:01:27 +00005600 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005601 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005602
Chris Lattnerac161bf2009-01-02 07:01:27 +00005603 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5604 return false;
5605}
5606
5607/// ParseShuffleVector
5608/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5609bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5610 LocTy Loc;
5611 Value *Op0, *Op1, *Op2;
5612 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5613 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5614 ParseTypeAndValue(Op1, PFS) ||
5615 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5616 ParseTypeAndValue(Op2, PFS))
5617 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005618
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005620 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005621
Chris Lattnerac161bf2009-01-02 07:01:27 +00005622 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5623 return false;
5624}
5625
5626/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005627/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005628int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005629 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005630 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005631
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005632 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005633 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5634 ParseValue(Ty, Op0, PFS) ||
5635 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005636 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005637 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5638 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005639
Chris Lattnerf4f03422009-12-30 05:27:33 +00005640 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005641 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5642 while (1) {
5643 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005644
Chris Lattner3822f632009-01-02 08:05:26 +00005645 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005646 break;
5647
Chris Lattnerf4f03422009-12-30 05:27:33 +00005648 if (Lex.getKind() == lltok::MetadataVar) {
5649 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005650 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005651 }
Devang Patel8f842d32009-10-16 18:45:49 +00005652
Chris Lattner3822f632009-01-02 08:05:26 +00005653 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005654 ParseValue(Ty, Op0, PFS) ||
5655 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005656 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5658 return true;
5659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005660
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 if (!Ty->isFirstClassType())
5662 return Error(TypeLoc, "phi node must have first class type");
5663
Jay Foad52131342011-03-30 11:28:46 +00005664 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005665 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5666 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5667 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005668 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005669}
5670
Bill Wendlingfae14752011-08-12 20:24:12 +00005671/// ParseLandingPad
5672/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5673/// Clause
5674/// ::= 'catch' TypeAndValue
5675/// ::= 'filter'
5676/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5677bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005678 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005679
David Majnemer7fddecc2015-06-17 20:52:32 +00005680 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005681 return true;
5682
David Majnemer7fddecc2015-06-17 20:52:32 +00005683 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005684 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5685
5686 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5687 LandingPadInst::ClauseType CT;
5688 if (EatIfPresent(lltok::kw_catch))
5689 CT = LandingPadInst::Catch;
5690 else if (EatIfPresent(lltok::kw_filter))
5691 CT = LandingPadInst::Filter;
5692 else
5693 return TokError("expected 'catch' or 'filter' clause type");
5694
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005695 Value *V;
5696 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005697 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005698 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005699
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005700 // A 'catch' type expects a non-array constant. A filter clause expects an
5701 // array constant.
5702 if (CT == LandingPadInst::Catch) {
5703 if (isa<ArrayType>(V->getType()))
5704 Error(VLoc, "'catch' clause has an invalid type");
5705 } else {
5706 if (!isa<ArrayType>(V->getType()))
5707 Error(VLoc, "'filter' clause has an invalid type");
5708 }
5709
Owen Andersonf8f259d2015-03-09 07:13:42 +00005710 Constant *CV = dyn_cast<Constant>(V);
5711 if (!CV)
5712 return Error(VLoc, "clause argument must be a constant");
5713 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005714 }
5715
Owen Andersonf8f259d2015-03-09 07:13:42 +00005716 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005717 return false;
5718}
5719
Chris Lattnerac161bf2009-01-02 07:01:27 +00005720/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005721/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5722/// OptionalAttrs Type Value ParameterList OptionalAttrs
5723/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5724/// OptionalAttrs Type Value ParameterList OptionalAttrs
5725/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5726/// OptionalAttrs Type Value ParameterList OptionalAttrs
5727/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5728/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005729bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005730 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005731 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005732 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005733 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005734 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005735 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005736 LocTy RetTypeLoc;
5737 ValID CalleeID;
5738 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005739 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005740 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005741
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005742 if (TCK != CallInst::TCK_None &&
5743 ParseToken(lltok::kw_call,
5744 "expected 'tail call', 'musttail call', or 'notail call'"))
5745 return true;
5746
5747 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5748
5749 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005750 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005751 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005752 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5753 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005754 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5755 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005756 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005757
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005758 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5759 return Error(CallLoc, "fast-math-flags specified for call without "
5760 "floating-point scalar or vector return type");
5761
Chris Lattnerac161bf2009-01-02 07:01:27 +00005762 // If RetType is a non-function pointer type, then this is the short syntax
5763 // for the call, which means that RetType is just the return type. Infer the
5764 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005765 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5766 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005767 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005768 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005769 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5770 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005771
Chris Lattnerac161bf2009-01-02 07:01:27 +00005772 if (!FunctionType::isValidReturnType(RetType))
5773 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005774
Owen Anderson4056ca92009-07-29 22:17:13 +00005775 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005776 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005777
David Blaikie41ba2b42015-07-27 23:32:19 +00005778 CalleeID.FTy = Ty;
5779
Chris Lattnerac161bf2009-01-02 07:01:27 +00005780 // Look up the callee.
5781 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005782 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5783 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005784
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005785 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005786 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005787 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005788 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5789 AttributeSet::ReturnIndex,
5790 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005791
Chris Lattnerac161bf2009-01-02 07:01:27 +00005792 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005793
Chris Lattnerac161bf2009-01-02 07:01:27 +00005794 // Loop through FunctionType's arguments and ensure they are specified
5795 // correctly. Also, gather any parameter attributes.
5796 FunctionType::param_iterator I = Ty->param_begin();
5797 FunctionType::param_iterator E = Ty->param_end();
5798 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005799 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 if (I != E) {
5801 ExpectedTy = *I++;
5802 } else if (!Ty->isVarArg()) {
5803 return Error(ArgList[i].Loc, "too many arguments specified");
5804 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005805
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5807 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005808 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005809 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005810 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5811 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005812 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5813 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005814 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005815
Chris Lattnerac161bf2009-01-02 07:01:27 +00005816 if (I != E)
5817 return Error(CallLoc, "not enough parameters specified for call");
5818
David Majnemer8d22abd2015-02-23 00:01:32 +00005819 if (FnAttrs.hasAttributes()) {
5820 if (FnAttrs.hasAlignmentAttr())
5821 return Error(CallLoc, "call instructions may not have an alignment");
5822
Bill Wendlingf5075a42013-01-27 02:24:02 +00005823 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5824 AttributeSet::FunctionIndex,
5825 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005826 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005827
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005828 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005829 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005830
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005831 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005832 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005834 if (FMF.any())
5835 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005837 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005838 Inst = CI;
5839 return false;
5840}
5841
5842//===----------------------------------------------------------------------===//
5843// Memory Instructions.
5844//===----------------------------------------------------------------------===//
5845
5846/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005847/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5848/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005849int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005850 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005851 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005853 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005854
5855 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005856 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005857
David Majnemera3b0eb22015-02-16 08:38:03 +00005858 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859
David Majnemera3b0eb22015-02-16 08:38:03 +00005860 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5861 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005862
Chris Lattnerb2f39502009-12-30 05:44:30 +00005863 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005864 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005865 if (Lex.getKind() == lltok::kw_align) {
5866 if (ParseOptionalAlignment(Alignment)) return true;
5867 } else if (Lex.getKind() == lltok::MetadataVar) {
5868 AteExtraComma = true;
5869 } else {
5870 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5871 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5872 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005873 }
5874 }
5875
Dan Gohman2140a742010-05-28 01:14:11 +00005876 if (Size && !Size->getType()->isIntegerTy())
5877 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005878
Reid Kleckner436c42e2014-01-17 23:58:17 +00005879 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5880 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005881 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005882 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005883 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884}
5885
5886/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005887/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005888/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005889/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005890int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005891 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005892 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005893 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005894 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005895 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005896 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005897
5898 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005899 isAtomic = true;
5900 Lex.Lex();
5901 }
5902
Chris Lattnerbc639292011-11-27 06:56:53 +00005903 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005904 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005905 isVolatile = true;
5906 Lex.Lex();
5907 }
5908
David Blaikie15d9a4c2015-04-06 20:59:48 +00005909 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005910 LocTy ExplicitTypeLoc = Lex.getLoc();
5911 if (ParseType(Ty) ||
5912 ParseToken(lltok::comma, "expected comma after load's type") ||
5913 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005914 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005915 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5916 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005917
David Blaikie15d9a4c2015-04-06 20:59:48 +00005918 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005919 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005920 if (isAtomic && !Alignment)
5921 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00005922 if (Ordering == AtomicOrdering::Release ||
5923 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00005924 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005925
David Blaikiea79ac142015-02-27 21:17:42 +00005926 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5927 return Error(ExplicitTypeLoc,
5928 "explicit pointee type doesn't match operand's pointee type");
5929
David Blaikie15d9a4c2015-04-06 20:59:48 +00005930 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005931 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005932}
5933
5934/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005935
5936/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5937/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005938/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005939int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005940 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005941 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005942 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005943 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005944 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005945 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005946
5947 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005948 isAtomic = true;
5949 Lex.Lex();
5950 }
5951
Chris Lattnerbc639292011-11-27 06:56:53 +00005952 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005953 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005954 isVolatile = true;
5955 Lex.Lex();
5956 }
5957
Chris Lattnerac161bf2009-01-02 07:01:27 +00005958 if (ParseTypeAndValue(Val, Loc, PFS) ||
5959 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005960 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005961 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005962 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005963 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005964
Duncan Sands19d0b472010-02-16 11:11:14 +00005965 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005966 return Error(PtrLoc, "store operand must be a pointer");
5967 if (!Val->getType()->isFirstClassType())
5968 return Error(Loc, "store operand must be a first class value");
5969 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5970 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005971 if (isAtomic && !Alignment)
5972 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00005973 if (Ordering == AtomicOrdering::Acquire ||
5974 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00005975 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005976
Eli Friedman59b66882011-08-09 23:02:53 +00005977 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005978 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005979}
5980
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005981/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005982/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5983/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005984int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005985 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5986 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005987 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
5988 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005989 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005990 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005991 bool isWeak = false;
5992
5993 if (EatIfPresent(lltok::kw_weak))
5994 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005995
5996 if (EatIfPresent(lltok::kw_volatile))
5997 isVolatile = true;
5998
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005999 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6000 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6001 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6002 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6003 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006004 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6005 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006006 return true;
6007
JF Bastien800f87a2016-04-06 21:19:33 +00006008 if (SuccessOrdering == AtomicOrdering::Unordered ||
6009 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006010 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006011 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6012 return TokError("cmpxchg failure argument shall be no stronger than the "
6013 "success argument");
6014 if (FailureOrdering == AtomicOrdering::Release ||
6015 FailureOrdering == AtomicOrdering::AcquireRelease)
6016 return TokError(
6017 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006018 if (!Ptr->getType()->isPointerTy())
6019 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6020 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6021 return Error(CmpLoc, "compare value and pointer type do not match");
6022 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6023 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006024 if (!New->getType()->isFirstClassType())
6025 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006026 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6027 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006028 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006029 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006030 Inst = CXI;
6031 return AteExtraComma ? InstExtraComma : InstNormal;
6032}
6033
6034/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006035/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6036/// 'singlethread'? AtomicOrdering
6037int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006038 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6039 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006040 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006041 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006042 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006043 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006044
6045 if (EatIfPresent(lltok::kw_volatile))
6046 isVolatile = true;
6047
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006048 switch (Lex.getKind()) {
6049 default: return TokError("expected binary operation in atomicrmw");
6050 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6051 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6052 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6053 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6054 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6055 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6056 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6057 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6058 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6059 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6060 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6061 }
6062 Lex.Lex(); // Eat the operation.
6063
6064 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6065 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6066 ParseTypeAndValue(Val, ValLoc, PFS) ||
6067 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6068 return true;
6069
JF Bastien800f87a2016-04-06 21:19:33 +00006070 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006071 return TokError("atomicrmw cannot be unordered");
6072 if (!Ptr->getType()->isPointerTy())
6073 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6074 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6075 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6076 if (!Val->getType()->isIntegerTy())
6077 return Error(ValLoc, "atomicrmw operand must be an integer");
6078 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6079 if (Size < 8 || (Size & (Size - 1)))
6080 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6081 " integer");
6082
6083 AtomicRMWInst *RMWI =
6084 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6085 RMWI->setVolatile(isVolatile);
6086 Inst = RMWI;
6087 return AteExtraComma ? InstExtraComma : InstNormal;
6088}
6089
Eli Friedmanfee02c62011-07-25 23:16:38 +00006090/// ParseFence
6091/// ::= 'fence' 'singlethread'? AtomicOrdering
6092int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006093 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006094 SynchronizationScope Scope = CrossThread;
6095 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6096 return true;
6097
JF Bastien800f87a2016-04-06 21:19:33 +00006098 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006099 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006100 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006101 return TokError("fence cannot be monotonic");
6102
6103 Inst = new FenceInst(Context, Ordering, Scope);
6104 return InstNormal;
6105}
6106
Chris Lattnerac161bf2009-01-02 07:01:27 +00006107/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006108/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006109int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006110 Value *Ptr = nullptr;
6111 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006112 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006113
Dan Gohman16cbbe42009-07-29 15:58:36 +00006114 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006115
David Blaikie79e6c742015-02-27 19:29:02 +00006116 Type *Ty = nullptr;
6117 LocTy ExplicitTypeLoc = Lex.getLoc();
6118 if (ParseType(Ty) ||
6119 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6120 ParseTypeAndValue(Ptr, Loc, PFS))
6121 return true;
6122
Eli Benderskyd9806682013-04-22 17:03:42 +00006123 Type *BaseType = Ptr->getType();
6124 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6125 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006126 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006127
David Blaikie8d757942015-03-09 23:08:44 +00006128 if (Ty != BasePointerType->getElementType())
6129 return Error(ExplicitTypeLoc,
6130 "explicit pointee type doesn't match operand's pointee type");
6131
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006133 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006134 // GEP returns a vector of pointers if at least one of parameters is a vector.
6135 // All vector parameters should have the same vector width.
6136 unsigned GEPWidth = BaseType->isVectorTy() ?
6137 BaseType->getVectorNumElements() : 0;
6138
Chris Lattner3822f632009-01-02 08:05:26 +00006139 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006140 if (Lex.getKind() == lltok::MetadataVar) {
6141 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006142 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006143 }
Chris Lattner3822f632009-01-02 08:05:26 +00006144 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006145 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006146 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006147
Nadav Rotem3924cb02011-12-05 06:29:09 +00006148 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006149 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6150 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006151 return Error(EltLoc,
6152 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006153 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006154 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006155 Indices.push_back(Val);
6156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006157
Craig Toppere3dcce92015-08-01 22:20:21 +00006158 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006159 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006160 return Error(Loc, "base element of getelementptr must be sized");
6161
David Blaikied33bad32015-04-17 22:32:13 +00006162 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006163 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006164 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006165 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006166 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006167 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006168}
6169
6170/// ParseExtractValue
6171/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006172int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006173 Value *Val; LocTy Loc;
6174 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006175 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006176 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006177 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006178 return true;
6179
Chris Lattner392be582010-02-12 20:49:41 +00006180 if (!Val->getType()->isAggregateType())
6181 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006182
Jay Foad57aa6362011-07-13 10:26:04 +00006183 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006184 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006185 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006186 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006187}
6188
6189/// ParseInsertValue
6190/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006191int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006192 Value *Val0, *Val1; LocTy Loc0, Loc1;
6193 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006194 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006195 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6196 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6197 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006198 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006199 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006200
Chris Lattner392be582010-02-12 20:49:41 +00006201 if (!Val0->getType()->isAggregateType())
6202 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006203
David Majnemer30074532015-02-11 07:43:58 +00006204 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6205 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006206 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006207 if (IndexedType != Val1->getType())
6208 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6209 getTypeString(Val1->getType()) + "' instead of '" +
6210 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006211 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006212 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006213}
Nick Lewycky49f89192009-04-04 07:22:01 +00006214
6215//===----------------------------------------------------------------------===//
6216// Embedded metadata.
6217//===----------------------------------------------------------------------===//
6218
6219/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006220/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006221/// Element
6222/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006223bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006224 if (ParseToken(lltok::lbrace, "expected '{' here"))
6225 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006226
Dan Gohman1e0213a2010-07-13 19:33:27 +00006227 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006228 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006229 return false;
6230
Nick Lewycky49f89192009-04-04 07:22:01 +00006231 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006232 // Null is a special case since it is typeless.
6233 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006234 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006235 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006236 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006237
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006238 Metadata *MD;
6239 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006240 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006241 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006242 } while (EatIfPresent(lltok::comma));
6243
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006244 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006245}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006246
6247//===----------------------------------------------------------------------===//
6248// Use-list order directives.
6249//===----------------------------------------------------------------------===//
6250bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6251 SMLoc Loc) {
6252 if (V->use_empty())
6253 return Error(Loc, "value has no uses");
6254
6255 unsigned NumUses = 0;
6256 SmallDenseMap<const Use *, unsigned, 16> Order;
6257 for (const Use &U : V->uses()) {
6258 if (++NumUses > Indexes.size())
6259 break;
6260 Order[&U] = Indexes[NumUses - 1];
6261 }
6262 if (NumUses < 2)
6263 return Error(Loc, "value only has one use");
6264 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6265 return Error(Loc, "wrong number of indexes, expected " +
6266 Twine(std::distance(V->use_begin(), V->use_end())));
6267
6268 V->sortUseList([&](const Use &L, const Use &R) {
6269 return Order.lookup(&L) < Order.lookup(&R);
6270 });
6271 return false;
6272}
6273
6274/// ParseUseListOrderIndexes
6275/// ::= '{' uint32 (',' uint32)+ '}'
6276bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6277 SMLoc Loc = Lex.getLoc();
6278 if (ParseToken(lltok::lbrace, "expected '{' here"))
6279 return true;
6280 if (Lex.getKind() == lltok::rbrace)
6281 return Lex.Error("expected non-empty list of uselistorder indexes");
6282
6283 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6284 // indexes should be distinct numbers in the range [0, size-1], and should
6285 // not be in order.
6286 unsigned Offset = 0;
6287 unsigned Max = 0;
6288 bool IsOrdered = true;
6289 assert(Indexes.empty() && "Expected empty order vector");
6290 do {
6291 unsigned Index;
6292 if (ParseUInt32(Index))
6293 return true;
6294
6295 // Update consistency checks.
6296 Offset += Index - Indexes.size();
6297 Max = std::max(Max, Index);
6298 IsOrdered &= Index == Indexes.size();
6299
6300 Indexes.push_back(Index);
6301 } while (EatIfPresent(lltok::comma));
6302
6303 if (ParseToken(lltok::rbrace, "expected '}' here"))
6304 return true;
6305
6306 if (Indexes.size() < 2)
6307 return Error(Loc, "expected >= 2 uselistorder indexes");
6308 if (Offset != 0 || Max >= Indexes.size())
6309 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6310 if (IsOrdered)
6311 return Error(Loc, "expected uselistorder indexes to change the order");
6312
6313 return false;
6314}
6315
6316/// ParseUseListOrder
6317/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6318bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6319 SMLoc Loc = Lex.getLoc();
6320 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6321 return true;
6322
6323 Value *V;
6324 SmallVector<unsigned, 16> Indexes;
6325 if (ParseTypeAndValue(V, PFS) ||
6326 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6327 ParseUseListOrderIndexes(Indexes))
6328 return true;
6329
6330 return sortUseListOrder(V, Indexes, Loc);
6331}
6332
6333/// ParseUseListOrderBB
6334/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6335bool LLParser::ParseUseListOrderBB() {
6336 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6337 SMLoc Loc = Lex.getLoc();
6338 Lex.Lex();
6339
6340 ValID Fn, Label;
6341 SmallVector<unsigned, 16> Indexes;
6342 if (ParseValID(Fn) ||
6343 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6344 ParseValID(Label) ||
6345 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6346 ParseUseListOrderIndexes(Indexes))
6347 return true;
6348
6349 // Check the function.
6350 GlobalValue *GV;
6351 if (Fn.Kind == ValID::t_GlobalName)
6352 GV = M->getNamedValue(Fn.StrVal);
6353 else if (Fn.Kind == ValID::t_GlobalID)
6354 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6355 else
6356 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6357 if (!GV)
6358 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6359 auto *F = dyn_cast<Function>(GV);
6360 if (!F)
6361 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6362 if (F->isDeclaration())
6363 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6364
6365 // Check the basic block.
6366 if (Label.Kind == ValID::t_LocalID)
6367 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6368 if (Label.Kind != ValID::t_LocalName)
6369 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6370 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6371 if (!V)
6372 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6373 if (!isa<BasicBlock>(V))
6374 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6375
6376 return sortUseListOrder(V, Indexes, Loc);
6377}