blob: d326edfd63fd3c58c2ee4b3a06ea73dc33bbf7cc [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 Amini09b4a8d2016-03-10 01:28:54 +000049 if (Context.discardValueNames())
50 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() {
Manman Ren209b17c2013-09-28 00:22:27 +0000103 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
104 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
105
Bill Wendlingb32b0412013-02-08 06:32:06 +0000106 // Handle any function attribute group forward references.
107 for (std::map<Value*, std::vector<unsigned> >::iterator
108 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
109 I != E; ++I) {
110 Value *V = I->first;
111 std::vector<unsigned> &Vec = I->second;
112 AttrBuilder B;
113
114 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
115 VI != VE; ++VI)
116 B.merge(NumberedAttrBuilders[*VI]);
117
118 if (Function *Fn = dyn_cast<Function>(V)) {
119 AttributeSet AS = Fn->getAttributes();
120 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
121 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
122 AS.getFnAttributes());
123
124 FnAttrs.merge(B);
125
126 // If the alignment was parsed as an attribute, move to the alignment
127 // field.
128 if (FnAttrs.hasAlignmentAttr()) {
129 Fn->setAlignment(FnAttrs.getAlignment());
130 FnAttrs.removeAttribute(Attribute::Alignment);
131 }
132
133 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134 AttributeSet::get(Context,
135 AttributeSet::FunctionIndex,
136 FnAttrs));
137 Fn->setAttributes(AS);
138 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
139 AttributeSet AS = CI->getAttributes();
140 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
141 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
142 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000143 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000144 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
145 AttributeSet::get(Context,
146 AttributeSet::FunctionIndex,
147 FnAttrs));
148 CI->setAttributes(AS);
149 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
150 AttributeSet AS = II->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
152 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
153 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000155 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
156 AttributeSet::get(Context,
157 AttributeSet::FunctionIndex,
158 FnAttrs));
159 II->setAttributes(AS);
160 } else {
161 llvm_unreachable("invalid object with forward attribute group reference");
162 }
163 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000164
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000165 // If there are entries in ForwardRefBlockAddresses at this point, the
166 // function was never defined.
167 if (!ForwardRefBlockAddresses.empty())
168 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
169 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000170
David Majnemer19b51052015-02-11 07:43:56 +0000171 for (const auto &NT : NumberedTypes)
172 if (NT.second.second.isValid())
173 return Error(NT.second.second,
174 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000175
176 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
177 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
178 if (I->second.second.isValid())
179 return Error(I->second.second,
180 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000181
David Majnemerdad0a642014-06-27 18:19:56 +0000182 if (!ForwardRefComdats.empty())
183 return Error(ForwardRefComdats.begin()->second,
184 "use of undefined comdat '$" +
185 ForwardRefComdats.begin()->first + "'");
186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 if (!ForwardRefVals.empty())
188 return Error(ForwardRefVals.begin()->second.second,
189 "use of undefined value '@" + ForwardRefVals.begin()->first +
190 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000191
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 if (!ForwardRefValIDs.empty())
193 return Error(ForwardRefValIDs.begin()->second.second,
194 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000195 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000196
Devang Pateld2541152009-07-08 19:23:54 +0000197 if (!ForwardRefMDNodes.empty())
198 return Error(ForwardRefMDNodes.begin()->second.second,
199 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000200 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000201
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000203 for (auto &N : NumberedMetadata) {
204 if (N.second && !N.second->isResolved())
205 N.second->resolveCycles();
206 }
Devang Pateld2541152009-07-08 19:23:54 +0000207
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:
470/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000471/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000473/// GlobalID '=' OptionalVisibility ALIAS ...
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
Rafael Espindola464fe022014-07-30 22:51:54 +0000503 if (Lex.getKind() != lltok::kw_alias)
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);
Rafael Espindola464fe022014-07-30 22:51:54 +0000506 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000507 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000508}
509
Chris Lattnerac161bf2009-01-02 07:01:27 +0000510/// ParseNamedGlobal:
511/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000512/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
513/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000514bool LLParser::ParseNamedGlobal() {
515 assert(Lex.getKind() == lltok::GlobalVar);
516 LocTy NameLoc = Lex.getLoc();
517 std::string Name = Lex.getStrVal();
518 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000519
Chris Lattnerac161bf2009-01-02 07:01:27 +0000520 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000521 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000522 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000523 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000524 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
525 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000526 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000527 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000528 ParseOptionalThreadLocal(TLM) ||
529 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000530 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000531
Rafael Espindola464fe022014-07-30 22:51:54 +0000532 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000533 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000534 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000535
536 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000537 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000538}
539
David Majnemerdad0a642014-06-27 18:19:56 +0000540bool LLParser::parseComdat() {
541 assert(Lex.getKind() == lltok::ComdatVar);
542 std::string Name = Lex.getStrVal();
543 LocTy NameLoc = Lex.getLoc();
544 Lex.Lex();
545
546 if (ParseToken(lltok::equal, "expected '=' here"))
547 return true;
548
549 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
550 return TokError("expected comdat type");
551
552 Comdat::SelectionKind SK;
553 switch (Lex.getKind()) {
554 default:
555 return TokError("unknown selection kind");
556 case lltok::kw_any:
557 SK = Comdat::Any;
558 break;
559 case lltok::kw_exactmatch:
560 SK = Comdat::ExactMatch;
561 break;
562 case lltok::kw_largest:
563 SK = Comdat::Largest;
564 break;
565 case lltok::kw_noduplicates:
566 SK = Comdat::NoDuplicates;
567 break;
568 case lltok::kw_samesize:
569 SK = Comdat::SameSize;
570 break;
571 }
572 Lex.Lex();
573
574 // See if the comdat was forward referenced, if so, use the comdat.
575 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
576 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
577 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
578 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
579
580 Comdat *C;
581 if (I != ComdatSymTab.end())
582 C = &I->second;
583 else
584 C = M->getOrInsertComdat(Name);
585 C->setSelectionKind(SK);
586
587 return false;
588}
589
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000590// MDString:
591// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000592bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000593 std::string Str;
594 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000595 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000596 return false;
597}
598
599// MDNode:
600// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000601bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000602 // !{ ..., !42, ... }
603 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000604 if (ParseUInt32(MID))
605 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000606
Chris Lattner8eff0152010-04-01 05:14:45 +0000607 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000608 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000609 Result = NumberedMetadata[MID];
610 return false;
611 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612
Chris Lattner8eff0152010-04-01 05:14:45 +0000613 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000614 auto &FwdRef = ForwardRefMDNodes[MID];
615 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000616
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000617 Result = FwdRef.first.get();
618 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000619 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000620}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000621
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000622/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000623/// !foo = !{ !1, !2 }
624bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000625 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000626 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000627 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000628
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000629 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000630 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000631 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000632 return true;
633
Dan Gohman2637cc12010-07-21 23:38:33 +0000634 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000635 if (Lex.getKind() != lltok::rbrace)
636 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000637 if (ParseToken(lltok::exclaim, "Expected '!' here"))
638 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000639
Craig Topper2617dcc2014-04-15 06:32:26 +0000640 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000641 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000642 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000643 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000644
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000645 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000646}
647
Devang Patel39e64d42009-07-01 19:21:12 +0000648/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000649/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000650bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000651 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000652 Lex.Lex();
653 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000654
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000655 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000656 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000657 ParseToken(lltok::equal, "expected '=' here"))
658 return true;
659
660 // Detect common error, from old metadata syntax.
661 if (Lex.getKind() == lltok::Type)
662 return TokError("unexpected type in metadata definition");
663
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000664 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000665 if (Lex.getKind() == lltok::MetadataVar) {
666 if (ParseSpecializedMDNode(Init, IsDistinct))
667 return true;
668 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
669 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000670 return true;
671
Chris Lattnerfc58af22009-12-30 04:51:58 +0000672 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000673 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000674 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000675 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000676 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000677
Chris Lattnerfc58af22009-12-30 04:51:58 +0000678 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
679 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000680 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000681 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000683 }
684
Devang Patel39e64d42009-07-01 19:21:12 +0000685 return false;
686}
687
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000688static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
689 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
690 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
691}
692
Chris Lattnerac161bf2009-01-02 07:01:27 +0000693/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000694/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
695/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000696/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000697///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000698/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000699/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000700///
Eric Christopher536f0a92015-05-28 23:07:39 +0000701/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000702///
Rafael Espindola464fe022014-07-30 22:51:54 +0000703bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000704 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000705 GlobalVariable::ThreadLocalMode TLM,
706 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000707 assert(Lex.getKind() == lltok::kw_alias);
708 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709
Rafael Espindola78527052013-10-06 15:10:43 +0000710 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
711
Rafael Espindolacaa43562013-10-09 16:07:32 +0000712 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000713 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000714
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000715 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000716 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000717 "symbol with local linkage must have default visibility");
718
David Blaikie2f408302015-09-11 03:22:04 +0000719 Type *Ty;
720 LocTy ExplicitTypeLoc = Lex.getLoc();
721 if (ParseType(Ty) ||
722 ParseToken(lltok::comma, "expected comma after alias's type"))
723 return true;
724
Rafael Espindola64c1e182014-06-03 02:41:57 +0000725 Constant *Aliasee;
726 LocTy AliaseeLoc = Lex.getLoc();
727 if (Lex.getKind() != lltok::kw_bitcast &&
728 Lex.getKind() != lltok::kw_getelementptr &&
729 Lex.getKind() != lltok::kw_addrspacecast &&
730 Lex.getKind() != lltok::kw_inttoptr) {
731 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000732 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000733 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000734 // The bitcast dest type is not present, it is implied by the dest type.
735 ValID ID;
736 if (ParseValID(ID))
737 return true;
738 if (ID.Kind != ValID::t_Constant)
739 return Error(AliaseeLoc, "invalid aliasee");
740 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Rafael Espindola64c1e182014-06-03 02:41:57 +0000743 Type *AliaseeType = Aliasee->getType();
744 auto *PTy = dyn_cast<PointerType>(AliaseeType);
745 if (!PTy)
746 return Error(AliaseeLoc, "An alias must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000747 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748
David Blaikie2f408302015-09-11 03:22:04 +0000749 if (Ty != PTy->getElementType())
750 return Error(
751 ExplicitTypeLoc,
752 "explicit pointee type doesn't match operand's pointee type");
753
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000754 GlobalValue *GVal = nullptr;
755
756 // See if the alias was forward referenced, if so, prepare to replace the
757 // forward reference.
758 if (!Name.empty()) {
759 GVal = M->getNamedValue(Name);
760 if (GVal) {
761 if (!ForwardRefVals.erase(Name))
762 return Error(NameLoc, "redefinition of global '@" + Name + "'");
763 }
764 } else {
765 auto I = ForwardRefValIDs.find(NumberedVals.size());
766 if (I != ForwardRefValIDs.end()) {
767 GVal = I->second.first;
768 ForwardRefValIDs.erase(I);
769 }
770 }
771
Chris Lattnerac161bf2009-01-02 07:01:27 +0000772 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000773 std::unique_ptr<GlobalAlias> GA(
David Blaikie16a2f3e2015-09-14 18:01:59 +0000774 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
775 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000776 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000777 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000778 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000779 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Rafael Espindola54fc2982015-06-17 17:53:31 +0000781 if (Name.empty())
782 NumberedVals.push_back(GA.get());
783
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000784 if (GVal) {
785 // Verify that types agree.
786 if (GVal->getType() != GA->getType())
787 return Error(
788 ExplicitTypeLoc,
789 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000790
Chris Lattnerac161bf2009-01-02 07:01:27 +0000791 // If they agree, just RAUW the old value with the alias and remove the
792 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000793 GVal->replaceAllUsesWith(GA.get());
794 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000795 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000796
Chris Lattnerac161bf2009-01-02 07:01:27 +0000797 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000798 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000799 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000800
Rafael Espindolaaa273822014-05-09 21:49:17 +0000801 // The module owns this now
802 GA.release();
803
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 return false;
805}
806
807/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000808/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000809/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000810/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000811/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000812/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000813/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000814///
Eric Christopher536f0a92015-05-28 23:07:39 +0000815/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000816/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817///
818bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
819 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000820 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000821 GlobalVariable::ThreadLocalMode TLM,
822 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000823 if (!isValidVisibilityForLinkage(Visibility, Linkage))
824 return Error(NameLoc,
825 "symbol with local linkage must have default visibility");
826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000828 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000829 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000830 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
Craig Topper2617dcc2014-04-15 06:32:26 +0000832 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000833 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000834 ParseOptionalToken(lltok::kw_externally_initialized,
835 IsExternallyInitialized,
836 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000837 ParseGlobalType(IsConstant) ||
838 ParseType(Ty, TyLoc))
839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000840
Chris Lattnerac161bf2009-01-02 07:01:27 +0000841 // If the linkage is specified and is external, then no initializer is
842 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000843 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000844 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 Linkage != GlobalValue::ExternalLinkage)) {
846 if (ParseGlobalValue(Ty, Init))
847 return true;
848 }
849
David Majnemer49b3d9b2015-02-16 08:41:08 +0000850 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000851 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000852
David Majnemer598bd052014-12-09 05:56:09 +0000853 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854
855 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000856 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000857 GVal = M->getNamedValue(Name);
858 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000859 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000860 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000861 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000862 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000863 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000864 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000865 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 ForwardRefValIDs.erase(I);
867 }
868 }
869
David Majnemer598bd052014-12-09 05:56:09 +0000870 GlobalVariable *GV;
871 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000872 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
873 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000874 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000875 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000876 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000877 return Error(TyLoc,
878 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000879
David Majnemer598bd052014-12-09 05:56:09 +0000880 GV = cast<GlobalVariable>(GVal);
881
Chris Lattnerac161bf2009-01-02 07:01:27 +0000882 // Move the forward-reference to the correct spot in the module.
883 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
884 }
885
886 if (Name.empty())
887 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000888
Chris Lattnerac161bf2009-01-02 07:01:27 +0000889 // Set the parsed properties on the global.
890 if (Init)
891 GV->setInitializer(Init);
892 GV->setConstant(IsConstant);
893 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
894 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000895 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000896 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000897 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000898 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000899
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 // Parse attributes on the global.
901 while (Lex.getKind() == lltok::comma) {
902 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000903
Chris Lattnerac161bf2009-01-02 07:01:27 +0000904 if (Lex.getKind() == lltok::kw_section) {
905 Lex.Lex();
906 GV->setSection(Lex.getStrVal());
907 if (ParseToken(lltok::StringConstant, "expected global section string"))
908 return true;
909 } else if (Lex.getKind() == lltok::kw_align) {
910 unsigned Alignment;
911 if (ParseOptionalAlignment(Alignment)) return true;
912 GV->setAlignment(Alignment);
913 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000914 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000915 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000916 return true;
917 if (C)
918 GV->setComdat(C);
919 else
920 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 }
922 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000923
Chris Lattnerac161bf2009-01-02 07:01:27 +0000924 return false;
925}
926
Bill Wendling63b88192013-02-06 06:52:58 +0000927/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000928/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000929bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000930 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000931 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000932 Lex.Lex();
933
David Majnemerb39e22b2014-12-09 18:33:57 +0000934 if (Lex.getKind() != lltok::AttrGrpID)
935 return TokError("expected attribute group id");
936
Bill Wendling63b88192013-02-06 06:52:58 +0000937 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000938 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000939 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000940 Lex.Lex();
941
942 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000943 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000944 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000945 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000946 ParseToken(lltok::rbrace, "expected end of attribute group"))
947 return true;
948
Bill Wendlingb32b0412013-02-08 06:32:06 +0000949 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000950 return Error(AttrGrpLoc, "attribute group has no attributes");
951
952 return false;
953}
954
Bill Wendling8b0321d2013-02-08 00:52:31 +0000955/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000956/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000957bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
958 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000959 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000960 bool HaveError = false;
961
962 B.clear();
963
Bill Wendling63b88192013-02-06 06:52:58 +0000964 while (true) {
965 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000966 if (Token == lltok::kw_builtin)
967 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000968 switch (Token) {
969 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000970 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000971 return Error(Lex.getLoc(), "unterminated attribute group");
972 case lltok::rbrace:
973 // Finished.
974 return false;
975
Bill Wendlingb32b0412013-02-08 06:32:06 +0000976 case lltok::AttrGrpID: {
977 // Allow a function to reference an attribute group:
978 //
979 // define void @foo() #1 { ... }
980 if (inAttrGrp)
981 HaveError |=
982 Error(Lex.getLoc(),
983 "cannot have an attribute group reference in an attribute group");
984
985 unsigned AttrGrpNum = Lex.getUIntVal();
986 if (inAttrGrp) break;
987
988 // Save the reference to the attribute group. We'll fill it in later.
989 FwdRefAttrGrps.push_back(AttrGrpNum);
990 break;
991 }
Bill Wendling63b88192013-02-06 06:52:58 +0000992 // Target-dependent attributes:
993 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000994 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000995 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000996 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000997 }
998
999 // Target-independent attributes:
1000 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001001 // As a hack, we allow function alignment to be initially parsed as an
1002 // attribute on a function declaration/definition or added to an attribute
1003 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001004 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001005 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001006 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001007 if (ParseToken(lltok::equal, "expected '=' here") ||
1008 ParseUInt32(Alignment))
1009 return true;
1010 } else {
1011 if (ParseOptionalAlignment(Alignment))
1012 return true;
1013 }
Bill Wendling63b88192013-02-06 06:52:58 +00001014 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001015 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001016 }
1017 case lltok::kw_alignstack: {
1018 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001019 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001020 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001021 if (ParseToken(lltok::equal, "expected '=' here") ||
1022 ParseUInt32(Alignment))
1023 return true;
1024 } else {
1025 if (ParseOptionalStackAlignment(Alignment))
1026 return true;
1027 }
Bill Wendling63b88192013-02-06 06:52:58 +00001028 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001029 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001030 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001031 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1032 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1033 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1034 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1035 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001036 case lltok::kw_inaccessiblememonly:
1037 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1038 case lltok::kw_inaccessiblemem_or_argmemonly:
1039 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001040 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1041 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1042 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1043 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1044 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1045 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1046 case lltok::kw_noimplicitfloat:
1047 B.addAttribute(Attribute::NoImplicitFloat); break;
1048 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1049 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1050 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1051 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001052 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001053 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1054 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1055 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1056 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1057 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1058 case lltok::kw_returns_twice:
1059 B.addAttribute(Attribute::ReturnsTwice); break;
1060 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1061 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1062 case lltok::kw_sspstrong:
1063 B.addAttribute(Attribute::StackProtectStrong); break;
1064 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1065 case lltok::kw_sanitize_address:
1066 B.addAttribute(Attribute::SanitizeAddress); break;
1067 case lltok::kw_sanitize_thread:
1068 B.addAttribute(Attribute::SanitizeThread); break;
1069 case lltok::kw_sanitize_memory:
1070 B.addAttribute(Attribute::SanitizeMemory); break;
1071 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001072
1073 // Error handling.
1074 case lltok::kw_inreg:
1075 case lltok::kw_signext:
1076 case lltok::kw_zeroext:
1077 HaveError |=
1078 Error(Lex.getLoc(),
1079 "invalid use of attribute on a function");
1080 break;
1081 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001082 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001083 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001084 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001085 case lltok::kw_nest:
1086 case lltok::kw_noalias:
1087 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001088 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001089 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001090 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001091 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001092 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001093 HaveError |=
1094 Error(Lex.getLoc(),
1095 "invalid use of parameter-only attribute on a function");
1096 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001097 }
1098
1099 Lex.Lex();
1100 }
1101}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102
1103//===----------------------------------------------------------------------===//
1104// GlobalValue Reference/Resolution Routines.
1105//===----------------------------------------------------------------------===//
1106
Karl Schimpf77729782015-09-03 18:06:44 +00001107static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1108 const std::string &Name) {
1109 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1110 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1111 else
1112 return new GlobalVariable(*M, PTy->getElementType(), false,
1113 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1114 nullptr, GlobalVariable::NotThreadLocal,
1115 PTy->getAddressSpace());
1116}
1117
Chris Lattnerac161bf2009-01-02 07:01:27 +00001118/// GetGlobalVal - Get a value with the specified name or ID, creating a
1119/// forward reference record if needed. This can return null if the value
1120/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001121GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001122 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001123 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001124 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001125 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001126 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001128
Chris Lattnerac161bf2009-01-02 07:01:27 +00001129 // Look this name up in the normal function symbol table.
1130 GlobalValue *Val =
1131 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001132
Chris Lattnerac161bf2009-01-02 07:01:27 +00001133 // If this is a forward reference for the value, see if we already created a
1134 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001135 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001136 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001137 if (I != ForwardRefVals.end())
1138 Val = I->second.first;
1139 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001140
Chris Lattnerac161bf2009-01-02 07:01:27 +00001141 // If we have the value in the symbol table or fwd-ref table, return it.
1142 if (Val) {
1143 if (Val->getType() == Ty) return Val;
1144 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001145 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001146 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001148
Chris Lattnerac161bf2009-01-02 07:01:27 +00001149 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001150 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001151 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1152 return FwdVal;
1153}
1154
Chris Lattner229907c2011-07-18 04:54:35 +00001155GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1156 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001157 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001159 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001161
Craig Topper2617dcc2014-04-15 06:32:26 +00001162 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001163
Chris Lattnerac161bf2009-01-02 07:01:27 +00001164 // If this is a forward reference for the value, see if we already created a
1165 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001166 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001167 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001168 if (I != ForwardRefValIDs.end())
1169 Val = I->second.first;
1170 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001171
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172 // If we have the value in the symbol table or fwd-ref table, return it.
1173 if (Val) {
1174 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001175 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001176 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001177 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001178 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001179
Chris Lattnerac161bf2009-01-02 07:01:27 +00001180 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001181 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001182 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1183 return FwdVal;
1184}
1185
1186
1187//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001188// Comdat Reference/Resolution Routines.
1189//===----------------------------------------------------------------------===//
1190
1191Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1192 // Look this name up in the comdat symbol table.
1193 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1194 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1195 if (I != ComdatSymTab.end())
1196 return &I->second;
1197
1198 // Otherwise, create a new forward reference for this value and remember it.
1199 Comdat *C = M->getOrInsertComdat(Name);
1200 ForwardRefComdats[Name] = Loc;
1201 return C;
1202}
1203
1204
1205//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206// Helper Routines.
1207//===----------------------------------------------------------------------===//
1208
1209/// ParseToken - If the current token has the specified kind, eat it and return
1210/// success. Otherwise, emit the specified error and return failure.
1211bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1212 if (Lex.getKind() != T)
1213 return TokError(ErrMsg);
1214 Lex.Lex();
1215 return false;
1216}
1217
Chris Lattner3822f632009-01-02 08:05:26 +00001218/// ParseStringConstant
1219/// ::= StringConstant
1220bool LLParser::ParseStringConstant(std::string &Result) {
1221 if (Lex.getKind() != lltok::StringConstant)
1222 return TokError("expected string constant");
1223 Result = Lex.getStrVal();
1224 Lex.Lex();
1225 return false;
1226}
1227
1228/// ParseUInt32
1229/// ::= uint32
1230bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1232 return TokError("expected integer");
1233 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1234 if (Val64 != unsigned(Val64))
1235 return TokError("expected 32-bit integer (too large)");
1236 Val = Val64;
1237 Lex.Lex();
1238 return false;
1239}
1240
Hal Finkelb0407ba2014-07-18 15:51:28 +00001241/// ParseUInt64
1242/// ::= uint64
1243bool LLParser::ParseUInt64(uint64_t &Val) {
1244 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1245 return TokError("expected integer");
1246 Val = Lex.getAPSIntVal().getLimitedValue();
1247 Lex.Lex();
1248 return false;
1249}
1250
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001251/// ParseTLSModel
1252/// := 'localdynamic'
1253/// := 'initialexec'
1254/// := 'localexec'
1255bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1256 switch (Lex.getKind()) {
1257 default:
1258 return TokError("expected localdynamic, initialexec or localexec");
1259 case lltok::kw_localdynamic:
1260 TLM = GlobalVariable::LocalDynamicTLSModel;
1261 break;
1262 case lltok::kw_initialexec:
1263 TLM = GlobalVariable::InitialExecTLSModel;
1264 break;
1265 case lltok::kw_localexec:
1266 TLM = GlobalVariable::LocalExecTLSModel;
1267 break;
1268 }
1269
1270 Lex.Lex();
1271 return false;
1272}
1273
1274/// ParseOptionalThreadLocal
1275/// := /*empty*/
1276/// := 'thread_local'
1277/// := 'thread_local' '(' tlsmodel ')'
1278bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1279 TLM = GlobalVariable::NotThreadLocal;
1280 if (!EatIfPresent(lltok::kw_thread_local))
1281 return false;
1282
1283 TLM = GlobalVariable::GeneralDynamicTLSModel;
1284 if (Lex.getKind() == lltok::lparen) {
1285 Lex.Lex();
1286 return ParseTLSModel(TLM) ||
1287 ParseToken(lltok::rparen, "expected ')' after thread local model");
1288 }
1289 return false;
1290}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001291
1292/// ParseOptionalAddrSpace
1293/// := /*empty*/
1294/// := 'addrspace' '(' uint32 ')'
1295bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1296 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001297 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001298 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001299 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001300 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001301 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001302}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001303
Artur Pilipenko17376c42015-08-03 14:31:49 +00001304/// ParseStringAttribute
1305/// := StringConstant
1306/// := StringConstant '=' StringConstant
1307bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1308 std::string Attr = Lex.getStrVal();
1309 Lex.Lex();
1310 std::string Val;
1311 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1312 return true;
1313 B.addAttribute(Attr, Val);
1314 return false;
1315}
1316
Bill Wendling34c2eb22012-12-04 23:40:58 +00001317/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1318bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1319 bool HaveError = false;
1320
1321 B.clear();
1322
1323 while (1) {
1324 lltok::Kind Token = Lex.getKind();
1325 switch (Token) {
1326 default: // End of attributes.
1327 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001328 case lltok::StringConstant: {
1329 if (ParseStringAttribute(B))
1330 return true;
1331 continue;
1332 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001333 case lltok::kw_align: {
1334 unsigned Alignment;
1335 if (ParseOptionalAlignment(Alignment))
1336 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001337 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001338 continue;
1339 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001340 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001341 case lltok::kw_dereferenceable: {
1342 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001343 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001344 return true;
1345 B.addDereferenceableAttr(Bytes);
1346 continue;
1347 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001348 case lltok::kw_dereferenceable_or_null: {
1349 uint64_t Bytes;
1350 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1351 return true;
1352 B.addDereferenceableOrNullAttr(Bytes);
1353 continue;
1354 }
Reid Klecknera534a382013-12-19 02:14:12 +00001355 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001356 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1357 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1358 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1359 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001360 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001361 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1362 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001363 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001364 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1365 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001366 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001367 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001368 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001369
Stephen Lin7577ed52013-04-20 13:16:13 +00001370 case lltok::kw_alignstack:
1371 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001372 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001373 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001374 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001375 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001376 case lltok::kw_minsize:
1377 case lltok::kw_naked:
1378 case lltok::kw_nobuiltin:
1379 case lltok::kw_noduplicate:
1380 case lltok::kw_noimplicitfloat:
1381 case lltok::kw_noinline:
1382 case lltok::kw_nonlazybind:
1383 case lltok::kw_noredzone:
1384 case lltok::kw_noreturn:
1385 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001386 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001387 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001388 case lltok::kw_returns_twice:
1389 case lltok::kw_sanitize_address:
1390 case lltok::kw_sanitize_memory:
1391 case lltok::kw_sanitize_thread:
1392 case lltok::kw_ssp:
1393 case lltok::kw_sspreq:
1394 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001395 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001396 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001397 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1398 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001399 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001400
Bill Wendling34c2eb22012-12-04 23:40:58 +00001401 Lex.Lex();
1402 }
1403}
1404
1405/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1406bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1407 bool HaveError = false;
1408
1409 B.clear();
1410
1411 while (1) {
1412 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001413 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001414 default: // End of attributes.
1415 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001416 case lltok::StringConstant: {
1417 if (ParseStringAttribute(B))
1418 return true;
1419 continue;
1420 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001421 case lltok::kw_dereferenceable: {
1422 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001423 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001424 return true;
1425 B.addDereferenceableAttr(Bytes);
1426 continue;
1427 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001428 case lltok::kw_dereferenceable_or_null: {
1429 uint64_t Bytes;
1430 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1431 return true;
1432 B.addDereferenceableOrNullAttr(Bytes);
1433 continue;
1434 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001435 case lltok::kw_align: {
1436 unsigned Alignment;
1437 if (ParseOptionalAlignment(Alignment))
1438 return true;
1439 B.addAlignmentAttr(Alignment);
1440 continue;
1441 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001442 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1443 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001444 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001445 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1446 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001447
Bill Wendling34c2eb22012-12-04 23:40:58 +00001448 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001449 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001450 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001451 case lltok::kw_nest:
1452 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001453 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001454 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001455 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001456 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001457 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001458 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001459
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001460 case lltok::kw_alignstack:
1461 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001462 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001463 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001464 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001465 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001466 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001467 case lltok::kw_minsize:
1468 case lltok::kw_naked:
1469 case lltok::kw_nobuiltin:
1470 case lltok::kw_noduplicate:
1471 case lltok::kw_noimplicitfloat:
1472 case lltok::kw_noinline:
1473 case lltok::kw_nonlazybind:
1474 case lltok::kw_noredzone:
1475 case lltok::kw_noreturn:
1476 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001477 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001478 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001479 case lltok::kw_returns_twice:
1480 case lltok::kw_sanitize_address:
1481 case lltok::kw_sanitize_memory:
1482 case lltok::kw_sanitize_thread:
1483 case lltok::kw_ssp:
1484 case lltok::kw_sspreq:
1485 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001486 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001487 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001488 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001489 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001490
1491 case lltok::kw_readnone:
1492 case lltok::kw_readonly:
1493 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001494 }
1495
Chris Lattnerac161bf2009-01-02 07:01:27 +00001496 Lex.Lex();
1497 }
1498}
1499
1500/// ParseOptionalLinkage
1501/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001502/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001503/// ::= 'internal'
1504/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001505/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001506/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001507/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001508/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001509/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001510/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001511/// ::= 'extern_weak'
1512/// ::= 'external'
1513bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1514 HasLinkage = false;
1515 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001516 default: Res=GlobalValue::ExternalLinkage; return false;
1517 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001518 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1519 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1520 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1521 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1522 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001523 case lltok::kw_available_externally:
1524 Res = GlobalValue::AvailableExternallyLinkage;
1525 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001526 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001527 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001528 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1529 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530 }
1531 Lex.Lex();
1532 HasLinkage = true;
1533 return false;
1534}
1535
1536/// ParseOptionalVisibility
1537/// ::= /*empty*/
1538/// ::= 'default'
1539/// ::= 'hidden'
1540/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001541///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001542bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1543 switch (Lex.getKind()) {
1544 default: Res = GlobalValue::DefaultVisibility; return false;
1545 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1546 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1547 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1548 }
1549 Lex.Lex();
1550 return false;
1551}
1552
Nico Rieck7157bb72014-01-14 15:22:47 +00001553/// ParseOptionalDLLStorageClass
1554/// ::= /*empty*/
1555/// ::= 'dllimport'
1556/// ::= 'dllexport'
1557///
1558bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1559 switch (Lex.getKind()) {
1560 default: Res = GlobalValue::DefaultStorageClass; return false;
1561 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1562 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1563 }
1564 Lex.Lex();
1565 return false;
1566}
1567
Chris Lattnerac161bf2009-01-02 07:01:27 +00001568/// ParseOptionalCallingConv
1569/// ::= /*empty*/
1570/// ::= 'ccc'
1571/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001572/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573/// ::= 'coldcc'
1574/// ::= 'x86_stdcallcc'
1575/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001576/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001577/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001578/// ::= 'arm_apcscc'
1579/// ::= 'arm_aapcscc'
1580/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001581/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001582/// ::= 'avr_intrcc'
1583/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001584/// ::= 'ptx_kernel'
1585/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001586/// ::= 'spir_func'
1587/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001588/// ::= 'x86_64_sysvcc'
1589/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001590/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001591/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001592/// ::= 'preserve_mostcc'
1593/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001594/// ::= 'ghccc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001595/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001596/// ::= 'hhvmcc'
1597/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001598/// ::= 'cxx_fast_tlscc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001599/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001600///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001601bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001602 switch (Lex.getKind()) {
1603 default: CC = CallingConv::C; return false;
1604 case lltok::kw_ccc: CC = CallingConv::C; break;
1605 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1606 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1607 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1608 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001609 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001610 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001611 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1612 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1613 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001614 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001615 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1616 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001617 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1618 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001619 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1620 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001621 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001622 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1623 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001624 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001625 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001626 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1627 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001628 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001629 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001630 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1631 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001632 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001633 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001634 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001635 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001636 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001637 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001638
Chris Lattnerac161bf2009-01-02 07:01:27 +00001639 Lex.Lex();
1640 return false;
1641}
1642
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001643/// ParseMetadataAttachment
1644/// ::= !dbg !42
1645bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1646 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1647
1648 std::string Name = Lex.getStrVal();
1649 Kind = M->getMDKindID(Name);
1650 Lex.Lex();
1651
1652 return ParseMDNode(MD);
1653}
1654
Chris Lattner5c427632009-12-30 05:31:19 +00001655/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001656/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001657bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001658 do {
1659 if (Lex.getKind() != lltok::MetadataVar)
1660 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001661
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001662 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001663 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001664 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001665 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001666
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001667 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001668 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001669 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001670
Chris Lattner596760d2009-12-29 21:25:40 +00001671 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001672 } while (EatIfPresent(lltok::comma));
1673 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001674}
1675
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001676/// ParseOptionalFunctionMetadata
1677/// ::= (!dbg !57)*
1678bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1679 while (Lex.getKind() == lltok::MetadataVar) {
1680 unsigned MDK;
1681 MDNode *N;
1682 if (ParseMetadataAttachment(MDK, N))
1683 return true;
1684
1685 F.setMetadata(MDK, N);
1686 }
1687 return false;
1688}
1689
Chris Lattnerac161bf2009-01-02 07:01:27 +00001690/// ParseOptionalAlignment
1691/// ::= /* empty */
1692/// ::= 'align' 4
1693bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1694 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001695 if (!EatIfPresent(lltok::kw_align))
1696 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001697 LocTy AlignLoc = Lex.getLoc();
1698 if (ParseUInt32(Alignment)) return true;
1699 if (!isPowerOf2_32(Alignment))
1700 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001701 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001702 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001703 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704}
1705
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001706/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001707/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001708/// ::= AttrKind '(' 4 ')'
1709///
1710/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1711bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1712 uint64_t &Bytes) {
1713 assert((AttrKind == lltok::kw_dereferenceable ||
1714 AttrKind == lltok::kw_dereferenceable_or_null) &&
1715 "contract!");
1716
Hal Finkelb0407ba2014-07-18 15:51:28 +00001717 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001718 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001719 return false;
1720 LocTy ParenLoc = Lex.getLoc();
1721 if (!EatIfPresent(lltok::lparen))
1722 return Error(ParenLoc, "expected '('");
1723 LocTy DerefLoc = Lex.getLoc();
1724 if (ParseUInt64(Bytes)) return true;
1725 ParenLoc = Lex.getLoc();
1726 if (!EatIfPresent(lltok::rparen))
1727 return Error(ParenLoc, "expected ')'");
1728 if (!Bytes)
1729 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1730 return false;
1731}
1732
Chris Lattnerb2f39502009-12-30 05:44:30 +00001733/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001734/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001735/// ::= ',' align 4
1736///
1737/// This returns with AteExtraComma set to true if it ate an excess comma at the
1738/// end.
1739bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1740 bool &AteExtraComma) {
1741 AteExtraComma = false;
1742 while (EatIfPresent(lltok::comma)) {
1743 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001744 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001745 AteExtraComma = true;
1746 return false;
1747 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001748
Chris Lattner95b0ff42010-04-23 00:50:50 +00001749 if (Lex.getKind() != lltok::kw_align)
1750 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001751
Chris Lattner95b0ff42010-04-23 00:50:50 +00001752 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001753 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001754
Devang Patelea8a4b92009-09-17 23:04:48 +00001755 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756}
1757
Eli Friedmanfee02c62011-07-25 23:16:38 +00001758/// ParseScopeAndOrdering
1759/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1760/// else: ::=
1761///
1762/// This sets Scope and Ordering to the parsed values.
1763bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1764 AtomicOrdering &Ordering) {
1765 if (!isAtomic)
1766 return false;
1767
1768 Scope = CrossThread;
1769 if (EatIfPresent(lltok::kw_singlethread))
1770 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001771
1772 return ParseOrdering(Ordering);
1773}
1774
1775/// ParseOrdering
1776/// ::= AtomicOrdering
1777///
1778/// This sets Ordering to the parsed value.
1779bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001780 switch (Lex.getKind()) {
1781 default: return TokError("Expected ordering on atomic instruction");
1782 case lltok::kw_unordered: Ordering = Unordered; break;
1783 case lltok::kw_monotonic: Ordering = Monotonic; break;
1784 case lltok::kw_acquire: Ordering = Acquire; break;
1785 case lltok::kw_release: Ordering = Release; break;
1786 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1787 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1788 }
1789 Lex.Lex();
1790 return false;
1791}
1792
Charles Davisbe5557e2010-02-12 00:31:15 +00001793/// ParseOptionalStackAlignment
1794/// ::= /* empty */
1795/// ::= 'alignstack' '(' 4 ')'
1796bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1797 Alignment = 0;
1798 if (!EatIfPresent(lltok::kw_alignstack))
1799 return false;
1800 LocTy ParenLoc = Lex.getLoc();
1801 if (!EatIfPresent(lltok::lparen))
1802 return Error(ParenLoc, "expected '('");
1803 LocTy AlignLoc = Lex.getLoc();
1804 if (ParseUInt32(Alignment)) return true;
1805 ParenLoc = Lex.getLoc();
1806 if (!EatIfPresent(lltok::rparen))
1807 return Error(ParenLoc, "expected ')'");
1808 if (!isPowerOf2_32(Alignment))
1809 return Error(AlignLoc, "stack alignment is not a power of two");
1810 return false;
1811}
Devang Patelea8a4b92009-09-17 23:04:48 +00001812
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001813/// ParseIndexList - This parses the index list for an insert/extractvalue
1814/// instruction. This sets AteExtraComma in the case where we eat an extra
1815/// comma at the end of the line and find that it is followed by metadata.
1816/// Clients that don't allow metadata can call the version of this function that
1817/// only takes one argument.
1818///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001819/// ParseIndexList
1820/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001821///
1822bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1823 bool &AteExtraComma) {
1824 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001825
Chris Lattnerac161bf2009-01-02 07:01:27 +00001826 if (Lex.getKind() != lltok::comma)
1827 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001828
Chris Lattner3822f632009-01-02 08:05:26 +00001829 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001830 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001831 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001832 AteExtraComma = true;
1833 return false;
1834 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001835 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001836 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001837 Indices.push_back(Idx);
1838 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001839
Chris Lattnerac161bf2009-01-02 07:01:27 +00001840 return false;
1841}
1842
1843//===----------------------------------------------------------------------===//
1844// Type Parsing.
1845//===----------------------------------------------------------------------===//
1846
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001847/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001848bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001849 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001850 switch (Lex.getKind()) {
1851 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001852 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001854 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001855 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001856 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001857 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001858 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001859 // Type ::= StructType
1860 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001861 return true;
1862 break;
1863 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001864 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001865 Lex.Lex(); // eat the lsquare.
1866 if (ParseArrayVectorType(Result, false))
1867 return true;
1868 break;
1869 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001870 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001871 Lex.Lex();
1872 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001873 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001874 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876 } else if (ParseArrayVectorType(Result, true))
1877 return true;
1878 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001879 case lltok::LocalVar: {
1880 // Type ::= %foo
1881 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001882
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001883 // If the type hasn't been defined yet, create a forward definition and
1884 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001885 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001886 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001887 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001888 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001889 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001890 Lex.Lex();
1891 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001893
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001894 case lltok::LocalVarID: {
1895 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001896 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001897
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001898 // If the type hasn't been defined yet, create a forward definition and
1899 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001900 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001901 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001902 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001903 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001904 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001905 Lex.Lex();
1906 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907 }
1908 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001909
1910 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 while (1) {
1912 switch (Lex.getKind()) {
1913 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001914 default:
1915 if (!AllowVoid && Result->isVoidTy())
1916 return Error(TypeLoc, "void type only allowed for function results");
1917 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001919 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001921 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001923 if (Result->isVoidTy())
1924 return TokError("pointers to void are invalid - use i8* instead");
1925 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001926 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001927 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 Lex.Lex();
1929 break;
1930
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001934 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001935 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001936 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001937 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001938 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001939 unsigned AddrSpace;
1940 if (ParseOptionalAddrSpace(AddrSpace) ||
1941 ParseToken(lltok::star, "expected '*' in address space"))
1942 return true;
1943
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001944 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945 break;
1946 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001947
Chris Lattnerac161bf2009-01-02 07:01:27 +00001948 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1949 case lltok::lparen:
1950 if (ParseFunctionType(Result))
1951 return true;
1952 break;
1953 }
1954 }
1955}
1956
1957/// ParseParameterList
1958/// ::= '(' ')'
1959/// ::= '(' Arg (',' Arg)* ')'
1960/// Arg
1961/// ::= Type OptionalAttributes Value OptionalAttributes
1962bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001963 PerFunctionState &PFS, bool IsMustTailCall,
1964 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 if (ParseToken(lltok::lparen, "expected '(' in call"))
1966 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001967
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001968 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001969 while (Lex.getKind() != lltok::rparen) {
1970 // If this isn't the first argument, we need a comma.
1971 if (!ArgList.empty() &&
1972 ParseToken(lltok::comma, "expected ',' in argument list"))
1973 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001974
Reid Kleckner83498642014-08-26 00:33:28 +00001975 // Parse an ellipsis if this is a musttail call in a variadic function.
1976 if (Lex.getKind() == lltok::dotdotdot) {
1977 const char *Msg = "unexpected ellipsis in argument list for ";
1978 if (!IsMustTailCall)
1979 return TokError(Twine(Msg) + "non-musttail call");
1980 if (!InVarArgsFunc)
1981 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1982 Lex.Lex(); // Lex the '...', it is purely for readability.
1983 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1984 }
1985
Chris Lattnerac161bf2009-01-02 07:01:27 +00001986 // Parse the argument.
1987 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001988 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001989 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001991 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001992 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001993
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001994 if (ArgTy->isMetadataTy()) {
1995 if (ParseMetadataAsValue(V, PFS))
1996 return true;
1997 } else {
1998 // Otherwise, handle normal operands.
1999 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2000 return true;
2001 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002002 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2003 AttrIndex++,
2004 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 }
2006
Reid Kleckner83498642014-08-26 00:33:28 +00002007 if (IsMustTailCall && InVarArgsFunc)
2008 return TokError("expected '...' at end of argument list for musttail call "
2009 "in varargs function");
2010
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 Lex.Lex(); // Lex the ')'.
2012 return false;
2013}
2014
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002015/// ParseOptionalOperandBundles
2016/// ::= /*empty*/
2017/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2018///
2019/// OperandBundle
2020/// ::= bundle-tag '(' ')'
2021/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2022///
2023/// bundle-tag ::= String Constant
2024bool LLParser::ParseOptionalOperandBundles(
2025 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2026 LocTy BeginLoc = Lex.getLoc();
2027 if (!EatIfPresent(lltok::lsquare))
2028 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002030 while (Lex.getKind() != lltok::rsquare) {
2031 // If this isn't the first operand bundle, we need a comma.
2032 if (!BundleList.empty() &&
2033 ParseToken(lltok::comma, "expected ',' in input list"))
2034 return true;
2035
2036 std::string Tag;
2037 if (ParseStringConstant(Tag))
2038 return true;
2039
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002040 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2041 return true;
2042
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002043 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002044 while (Lex.getKind() != lltok::rparen) {
2045 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002046 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002047 ParseToken(lltok::comma, "expected ',' in input list"))
2048 return true;
2049
2050 Type *Ty = nullptr;
2051 Value *Input = nullptr;
2052 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2053 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002054 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002055 }
2056
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002057 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2058
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002059 Lex.Lex(); // Lex the ')'.
2060 }
2061
2062 if (BundleList.empty())
2063 return Error(BeginLoc, "operand bundle set must not be empty");
2064
2065 Lex.Lex(); // Lex the ']'.
2066 return false;
2067}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068
Chris Lattner2ed06b42009-01-05 18:34:07 +00002069/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071/// ::= '(' ArgTypeListI ')'
2072/// ArgTypeListI
2073/// ::= /*empty*/
2074/// ::= '...'
2075/// ::= ArgTypeList ',' '...'
2076/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002077///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2079 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 isVarArg = false;
2081 assert(Lex.getKind() == lltok::lparen);
2082 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002083
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084 if (Lex.getKind() == lltok::rparen) {
2085 // empty
2086 } else if (Lex.getKind() == lltok::dotdotdot) {
2087 isVarArg = true;
2088 Lex.Lex();
2089 } else {
2090 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002091 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002092 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002095 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002096 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002097
Chris Lattnerfdd87902009-10-05 05:54:46 +00002098 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002099 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Chris Lattnerdef19492011-06-17 06:36:20 +00002101 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 Name = Lex.getStrVal();
2103 Lex.Lex();
2104 }
Chris Lattner3822f632009-01-02 08:05:26 +00002105
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002106 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002107 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002108
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002109 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002110 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2111 AttrIndex++, Attrs),
2112 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
Chris Lattner3822f632009-01-02 08:05:26 +00002114 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002116 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 break;
2119 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 // Otherwise must be an argument type.
2122 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002123 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002124
Chris Lattnerfdd87902009-10-05 05:54:46 +00002125 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002126 return Error(TypeLoc, "argument can not have void type");
2127
Chris Lattnerdef19492011-06-17 06:36:20 +00002128 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 Name = Lex.getStrVal();
2130 Lex.Lex();
2131 } else {
2132 Name = "";
2133 }
Chris Lattner3822f632009-01-02 08:05:26 +00002134
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002135 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002136 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002137
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002138 ArgList.emplace_back(
2139 TypeLoc, ArgTy,
2140 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2141 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142 }
2143 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002144
Chris Lattner3822f632009-01-02 08:05:26 +00002145 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002147
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148/// ParseFunctionType
2149/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002150bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 assert(Lex.getKind() == lltok::lparen);
2152
Chris Lattnerce473c72009-01-05 08:04:33 +00002153 if (!FunctionType::isValidReturnType(Result))
2154 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002155
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002156 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002158 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002160
Chris Lattnerac161bf2009-01-02 07:01:27 +00002161 // Reject names on the arguments lists.
2162 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2163 if (!ArgList[i].Name.empty())
2164 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002165 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002166 return Error(ArgList[i].Loc,
2167 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002169
Jay Foadb804a2b2011-07-12 14:06:48 +00002170 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002172 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002174 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 return false;
2176}
2177
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002178/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2179/// other structs.
2180bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2181 SmallVector<Type*, 8> Elts;
2182 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002183
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002184 Result = StructType::get(Context, Elts, Packed);
2185 return false;
2186}
2187
2188/// ParseStructDefinition - Parse a struct in a 'type' definition.
2189bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2190 std::pair<Type*, LocTy> &Entry,
2191 Type *&ResultTy) {
2192 // If the type was already defined, diagnose the redefinition.
2193 if (Entry.first && !Entry.second.isValid())
2194 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002195
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002196 // If we have opaque, just return without filling in the definition for the
2197 // struct. This counts as a definition as far as the .ll file goes.
2198 if (EatIfPresent(lltok::kw_opaque)) {
2199 // This type is being defined, so clear the location to indicate this.
2200 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002201
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002202 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002203 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002204 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002205 ResultTy = Entry.first;
2206 return false;
2207 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002208
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002209 // If the type starts with '<', then it is either a packed struct or a vector.
2210 bool isPacked = EatIfPresent(lltok::less);
2211
2212 // If we don't have a struct, then we have a random type alias, which we
2213 // accept for compatibility with old files. These types are not allowed to be
2214 // forward referenced and not allowed to be recursive.
2215 if (Lex.getKind() != lltok::lbrace) {
2216 if (Entry.first)
2217 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002218
Craig Topper2617dcc2014-04-15 06:32:26 +00002219 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002220 if (isPacked)
2221 return ParseArrayVectorType(ResultTy, true);
2222 return ParseType(ResultTy);
2223 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002224
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002225 // This type is being defined, so clear the location to indicate this.
2226 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002228 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002229 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002230 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002231
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002232 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002233
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002234 SmallVector<Type*, 8> Body;
2235 if (ParseStructBody(Body) ||
2236 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2237 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002238
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002239 STy->setBody(Body, isPacked);
2240 ResultTy = STy;
2241 return false;
2242}
2243
2244
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002246/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002248/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002250/// ::= '<' '{' Type (',' Type)* '}' '>'
2251bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002252 assert(Lex.getKind() == lltok::lbrace);
2253 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002255 // Handle the empty struct.
2256 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258
Chris Lattnerf880ca22009-03-09 04:49:14 +00002259 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002260 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002261 if (ParseType(Ty)) return true;
2262 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002263
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002265 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266
Chris Lattner3822f632009-01-02 08:05:26 +00002267 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002268 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002269 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002271 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002272 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002273
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002274 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002276
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002277 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002278}
2279
2280/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2281/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002282/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283/// ::= '[' APSINTVAL 'x' Types ']'
2284/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002285bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2287 Lex.getAPSIntVal().getBitWidth() > 64)
2288 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002289
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 LocTy SizeLoc = Lex.getLoc();
2291 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002292 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Chris Lattner3822f632009-01-02 08:05:26 +00002294 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2295 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296
2297 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002298 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002299 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002300
Chris Lattner3822f632009-01-02 08:05:26 +00002301 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2302 "expected end of sequential type"))
2303 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002306 if (Size == 0)
2307 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 if ((unsigned)Size != Size)
2309 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002310 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002311 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002312 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002314 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002316 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 }
2318 return false;
2319}
2320
2321//===----------------------------------------------------------------------===//
2322// Function Semantic Analysis.
2323//===----------------------------------------------------------------------===//
2324
Chris Lattner3432c622009-10-28 03:39:23 +00002325LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2326 int functionNumber)
2327 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328
2329 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002330 for (Argument &A : F.args())
2331 if (!A.hasName())
2332 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333}
2334
2335LLParser::PerFunctionState::~PerFunctionState() {
2336 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002337
David Blaikie9ebdc692015-09-21 21:07:50 +00002338 for (const auto &P : ForwardRefVals) {
2339 if (isa<BasicBlock>(P.second.first))
2340 continue;
2341 P.second.first->replaceAllUsesWith(
2342 UndefValue::get(P.second.first->getType()));
2343 delete P.second.first;
2344 }
2345
2346 for (const auto &P : ForwardRefValIDs) {
2347 if (isa<BasicBlock>(P.second.first))
2348 continue;
2349 P.second.first->replaceAllUsesWith(
2350 UndefValue::get(P.second.first->getType()));
2351 delete P.second.first;
2352 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353}
2354
Chris Lattner3432c622009-10-28 03:39:23 +00002355bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 if (!ForwardRefVals.empty())
2357 return P.Error(ForwardRefVals.begin()->second.second,
2358 "use of undefined value '%" + ForwardRefVals.begin()->first +
2359 "'");
2360 if (!ForwardRefValIDs.empty())
2361 return P.Error(ForwardRefValIDs.begin()->second.second,
2362 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002363 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 return false;
2365}
2366
2367
2368/// GetVal - Get a value with the specified name or ID, creating a
2369/// forward reference record if needed. This can return null if the value
2370/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002371Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002372 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 // Look this name up in the normal function symbol table.
2374 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002375
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 // If this is a forward reference for the value, see if we already created a
2377 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002378 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002379 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380 if (I != ForwardRefVals.end())
2381 Val = I->second.first;
2382 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002383
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384 // If we have the value in the symbol table or fwd-ref table, return it.
2385 if (Val) {
2386 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002387 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002388 P.Error(Loc, "'%" + Name + "' is not a basic block");
2389 else
2390 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002391 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002392 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002396 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002398 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002400
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401 // Otherwise, create a new forward reference for this value and remember it.
2402 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002403 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002404 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002405 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002406 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002408
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2410 return FwdVal;
2411}
2412
David Majnemer8a1c45d2015-12-12 05:38:55 +00002413Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002415 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 // If this is a forward reference for the value, see if we already created a
2418 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002419 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002420 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421 if (I != ForwardRefValIDs.end())
2422 Val = I->second.first;
2423 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002424
Chris Lattnerac161bf2009-01-02 07:01:27 +00002425 // If we have the value in the symbol table or fwd-ref table, return it.
2426 if (Val) {
2427 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002428 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002429 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002431 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002432 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002433 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002436 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002438 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002440
Chris Lattnerac161bf2009-01-02 07:01:27 +00002441 // Otherwise, create a new forward reference for this value and remember it.
2442 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002443 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002444 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002445 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002446 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002448
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2450 return FwdVal;
2451}
2452
2453/// SetInstName - After an instruction is parsed and inserted into its
2454/// basic block, this installs its name.
2455bool LLParser::PerFunctionState::SetInstName(int NameID,
2456 const std::string &NameStr,
2457 LocTy NameLoc, Instruction *Inst) {
2458 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002459 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 if (NameID != -1 || !NameStr.empty())
2461 return P.Error(NameLoc, "instructions returning void cannot have a name");
2462 return false;
2463 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002464
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 // If this was a numbered instruction, verify that the instruction is the
2466 // expected value and resolve any forward references.
2467 if (NameStr.empty()) {
2468 // If neither a name nor an ID was specified, just use the next ID.
2469 if (NameID == -1)
2470 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002471
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 if (unsigned(NameID) != NumberedVals.size())
2473 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002474 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002475
David Blaikie9ebdc692015-09-21 21:07:50 +00002476 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002477 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002478 Value *Sentinel = FI->second.first;
2479 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002481 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002482
2483 Sentinel->replaceAllUsesWith(Inst);
2484 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 ForwardRefValIDs.erase(FI);
2486 }
2487
2488 NumberedVals.push_back(Inst);
2489 return false;
2490 }
2491
2492 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002493 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002495 Value *Sentinel = FI->second.first;
2496 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002497 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002498 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002499
2500 Sentinel->replaceAllUsesWith(Inst);
2501 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502 ForwardRefVals.erase(FI);
2503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 // Set the name on the instruction.
2506 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002507
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002508 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002509 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002510 NameStr + "'");
2511 return false;
2512}
2513
2514/// GetBB - Get a basic block with the specified name or ID, creating a
2515/// forward reference record if needed.
2516BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2517 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002518 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2519 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520}
2521
2522BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002523 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2524 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525}
2526
2527/// DefineBB - Define the specified basic block, which is either named or
2528/// unnamed. If there is an error, this returns null otherwise it returns
2529/// the block being defined.
2530BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2531 LocTy Loc) {
2532 BasicBlock *BB;
2533 if (Name.empty())
2534 BB = GetBB(NumberedVals.size(), Loc);
2535 else
2536 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002537 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 // Move the block to the end of the function. Forward ref'd blocks are
2540 // inserted wherever they happen to be referenced.
2541 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002542
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543 // Remove the block from forward ref sets.
2544 if (Name.empty()) {
2545 ForwardRefValIDs.erase(NumberedVals.size());
2546 NumberedVals.push_back(BB);
2547 } else {
2548 // BB forward references are already in the function symbol table.
2549 ForwardRefVals.erase(Name);
2550 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002551
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 return BB;
2553}
2554
2555//===----------------------------------------------------------------------===//
2556// Constants.
2557//===----------------------------------------------------------------------===//
2558
2559/// ParseValID - Parse an abstract value that doesn't necessarily have a
2560/// type implied. For example, if we parse "4" we don't know what integer type
2561/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002562/// sanity. PFS is used to convert function-local operands of metadata (since
2563/// metadata operands are not just parsed here but also converted to values).
2564/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002565bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 ID.Loc = Lex.getLoc();
2567 switch (Lex.getKind()) {
2568 default: return TokError("expected value token");
2569 case lltok::GlobalID: // @42
2570 ID.UIntVal = Lex.getUIntVal();
2571 ID.Kind = ValID::t_GlobalID;
2572 break;
2573 case lltok::GlobalVar: // @foo
2574 ID.StrVal = Lex.getStrVal();
2575 ID.Kind = ValID::t_GlobalName;
2576 break;
2577 case lltok::LocalVarID: // %42
2578 ID.UIntVal = Lex.getUIntVal();
2579 ID.Kind = ValID::t_LocalID;
2580 break;
2581 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 ID.StrVal = Lex.getStrVal();
2583 ID.Kind = ValID::t_LocalName;
2584 break;
2585 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002586 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 ID.Kind = ValID::t_APSInt;
2588 break;
2589 case lltok::APFloat:
2590 ID.APFloatVal = Lex.getAPFloatVal();
2591 ID.Kind = ValID::t_APFloat;
2592 break;
2593 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002594 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595 ID.Kind = ValID::t_Constant;
2596 break;
2597 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002598 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 ID.Kind = ValID::t_Constant;
2600 break;
2601 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2602 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2603 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002604 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002605
Chris Lattnerac161bf2009-01-02 07:01:27 +00002606 case lltok::lbrace: {
2607 // ValID ::= '{' ConstVector '}'
2608 Lex.Lex();
2609 SmallVector<Constant*, 16> Elts;
2610 if (ParseGlobalValueVector(Elts) ||
2611 ParseToken(lltok::rbrace, "expected end of struct constant"))
2612 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002613
David Blaikieadbda4b2015-08-03 20:08:41 +00002614 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002615 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002616 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2617 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002618 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 return false;
2620 }
2621 case lltok::less: {
2622 // ValID ::= '<' ConstVector '>' --> Vector.
2623 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2624 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002625 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 SmallVector<Constant*, 16> Elts;
2628 LocTy FirstEltLoc = Lex.getLoc();
2629 if (ParseGlobalValueVector(Elts) ||
2630 (isPackedStruct &&
2631 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2632 ParseToken(lltok::greater, "expected end of constant"))
2633 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002636 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2637 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2638 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002639 ID.UIntVal = Elts.size();
2640 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 return false;
2642 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 if (Elts.empty())
2645 return Error(ID.Loc, "constant vector must not be empty");
2646
Duncan Sands9dff9be2010-02-15 16:12:20 +00002647 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002648 !Elts[0]->getType()->isFloatingPointTy() &&
2649 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002651 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 // Verify that all the vector elements have the same type.
2654 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2655 if (Elts[i]->getType() != Elts[0]->getType())
2656 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002657 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002658 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002659
Chris Lattner69229312011-02-15 00:14:00 +00002660 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 ID.Kind = ValID::t_Constant;
2662 return false;
2663 }
2664 case lltok::lsquare: { // Array Constant
2665 Lex.Lex();
2666 SmallVector<Constant*, 16> Elts;
2667 LocTy FirstEltLoc = Lex.getLoc();
2668 if (ParseGlobalValueVector(Elts) ||
2669 ParseToken(lltok::rsquare, "expected end of array constant"))
2670 return true;
2671
2672 // Handle empty element.
2673 if (Elts.empty()) {
2674 // Use undef instead of an array because it's inconvenient to determine
2675 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002676 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 return false;
2678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002679
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002681 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002682 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002683
Owen Anderson4056ca92009-07-29 22:17:13 +00002684 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002685
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002687 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 if (Elts[i]->getType() != Elts[0]->getType())
2689 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002690 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002691 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Jay Foad83be3612011-06-22 09:24:39 +00002694 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 ID.Kind = ValID::t_Constant;
2696 return false;
2697 }
2698 case lltok::kw_c: // c "foo"
2699 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002700 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2701 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002702 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2703 ID.Kind = ValID::t_Constant;
2704 return false;
2705
2706 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002707 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2708 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002709 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 Lex.Lex();
2711 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002712 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002713 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002714 ParseStringConstant(ID.StrVal) ||
2715 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 ParseToken(lltok::StringConstant, "expected constraint string"))
2717 return true;
2718 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002719 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002720 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002721 ID.Kind = ValID::t_InlineAsm;
2722 return false;
2723 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002724
Chris Lattner3432c622009-10-28 03:39:23 +00002725 case lltok::kw_blockaddress: {
2726 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2727 Lex.Lex();
2728
2729 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002730
Chris Lattner3432c622009-10-28 03:39:23 +00002731 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2732 ParseValID(Fn) ||
2733 ParseToken(lltok::comma, "expected comma in block address expression")||
2734 ParseValID(Label) ||
2735 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2736 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002737
Chris Lattner3432c622009-10-28 03:39:23 +00002738 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2739 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002740 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002741 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002742
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002743 // Try to find the function (but skip it if it's forward-referenced).
2744 GlobalValue *GV = nullptr;
2745 if (Fn.Kind == ValID::t_GlobalID) {
2746 if (Fn.UIntVal < NumberedVals.size())
2747 GV = NumberedVals[Fn.UIntVal];
2748 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2749 GV = M->getNamedValue(Fn.StrVal);
2750 }
2751 Function *F = nullptr;
2752 if (GV) {
2753 // Confirm that it's actually a function with a definition.
2754 if (!isa<Function>(GV))
2755 return Error(Fn.Loc, "expected function name in blockaddress");
2756 F = cast<Function>(GV);
2757 if (F->isDeclaration())
2758 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2759 }
2760
2761 if (!F) {
2762 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002763 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002764 ForwardRefBlockAddresses.insert(std::make_pair(
2765 std::move(Fn),
2766 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002767 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2768 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002769 if (!FwdRef)
2770 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2771 GlobalValue::InternalLinkage, nullptr, "");
2772 ID.ConstantVal = FwdRef;
2773 ID.Kind = ValID::t_Constant;
2774 return false;
2775 }
2776
2777 // We found the function; now find the basic block. Don't use PFS, since we
2778 // might be inside a constant expression.
2779 BasicBlock *BB;
2780 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2781 if (Label.Kind == ValID::t_LocalID)
2782 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2783 else
2784 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2785 if (!BB)
2786 return Error(Label.Loc, "referenced value is not a basic block");
2787 } else {
2788 if (Label.Kind == ValID::t_LocalID)
2789 return Error(Label.Loc, "cannot take address of numeric label after "
2790 "the function is defined");
2791 BB = dyn_cast_or_null<BasicBlock>(
2792 F->getValueSymbolTable().lookup(Label.StrVal));
2793 if (!BB)
2794 return Error(Label.Loc, "referenced value is not a basic block");
2795 }
2796
2797 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002798 ID.Kind = ValID::t_Constant;
2799 return false;
2800 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002801
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 case lltok::kw_trunc:
2803 case lltok::kw_zext:
2804 case lltok::kw_sext:
2805 case lltok::kw_fptrunc:
2806 case lltok::kw_fpext:
2807 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002808 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 case lltok::kw_uitofp:
2810 case lltok::kw_sitofp:
2811 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002814 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002816 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 Constant *SrcVal;
2818 Lex.Lex();
2819 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2820 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002821 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 ParseType(DestTy) ||
2823 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2824 return true;
2825 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2826 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002827 getTypeString(SrcVal->getType()) + "' to '" +
2828 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002829 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002830 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 ID.Kind = ValID::t_Constant;
2832 return false;
2833 }
2834 case lltok::kw_extractvalue: {
2835 Lex.Lex();
2836 Constant *Val;
2837 SmallVector<unsigned, 4> Indices;
2838 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2839 ParseGlobalTypeAndValue(Val) ||
2840 ParseIndexList(Indices) ||
2841 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2842 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002843
Chris Lattner392be582010-02-12 20:49:41 +00002844 if (!Val->getType()->isAggregateType())
2845 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002846 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002848 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 ID.Kind = ValID::t_Constant;
2850 return false;
2851 }
2852 case lltok::kw_insertvalue: {
2853 Lex.Lex();
2854 Constant *Val0, *Val1;
2855 SmallVector<unsigned, 4> Indices;
2856 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2857 ParseGlobalTypeAndValue(Val0) ||
2858 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2859 ParseGlobalTypeAndValue(Val1) ||
2860 ParseIndexList(Indices) ||
2861 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2862 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002863 if (!Val0->getType()->isAggregateType())
2864 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002865 Type *IndexedType =
2866 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2867 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002869 if (IndexedType != Val1->getType())
2870 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2871 getTypeString(Val1->getType()) +
2872 "' instead of '" + getTypeString(IndexedType) +
2873 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002874 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002875 ID.Kind = ValID::t_Constant;
2876 return false;
2877 }
2878 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002879 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002880 unsigned PredVal, Opc = Lex.getUIntVal();
2881 Constant *Val0, *Val1;
2882 Lex.Lex();
2883 if (ParseCmpPredicate(PredVal, Opc) ||
2884 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2885 ParseGlobalTypeAndValue(Val0) ||
2886 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2887 ParseGlobalTypeAndValue(Val1) ||
2888 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2889 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002890
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 if (Val0->getType() != Val1->getType())
2892 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002893
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895
Chris Lattnerac161bf2009-01-02 07:01:27 +00002896 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002897 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002898 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002899 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002900 } else {
2901 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002902 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002903 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002904 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002905 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002906 }
2907 ID.Kind = ValID::t_Constant;
2908 return false;
2909 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002910
Chris Lattnerac161bf2009-01-02 07:01:27 +00002911 // Binary Operators.
2912 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002913 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002915 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002916 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002917 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002918 case lltok::kw_udiv:
2919 case lltok::kw_sdiv:
2920 case lltok::kw_fdiv:
2921 case lltok::kw_urem:
2922 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002923 case lltok::kw_frem:
2924 case lltok::kw_shl:
2925 case lltok::kw_lshr:
2926 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002927 bool NUW = false;
2928 bool NSW = false;
2929 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 unsigned Opc = Lex.getUIntVal();
2931 Constant *Val0, *Val1;
2932 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002933 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002934 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2935 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002936 if (EatIfPresent(lltok::kw_nuw))
2937 NUW = true;
2938 if (EatIfPresent(lltok::kw_nsw)) {
2939 NSW = true;
2940 if (EatIfPresent(lltok::kw_nuw))
2941 NUW = true;
2942 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002943 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2944 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002945 if (EatIfPresent(lltok::kw_exact))
2946 Exact = true;
2947 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002948 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2949 ParseGlobalTypeAndValue(Val0) ||
2950 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2951 ParseGlobalTypeAndValue(Val1) ||
2952 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2953 return true;
2954 if (Val0->getType() != Val1->getType())
2955 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002956 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002957 if (NUW)
2958 return Error(ModifierLoc, "nuw only applies to integer operations");
2959 if (NSW)
2960 return Error(ModifierLoc, "nsw only applies to integer operations");
2961 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002962 // Check that the type is valid for the operator.
2963 switch (Opc) {
2964 case Instruction::Add:
2965 case Instruction::Sub:
2966 case Instruction::Mul:
2967 case Instruction::UDiv:
2968 case Instruction::SDiv:
2969 case Instruction::URem:
2970 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002971 case Instruction::Shl:
2972 case Instruction::AShr:
2973 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002974 if (!Val0->getType()->isIntOrIntVectorTy())
2975 return Error(ID.Loc, "constexpr requires integer operands");
2976 break;
2977 case Instruction::FAdd:
2978 case Instruction::FSub:
2979 case Instruction::FMul:
2980 case Instruction::FDiv:
2981 case Instruction::FRem:
2982 if (!Val0->getType()->isFPOrFPVectorTy())
2983 return Error(ID.Loc, "constexpr requires fp operands");
2984 break;
2985 default: llvm_unreachable("Unknown binary operator!");
2986 }
Dan Gohman1b849082009-09-07 23:54:19 +00002987 unsigned Flags = 0;
2988 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2989 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002990 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002991 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002992 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002993 ID.Kind = ValID::t_Constant;
2994 return false;
2995 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002996
Chris Lattnerac161bf2009-01-02 07:01:27 +00002997 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 case lltok::kw_and:
2999 case lltok::kw_or:
3000 case lltok::kw_xor: {
3001 unsigned Opc = Lex.getUIntVal();
3002 Constant *Val0, *Val1;
3003 Lex.Lex();
3004 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3005 ParseGlobalTypeAndValue(Val0) ||
3006 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3007 ParseGlobalTypeAndValue(Val1) ||
3008 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3009 return true;
3010 if (Val0->getType() != Val1->getType())
3011 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003012 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 return Error(ID.Loc,
3014 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003015 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003016 ID.Kind = ValID::t_Constant;
3017 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003018 }
3019
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 case lltok::kw_getelementptr:
3021 case lltok::kw_shufflevector:
3022 case lltok::kw_insertelement:
3023 case lltok::kw_extractelement:
3024 case lltok::kw_select: {
3025 unsigned Opc = Lex.getUIntVal();
3026 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003027 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003028 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003030
Dan Gohman1639c392009-07-27 21:53:46 +00003031 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003032 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003033
3034 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3035 return true;
3036
3037 LocTy ExplicitTypeLoc = Lex.getLoc();
3038 if (Opc == Instruction::GetElementPtr) {
3039 if (ParseType(Ty) ||
3040 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3041 return true;
3042 }
3043
3044 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3046 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003047
Chris Lattnerac161bf2009-01-02 07:01:27 +00003048 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003049 if (Elts.size() == 0 ||
3050 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003051 return Error(ID.Loc, "base of getelementptr must be a pointer");
3052
3053 Type *BaseType = Elts[0]->getType();
3054 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003055 if (Ty != BasePointerType->getElementType())
3056 return Error(
3057 ExplicitTypeLoc,
3058 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003059
Jay Foaded8db7d2011-07-21 14:31:17 +00003060 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003061 for (Constant *Val : Indices) {
3062 Type *ValTy = Val->getType();
3063 if (!ValTy->getScalarType()->isIntegerTy())
3064 return Error(ID.Loc, "getelementptr index must be an integer");
3065 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3066 return Error(ID.Loc, "getelementptr index type missmatch");
3067 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003068 unsigned ValNumEl = ValTy->getVectorNumElements();
3069 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003070 if (ValNumEl != PtrNumEl)
3071 return Error(
3072 ID.Loc,
3073 "getelementptr vector index has a wrong number of elements");
3074 }
3075 }
3076
Craig Toppere3dcce92015-08-01 22:20:21 +00003077 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003078 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003079 return Error(ID.Loc, "base element of getelementptr must be sized");
3080
David Blaikie4a2e73b2015-04-02 18:55:32 +00003081 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003082 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003083 ID.ConstantVal =
3084 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003085 } else if (Opc == Instruction::Select) {
3086 if (Elts.size() != 3)
3087 return Error(ID.Loc, "expected three operands to select");
3088 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3089 Elts[2]))
3090 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003091 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003092 } else if (Opc == Instruction::ShuffleVector) {
3093 if (Elts.size() != 3)
3094 return Error(ID.Loc, "expected three operands to shufflevector");
3095 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3096 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003097 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003098 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003099 } else if (Opc == Instruction::ExtractElement) {
3100 if (Elts.size() != 2)
3101 return Error(ID.Loc, "expected two operands to extractelement");
3102 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3103 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003104 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003105 } else {
3106 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3107 if (Elts.size() != 3)
3108 return Error(ID.Loc, "expected three operands to insertelement");
3109 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3110 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003111 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003112 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003113 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003114
Chris Lattnerac161bf2009-01-02 07:01:27 +00003115 ID.Kind = ValID::t_Constant;
3116 return false;
3117 }
3118 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003119
Chris Lattnerac161bf2009-01-02 07:01:27 +00003120 Lex.Lex();
3121 return false;
3122}
3123
3124/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003125bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003126 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003127 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003128 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003129 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003130 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003131 if (V && !(C = dyn_cast<Constant>(V)))
3132 return Error(ID.Loc, "global values must be constants");
3133 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003134}
3135
Victor Hernandez9d75c962010-01-11 22:31:58 +00003136bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003137 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003138 return ParseType(Ty) ||
3139 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003140}
3141
Rafael Espindola83a362c2015-01-06 22:55:16 +00003142bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003143 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003144
3145 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003146 if (!EatIfPresent(lltok::kw_comdat))
3147 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003148
3149 if (EatIfPresent(lltok::lparen)) {
3150 if (Lex.getKind() != lltok::ComdatVar)
3151 return TokError("expected comdat variable");
3152 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3153 Lex.Lex();
3154 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3155 return true;
3156 } else {
3157 if (GlobalName.empty())
3158 return TokError("comdat cannot be unnamed");
3159 C = getComdat(GlobalName, KwLoc);
3160 }
3161
David Majnemerdad0a642014-06-27 18:19:56 +00003162 return false;
3163}
3164
Victor Hernandez9d75c962010-01-11 22:31:58 +00003165/// ParseGlobalValueVector
3166/// ::= /*empty*/
3167/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003168bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003169 // Empty list.
3170 if (Lex.getKind() == lltok::rbrace ||
3171 Lex.getKind() == lltok::rsquare ||
3172 Lex.getKind() == lltok::greater ||
3173 Lex.getKind() == lltok::rparen)
3174 return false;
3175
3176 Constant *C;
3177 if (ParseGlobalTypeAndValue(C)) return true;
3178 Elts.push_back(C);
3179
3180 while (EatIfPresent(lltok::comma)) {
3181 if (ParseGlobalTypeAndValue(C)) return true;
3182 Elts.push_back(C);
3183 }
3184
3185 return false;
3186}
3187
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003188bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003189 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003190 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003191 return true;
3192
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003193 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003194 return false;
3195}
3196
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003197/// MDNode:
3198/// ::= !{ ... }
3199/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003200/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003201bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003202 if (Lex.getKind() == lltok::MetadataVar)
3203 return ParseSpecializedMDNode(N);
3204
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003205 return ParseToken(lltok::exclaim, "expected '!' here") ||
3206 ParseMDNodeTail(N);
3207}
3208
3209bool LLParser::ParseMDNodeTail(MDNode *&N) {
3210 // !{ ... }
3211 if (Lex.getKind() == lltok::lbrace)
3212 return ParseMDTuple(N);
3213
3214 // !42
3215 return ParseMDNodeID(N);
3216}
3217
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003218namespace {
3219
3220/// Structure to represent an optional metadata field.
3221template <class FieldTy> struct MDFieldImpl {
3222 typedef MDFieldImpl ImplTy;
3223 FieldTy Val;
3224 bool Seen;
3225
3226 void assign(FieldTy Val) {
3227 Seen = true;
3228 this->Val = std::move(Val);
3229 }
3230
3231 explicit MDFieldImpl(FieldTy Default)
3232 : Val(std::move(Default)), Seen(false) {}
3233};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003234
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003235struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3236 uint64_t Max;
3237
3238 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3239 : ImplTy(Default), Max(Max) {}
3240};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003241struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003242 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003243};
3244struct ColumnField : public MDUnsignedField {
3245 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3246};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003247struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003248 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003249 DwarfTagField(dwarf::Tag DefaultTag)
3250 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003251};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003252struct DwarfMacinfoTypeField : public MDUnsignedField {
3253 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3254 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3255 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3256};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003257struct DwarfAttEncodingField : public MDUnsignedField {
3258 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3259};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003260struct DwarfVirtualityField : public MDUnsignedField {
3261 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3262};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003263struct DwarfLangField : public MDUnsignedField {
3264 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3265};
Adrian Prantlb939a252016-03-31 23:56:58 +00003266struct EmissionKindField : public MDUnsignedField {
3267 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3268};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003269
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003270struct DIFlagField : public MDUnsignedField {
3271 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3272};
3273
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003274struct MDSignedField : public MDFieldImpl<int64_t> {
3275 int64_t Min;
3276 int64_t Max;
3277
3278 MDSignedField(int64_t Default = 0)
3279 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3280 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3281 : ImplTy(Default), Min(Min), Max(Max) {}
3282};
3283
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003284struct MDBoolField : public MDFieldImpl<bool> {
3285 MDBoolField(bool Default = false) : ImplTy(Default) {}
3286};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003287struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003288 bool AllowNull;
3289
3290 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003291};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003292struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3293 MDConstant() : ImplTy(nullptr) {}
3294};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003295struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003296 bool AllowEmpty;
3297 MDStringField(bool AllowEmpty = true)
3298 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003299};
3300struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3301 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3302};
3303
3304} // end namespace
3305
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003306namespace llvm {
3307
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003308template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003309bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003310 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003311 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3312 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003313
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003314 auto &U = Lex.getAPSIntVal();
3315 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003316 return TokError("value for '" + Name + "' too large, limit is " +
3317 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003318 Result.assign(U.getZExtValue());
3319 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003320 Lex.Lex();
3321 return false;
3322}
3323
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003324template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003325bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3326 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3327}
3328template <>
3329bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3330 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3331}
3332
3333template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003334bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3335 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003336 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003337
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003338 if (Lex.getKind() != lltok::DwarfTag)
3339 return TokError("expected DWARF tag");
3340
3341 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3342 if (Tag == dwarf::DW_TAG_invalid)
3343 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003344 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003345
3346 Result.assign(Tag);
3347 Lex.Lex();
3348 return false;
3349}
3350
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003351template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003352bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003353 DwarfMacinfoTypeField &Result) {
3354 if (Lex.getKind() == lltok::APSInt)
3355 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3356
3357 if (Lex.getKind() != lltok::DwarfMacinfo)
3358 return TokError("expected DWARF macinfo type");
3359
3360 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3361 if (Macinfo == dwarf::DW_MACINFO_invalid)
3362 return TokError(
3363 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3364 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3365
3366 Result.assign(Macinfo);
3367 Lex.Lex();
3368 return false;
3369}
3370
3371template <>
3372bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003373 DwarfVirtualityField &Result) {
3374 if (Lex.getKind() == lltok::APSInt)
3375 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3376
3377 if (Lex.getKind() != lltok::DwarfVirtuality)
3378 return TokError("expected DWARF virtuality code");
3379
3380 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003381 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003382 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3383 Lex.getStrVal() + "'");
3384 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3385 Result.assign(Virtuality);
3386 Lex.Lex();
3387 return false;
3388}
3389
3390template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003391bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3392 if (Lex.getKind() == lltok::APSInt)
3393 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3394
3395 if (Lex.getKind() != lltok::DwarfLang)
3396 return TokError("expected DWARF language");
3397
3398 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3399 if (!Lang)
3400 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3401 "'");
3402 assert(Lang <= Result.Max && "Expected valid DWARF language");
3403 Result.assign(Lang);
3404 Lex.Lex();
3405 return false;
3406}
3407
3408template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003409bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3410 if (Lex.getKind() == lltok::APSInt)
3411 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3412
3413 if (Lex.getKind() != lltok::EmissionKind)
3414 return TokError("expected emission kind");
3415
3416 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3417 if (!Kind)
3418 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3419 "'");
3420 assert(*Kind <= Result.Max && "Expected valid emission kind");
3421 Result.assign(*Kind);
3422 Lex.Lex();
3423 return false;
3424}
3425
3426template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003427bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003428 DwarfAttEncodingField &Result) {
3429 if (Lex.getKind() == lltok::APSInt)
3430 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3431
3432 if (Lex.getKind() != lltok::DwarfAttEncoding)
3433 return TokError("expected DWARF type attribute encoding");
3434
3435 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3436 if (!Encoding)
3437 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3438 Lex.getStrVal() + "'");
3439 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3440 Result.assign(Encoding);
3441 Lex.Lex();
3442 return false;
3443}
3444
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003445/// DIFlagField
3446/// ::= uint32
3447/// ::= DIFlagVector
3448/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3449template <>
3450bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3451 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3452
3453 // Parser for a single flag.
3454 auto parseFlag = [&](unsigned &Val) {
3455 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3456 return ParseUInt32(Val);
3457
3458 if (Lex.getKind() != lltok::DIFlag)
3459 return TokError("expected debug info flag");
3460
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003461 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003462 if (!Val)
3463 return TokError(Twine("invalid debug info flag flag '") +
3464 Lex.getStrVal() + "'");
3465 Lex.Lex();
3466 return false;
3467 };
3468
3469 // Parse the flags and combine them together.
3470 unsigned Combined = 0;
3471 do {
3472 unsigned Val;
3473 if (parseFlag(Val))
3474 return true;
3475 Combined |= Val;
3476 } while (EatIfPresent(lltok::bar));
3477
3478 Result.assign(Combined);
3479 return false;
3480}
3481
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003482template <>
3483bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003484 MDSignedField &Result) {
3485 if (Lex.getKind() != lltok::APSInt)
3486 return TokError("expected signed integer");
3487
3488 auto &S = Lex.getAPSIntVal();
3489 if (S < Result.Min)
3490 return TokError("value for '" + Name + "' too small, limit is " +
3491 Twine(Result.Min));
3492 if (S > Result.Max)
3493 return TokError("value for '" + Name + "' too large, limit is " +
3494 Twine(Result.Max));
3495 Result.assign(S.getExtValue());
3496 assert(Result.Val >= Result.Min && "Expected value in range");
3497 assert(Result.Val <= Result.Max && "Expected value in range");
3498 Lex.Lex();
3499 return false;
3500}
3501
3502template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003503bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3504 switch (Lex.getKind()) {
3505 default:
3506 return TokError("expected 'true' or 'false'");
3507 case lltok::kw_true:
3508 Result.assign(true);
3509 break;
3510 case lltok::kw_false:
3511 Result.assign(false);
3512 break;
3513 }
3514 Lex.Lex();
3515 return false;
3516}
3517
3518template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003519bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003520 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003521 if (!Result.AllowNull)
3522 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003523 Lex.Lex();
3524 Result.assign(nullptr);
3525 return false;
3526 }
3527
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003528 Metadata *MD;
3529 if (ParseMetadata(MD, nullptr))
3530 return true;
3531
3532 Result.assign(MD);
3533 return false;
3534}
3535
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003536template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003537bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3538 Metadata *MD;
3539 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3540 return true;
3541
3542 Result.assign(cast<ConstantAsMetadata>(MD));
3543 return false;
3544}
3545
3546template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003547bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003548 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003549 std::string S;
3550 if (ParseStringConstant(S))
3551 return true;
3552
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003553 if (!Result.AllowEmpty && S.empty())
3554 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3555
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003556 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003557 return false;
3558}
3559
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003560template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003561bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3562 SmallVector<Metadata *, 4> MDs;
3563 if (ParseMDNodeVector(MDs))
3564 return true;
3565
3566 Result.assign(std::move(MDs));
3567 return false;
3568}
3569
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003570} // end namespace llvm
3571
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003572template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003573bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003574 do {
3575 if (Lex.getKind() != lltok::LabelStr)
3576 return TokError("expected field label here");
3577
3578 if (parseField())
3579 return true;
3580 } while (EatIfPresent(lltok::comma));
3581
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003582 return false;
3583}
3584
3585template <class ParserTy>
3586bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3587 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3588 Lex.Lex();
3589
3590 if (ParseToken(lltok::lparen, "expected '(' here"))
3591 return true;
3592 if (Lex.getKind() != lltok::rparen)
3593 if (ParseMDFieldsImplBody(parseField))
3594 return true;
3595
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003596 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003597 return ParseToken(lltok::rparen, "expected ')' here");
3598}
3599
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003600template <class FieldTy>
3601bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3602 if (Result.Seen)
3603 return TokError("field '" + Name + "' cannot be specified more than once");
3604
3605 LocTy Loc = Lex.getLoc();
3606 Lex.Lex();
3607 return ParseMDField(Loc, Name, Result);
3608}
3609
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003610bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3611 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003612
3613#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003614 if (Lex.getStrVal() == #CLASS) \
3615 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003616#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003617
3618 return TokError("expected metadata type");
3619}
3620
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003621#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3622#define NOP_FIELD(NAME, TYPE, INIT)
3623#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3624 if (!NAME.Seen) \
3625 return Error(ClosingLoc, "missing required field '" #NAME "'");
3626#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003627 if (Lex.getStrVal() == #NAME) \
3628 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003629#define PARSE_MD_FIELDS() \
3630 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3631 do { \
3632 LocTy ClosingLoc; \
3633 if (ParseMDFieldsImpl([&]() -> bool { \
3634 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3635 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3636 }, ClosingLoc)) \
3637 return true; \
3638 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3639 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003640#define GET_OR_DISTINCT(CLASS, ARGS) \
3641 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003642
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003643/// ParseDILocationFields:
3644/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3645bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003646#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003647 OPTIONAL(line, LineField, ); \
3648 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003649 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003650 OPTIONAL(inlinedAt, MDField, );
3651 PARSE_MD_FIELDS();
3652#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003653
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003654 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003655 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003656 return false;
3657}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003658
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003659/// ParseGenericDINode:
3660/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3661bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003662#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003663 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003664 OPTIONAL(header, MDStringField, ); \
3665 OPTIONAL(operands, MDFieldList, );
3666 PARSE_MD_FIELDS();
3667#undef VISIT_MD_FIELDS
3668
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003669 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003670 (Context, tag.Val, header.Val, operands.Val));
3671 return false;
3672}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003673
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003674/// ParseDISubrange:
3675/// ::= !DISubrange(count: 30, lowerBound: 2)
3676bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003677#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003678 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003679 OPTIONAL(lowerBound, MDSignedField, );
3680 PARSE_MD_FIELDS();
3681#undef VISIT_MD_FIELDS
3682
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003683 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003684 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003685}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003686
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003687/// ParseDIEnumerator:
3688/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3689bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003690#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003691 REQUIRED(name, MDStringField, ); \
3692 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003693 PARSE_MD_FIELDS();
3694#undef VISIT_MD_FIELDS
3695
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003696 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003697 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003698}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003699
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003700/// ParseDIBasicType:
3701/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3702bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003703#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003704 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003705 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003706 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3707 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003708 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003709 PARSE_MD_FIELDS();
3710#undef VISIT_MD_FIELDS
3711
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003712 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003713 align.Val, encoding.Val));
3714 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003715}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003716
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003717/// ParseDIDerivedType:
3718/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003719/// line: 7, scope: !1, baseType: !2, size: 32,
3720/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003721bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003722#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3723 REQUIRED(tag, DwarfTagField, ); \
3724 OPTIONAL(name, MDStringField, ); \
3725 OPTIONAL(file, MDField, ); \
3726 OPTIONAL(line, LineField, ); \
3727 OPTIONAL(scope, MDField, ); \
3728 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003729 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3730 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3731 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003732 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003733 OPTIONAL(extraData, MDField, );
3734 PARSE_MD_FIELDS();
3735#undef VISIT_MD_FIELDS
3736
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003737 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003738 (Context, tag.Val, name.Val, file.Val, line.Val,
3739 scope.Val, baseType.Val, size.Val, align.Val,
3740 offset.Val, flags.Val, extraData.Val));
3741 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003742}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003743
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003744bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003745#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3746 REQUIRED(tag, DwarfTagField, ); \
3747 OPTIONAL(name, MDStringField, ); \
3748 OPTIONAL(file, MDField, ); \
3749 OPTIONAL(line, LineField, ); \
3750 OPTIONAL(scope, MDField, ); \
3751 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003752 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3753 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3754 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003755 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003756 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003757 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003758 OPTIONAL(vtableHolder, MDField, ); \
3759 OPTIONAL(templateParams, MDField, ); \
3760 OPTIONAL(identifier, MDStringField, );
3761 PARSE_MD_FIELDS();
3762#undef VISIT_MD_FIELDS
3763
3764 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003765 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003766 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3767 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3768 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3769 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003770}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003771
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003772bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003773#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003774 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003775 REQUIRED(types, MDField, );
3776 PARSE_MD_FIELDS();
3777#undef VISIT_MD_FIELDS
3778
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003779 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003780 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003781}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003782
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783/// ParseDIFileType:
3784/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3785bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003786#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3787 REQUIRED(filename, MDStringField, ); \
3788 REQUIRED(directory, MDStringField, );
3789 PARSE_MD_FIELDS();
3790#undef VISIT_MD_FIELDS
3791
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003792 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003793 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003794}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003795
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003796/// ParseDICompileUnit:
3797/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003798/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003799/// splitDebugFilename: "abc.debug",
3800/// emissionKind: FullDebug,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003801/// enums: !1, retainedTypes: !2, subprograms: !3,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003802/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003803bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003804 if (!IsDistinct)
3805 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3806
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003807#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3808 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003809 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003810 OPTIONAL(producer, MDStringField, ); \
3811 OPTIONAL(isOptimized, MDBoolField, ); \
3812 OPTIONAL(flags, MDStringField, ); \
3813 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3814 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003815 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003816 OPTIONAL(enums, MDField, ); \
3817 OPTIONAL(retainedTypes, MDField, ); \
3818 OPTIONAL(subprograms, MDField, ); \
3819 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003820 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003821 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003822 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003823 PARSE_MD_FIELDS();
3824#undef VISIT_MD_FIELDS
3825
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003826 Result = DICompileUnit::getDistinct(
3827 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3828 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003829 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, macros.Val,
3830 dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003831 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003832}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003833
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003834/// ParseDISubprogram:
3835/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003836/// file: !1, line: 7, type: !2, isLocal: false,
3837/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003838/// virtuality: DW_VIRTUALTIY_pure_virtual,
3839/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003840/// isOptimized: false, templateParams: !4, declaration: !5,
3841/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003842bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003843 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003844#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3845 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003846 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003847 OPTIONAL(linkageName, MDStringField, ); \
3848 OPTIONAL(file, MDField, ); \
3849 OPTIONAL(line, LineField, ); \
3850 OPTIONAL(type, MDField, ); \
3851 OPTIONAL(isLocal, MDBoolField, ); \
3852 OPTIONAL(isDefinition, MDBoolField, (true)); \
3853 OPTIONAL(scopeLine, LineField, ); \
3854 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003855 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003856 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003857 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003858 OPTIONAL(isOptimized, MDBoolField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003859 OPTIONAL(templateParams, MDField, ); \
3860 OPTIONAL(declaration, MDField, ); \
3861 OPTIONAL(variables, MDField, );
3862 PARSE_MD_FIELDS();
3863#undef VISIT_MD_FIELDS
3864
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003865 if (isDefinition.Val && !IsDistinct)
3866 return Lex.Error(
3867 Loc,
3868 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3869
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003870 Result = GET_OR_DISTINCT(
Peter Collingbourned4bff302015-11-05 22:03:56 +00003871 DISubprogram,
3872 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
3873 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
3874 containingType.Val, virtuality.Val, virtualIndex.Val, flags.Val,
3875 isOptimized.Val, templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003876 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003877}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003878
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003879/// ParseDILexicalBlock:
3880/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3881bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003882#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003883 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003884 OPTIONAL(file, MDField, ); \
3885 OPTIONAL(line, LineField, ); \
3886 OPTIONAL(column, ColumnField, );
3887 PARSE_MD_FIELDS();
3888#undef VISIT_MD_FIELDS
3889
3890 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003891 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003892 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003893}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003894
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003895/// ParseDILexicalBlockFile:
3896/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3897bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003898#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003899 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003900 OPTIONAL(file, MDField, ); \
3901 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3902 PARSE_MD_FIELDS();
3903#undef VISIT_MD_FIELDS
3904
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003905 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003906 (Context, scope.Val, file.Val, discriminator.Val));
3907 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003908}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003909
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003910/// ParseDINamespace:
3911/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3912bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003913#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3914 REQUIRED(scope, MDField, ); \
3915 OPTIONAL(file, MDField, ); \
3916 OPTIONAL(name, MDStringField, ); \
3917 OPTIONAL(line, LineField, );
3918 PARSE_MD_FIELDS();
3919#undef VISIT_MD_FIELDS
3920
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003921 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003922 (Context, scope.Val, file.Val, name.Val, line.Val));
3923 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003924}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003925
Amjad Abouda9bcf162015-12-10 12:56:35 +00003926/// ParseDIMacro:
3927/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3928bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3929#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3930 REQUIRED(type, DwarfMacinfoTypeField, ); \
3931 REQUIRED(line, LineField, ); \
3932 REQUIRED(name, MDStringField, ); \
3933 OPTIONAL(value, MDStringField, );
3934 PARSE_MD_FIELDS();
3935#undef VISIT_MD_FIELDS
3936
3937 Result = GET_OR_DISTINCT(DIMacro,
3938 (Context, type.Val, line.Val, name.Val, value.Val));
3939 return false;
3940}
3941
3942/// ParseDIMacroFile:
3943/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
3944bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
3945#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3946 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
3947 REQUIRED(line, LineField, ); \
3948 REQUIRED(file, MDField, ); \
3949 OPTIONAL(nodes, MDField, );
3950 PARSE_MD_FIELDS();
3951#undef VISIT_MD_FIELDS
3952
3953 Result = GET_OR_DISTINCT(DIMacroFile,
3954 (Context, type.Val, line.Val, file.Val, nodes.Val));
3955 return false;
3956}
3957
3958
Adrian Prantlab1243f2015-06-29 23:03:47 +00003959/// ParseDIModule:
3960/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3961/// includePath: "/usr/include", isysroot: "/")
3962bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3963#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3964 REQUIRED(scope, MDField, ); \
3965 REQUIRED(name, MDStringField, ); \
3966 OPTIONAL(configMacros, MDStringField, ); \
3967 OPTIONAL(includePath, MDStringField, ); \
3968 OPTIONAL(isysroot, MDStringField, );
3969 PARSE_MD_FIELDS();
3970#undef VISIT_MD_FIELDS
3971
3972 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3973 configMacros.Val, includePath.Val, isysroot.Val));
3974 return false;
3975}
3976
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003977/// ParseDITemplateTypeParameter:
3978/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3979bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003980#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003981 OPTIONAL(name, MDStringField, ); \
3982 REQUIRED(type, MDField, );
3983 PARSE_MD_FIELDS();
3984#undef VISIT_MD_FIELDS
3985
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003986 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003987 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003988 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003989}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003990
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003991/// ParseDITemplateValueParameter:
3992/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003993/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003994bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003995#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003996 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003997 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003998 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003999 REQUIRED(value, MDField, );
4000 PARSE_MD_FIELDS();
4001#undef VISIT_MD_FIELDS
4002
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004003 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004004 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004005 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004006}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004007
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004008/// ParseDIGlobalVariable:
4009/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004010/// file: !1, line: 7, type: !2, isLocal: false,
4011/// isDefinition: true, variable: i32* @foo,
4012/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004013bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004014#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004015 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004016 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004017 OPTIONAL(linkageName, MDStringField, ); \
4018 OPTIONAL(file, MDField, ); \
4019 OPTIONAL(line, LineField, ); \
4020 OPTIONAL(type, MDField, ); \
4021 OPTIONAL(isLocal, MDBoolField, ); \
4022 OPTIONAL(isDefinition, MDBoolField, (true)); \
4023 OPTIONAL(variable, MDConstant, ); \
4024 OPTIONAL(declaration, MDField, );
4025 PARSE_MD_FIELDS();
4026#undef VISIT_MD_FIELDS
4027
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004028 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004029 (Context, scope.Val, name.Val, linkageName.Val,
4030 file.Val, line.Val, type.Val, isLocal.Val,
4031 isDefinition.Val, variable.Val, declaration.Val));
4032 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004033}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004034
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004035/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004036/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4037/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4038/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004039/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004040bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004041#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004042 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004043 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004044 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004045 OPTIONAL(file, MDField, ); \
4046 OPTIONAL(line, LineField, ); \
4047 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004048 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004049 PARSE_MD_FIELDS();
4050#undef VISIT_MD_FIELDS
4051
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004052 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004053 (Context, scope.Val, name.Val, file.Val, line.Val,
4054 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004055 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004056}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004057
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004058/// ParseDIExpression:
4059/// ::= !DIExpression(0, 7, -1)
4060bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004061 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4062 Lex.Lex();
4063
4064 if (ParseToken(lltok::lparen, "expected '(' here"))
4065 return true;
4066
4067 SmallVector<uint64_t, 8> Elements;
4068 if (Lex.getKind() != lltok::rparen)
4069 do {
4070 if (Lex.getKind() == lltok::DwarfOp) {
4071 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4072 Lex.Lex();
4073 Elements.push_back(Op);
4074 continue;
4075 }
4076 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4077 }
4078
4079 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4080 return TokError("expected unsigned integer");
4081
4082 auto &U = Lex.getAPSIntVal();
4083 if (U.ugt(UINT64_MAX))
4084 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4085 Elements.push_back(U.getZExtValue());
4086 Lex.Lex();
4087 } while (EatIfPresent(lltok::comma));
4088
4089 if (ParseToken(lltok::rparen, "expected ')' here"))
4090 return true;
4091
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004092 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004093 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004094}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004095
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004096/// ParseDIObjCProperty:
4097/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004098/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004099bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004100#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004101 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004102 OPTIONAL(file, MDField, ); \
4103 OPTIONAL(line, LineField, ); \
4104 OPTIONAL(setter, MDStringField, ); \
4105 OPTIONAL(getter, MDStringField, ); \
4106 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4107 OPTIONAL(type, MDField, );
4108 PARSE_MD_FIELDS();
4109#undef VISIT_MD_FIELDS
4110
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004111 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004112 (Context, name.Val, file.Val, line.Val, setter.Val,
4113 getter.Val, attributes.Val, type.Val));
4114 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004115}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004116
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004117/// ParseDIImportedEntity:
4118/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004119/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004120bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004121#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4122 REQUIRED(tag, DwarfTagField, ); \
4123 REQUIRED(scope, MDField, ); \
4124 OPTIONAL(entity, MDField, ); \
4125 OPTIONAL(line, LineField, ); \
4126 OPTIONAL(name, MDStringField, );
4127 PARSE_MD_FIELDS();
4128#undef VISIT_MD_FIELDS
4129
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004130 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004131 entity.Val, line.Val, name.Val));
4132 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004133}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004134
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004135#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004136#undef NOP_FIELD
4137#undef REQUIRE_FIELD
4138#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004139
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004140/// ParseMetadataAsValue
4141/// ::= metadata i32 %local
4142/// ::= metadata i32 @global
4143/// ::= metadata i32 7
4144/// ::= metadata !0
4145/// ::= metadata !{...}
4146/// ::= metadata !"string"
4147bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4148 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004149 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004150 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004151 return true;
4152
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004153 V = MetadataAsValue::get(Context, MD);
4154 return false;
4155}
4156
4157/// ParseValueAsMetadata
4158/// ::= i32 %local
4159/// ::= i32 @global
4160/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004161bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4162 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004163 Type *Ty;
4164 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004165 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004166 return true;
4167 if (Ty->isMetadataTy())
4168 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4169
4170 Value *V;
4171 if (ParseValue(Ty, V, PFS))
4172 return true;
4173
4174 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004175 return false;
4176}
4177
4178/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004179/// ::= i32 %local
4180/// ::= i32 @global
4181/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004182/// ::= !42
4183/// ::= !{...}
4184/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004185/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004186bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004187 if (Lex.getKind() == lltok::MetadataVar) {
4188 MDNode *N;
4189 if (ParseSpecializedMDNode(N))
4190 return true;
4191 MD = N;
4192 return false;
4193 }
4194
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004195 // ValueAsMetadata:
4196 // <type> <value>
4197 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004198 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004199
4200 // '!'.
4201 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4202 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004203
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004204 // MDString:
4205 // ::= '!' STRINGCONSTANT
4206 if (Lex.getKind() == lltok::StringConstant) {
4207 MDString *S;
4208 if (ParseMDString(S))
4209 return true;
4210 MD = S;
4211 return false;
4212 }
4213
Dan Gohman8939ba332010-07-14 18:26:50 +00004214 // MDNode:
4215 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004216 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004217 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004218 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004219 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004220 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004221 return false;
4222}
4223
Victor Hernandez9d75c962010-01-11 22:31:58 +00004224
4225//===----------------------------------------------------------------------===//
4226// Function Parsing.
4227//===----------------------------------------------------------------------===//
4228
Chris Lattner229907c2011-07-18 04:54:35 +00004229bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004230 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004231 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004232 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004233
Chris Lattnerac161bf2009-01-02 07:01:27 +00004234 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004235 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004236 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004237 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004238 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004239 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004240 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004241 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004242 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004243 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004244 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004245 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004246 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4247 (ID.UIntVal >> 1) & 1,
4248 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004249 return false;
4250 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004251 case ValID::t_GlobalName:
4252 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004253 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004254 case ValID::t_GlobalID:
4255 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004256 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004258 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004259 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004260 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004261 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004262 return false;
4263 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004264 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004265 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4266 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004267
Dan Gohman518cda42011-12-17 00:04:22 +00004268 // The lexer has no type info, so builds all half, float, and double FP
4269 // constants as double. Fix this here. Long double does not need this.
4270 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004271 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004272 if (Ty->isHalfTy())
4273 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4274 &Ignored);
4275 else if (Ty->isFloatTy())
4276 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4277 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004278 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004279 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004280
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004281 if (V->getType() != Ty)
4282 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004283 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004284
Chris Lattnerac161bf2009-01-02 07:01:27 +00004285 return false;
4286 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004287 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004288 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004289 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004290 return false;
4291 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004292 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004293 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004294 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004295 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004296 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004297 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004298 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004299 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004300 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004301 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004302 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004303 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004304 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004305 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004306 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004307 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004308 case ValID::t_None:
4309 if (!Ty->isTokenTy())
4310 return Error(ID.Loc, "invalid type for none constant");
4311 V = Constant::getNullValue(Ty);
4312 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004313 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004314 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004315 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004316
Chris Lattnerac161bf2009-01-02 07:01:27 +00004317 V = ID.ConstantVal;
4318 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004319 case ValID::t_ConstantStruct:
4320 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004321 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004322 if (ST->getNumElements() != ID.UIntVal)
4323 return Error(ID.Loc,
4324 "initializer with struct type has wrong # elements");
4325 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4326 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004327
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004328 // Verify that the elements are compatible with the structtype.
4329 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4330 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4331 return Error(ID.Loc, "element " + Twine(i) +
4332 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004333
David Blaikieadbda4b2015-08-03 20:08:41 +00004334 V = ConstantStruct::get(
4335 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004336 } else
4337 return Error(ID.Loc, "constant expression type mismatch");
4338 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004339 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004340 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004341}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004342
Alex Lorenzd2255952015-07-17 22:07:03 +00004343bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4344 C = nullptr;
4345 ValID ID;
4346 auto Loc = Lex.getLoc();
4347 if (ParseValID(ID, /*PFS=*/nullptr))
4348 return true;
4349 switch (ID.Kind) {
4350 case ValID::t_APSInt:
4351 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004352 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004353 case ValID::t_Constant:
4354 case ValID::t_ConstantStruct:
4355 case ValID::t_PackedConstantStruct: {
4356 Value *V;
4357 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4358 return true;
4359 assert(isa<Constant>(V) && "Expected a constant value");
4360 C = cast<Constant>(V);
4361 return false;
4362 }
4363 default:
4364 return Error(Loc, "expected a constant value");
4365 }
4366}
4367
David Majnemer8a1c45d2015-12-12 05:38:55 +00004368bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004369 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004370 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004371 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004372}
4373
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004374bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004375 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004376 return ParseType(Ty) ||
4377 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004378}
4379
Chris Lattner3ed871f2009-10-27 19:13:16 +00004380bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4381 PerFunctionState &PFS) {
4382 Value *V;
4383 Loc = Lex.getLoc();
4384 if (ParseTypeAndValue(V, PFS)) return true;
4385 if (!isa<BasicBlock>(V))
4386 return Error(Loc, "expected a basic block");
4387 BB = cast<BasicBlock>(V);
4388 return false;
4389}
4390
4391
Chris Lattnerac161bf2009-01-02 07:01:27 +00004392/// FunctionHeader
4393/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004394/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004395/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4397 // Parse the linkage.
4398 LocTy LinkageLoc = Lex.getLoc();
4399 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004400
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004401 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004402 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004403 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004404 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004405 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004406 LocTy RetTypeLoc = Lex.getLoc();
4407 if (ParseOptionalLinkage(Linkage) ||
4408 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004409 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004410 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004411 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004412 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004413 return true;
4414
4415 // Verify that the linkage is ok.
4416 switch ((GlobalValue::LinkageTypes)Linkage) {
4417 case GlobalValue::ExternalLinkage:
4418 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004419 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004420 if (isDefine)
4421 return Error(LinkageLoc, "invalid linkage for function definition");
4422 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004423 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004424 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004425 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004426 case GlobalValue::LinkOnceAnyLinkage:
4427 case GlobalValue::LinkOnceODRLinkage:
4428 case GlobalValue::WeakAnyLinkage:
4429 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004430 if (!isDefine)
4431 return Error(LinkageLoc, "invalid linkage for function declaration");
4432 break;
4433 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004434 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004435 return Error(LinkageLoc, "invalid function linkage type");
4436 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004437
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004438 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4439 return Error(LinkageLoc,
4440 "symbol with local linkage must have default visibility");
4441
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004442 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004443 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004444
Chris Lattnerac161bf2009-01-02 07:01:27 +00004445 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004446
4447 std::string FunctionName;
4448 if (Lex.getKind() == lltok::GlobalVar) {
4449 FunctionName = Lex.getStrVal();
4450 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4451 unsigned NameID = Lex.getUIntVal();
4452
4453 if (NameID != NumberedVals.size())
4454 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004455 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004456 } else {
4457 return TokError("expected function name");
4458 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004459
Chris Lattner3822f632009-01-02 08:05:26 +00004460 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004461
Chris Lattner3822f632009-01-02 08:05:26 +00004462 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004464
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004465 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004466 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004467 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004468 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004469 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004470 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004471 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004472 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004473 bool UnnamedAddr;
4474 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004475 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004476 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004477 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004478 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004479
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004480 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004481 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4482 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004483 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004484 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004485 (EatIfPresent(lltok::kw_section) &&
4486 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004487 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004488 ParseOptionalAlignment(Alignment) ||
4489 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004490 ParseStringConstant(GC)) ||
4491 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004492 ParseGlobalTypeAndValue(Prefix)) ||
4493 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004494 ParseGlobalTypeAndValue(Prologue)) ||
4495 (EatIfPresent(lltok::kw_personality) &&
4496 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004497 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004498
Michael Gottesman41748d72013-06-27 00:25:01 +00004499 if (FuncAttrs.contains(Attribute::Builtin))
4500 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004501
Chris Lattnerac161bf2009-01-02 07:01:27 +00004502 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004503 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004504 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004505 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004506 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004507
Chris Lattnerac161bf2009-01-02 07:01:27 +00004508 // Okay, if we got here, the function is syntactically valid. Convert types
4509 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004510 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004511 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004512
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004513 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004514 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4515 AttributeSet::ReturnIndex,
4516 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004517
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004519 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004520 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4521 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004522 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4523 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 }
4525
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004526 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004527 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4528 AttributeSet::FunctionIndex,
4529 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530
Bill Wendlinge94d8432012-12-07 23:16:57 +00004531 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004532
Bill Wendling749a43d2012-12-30 13:50:49 +00004533 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004534 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4535
Chris Lattner229907c2011-07-18 04:54:35 +00004536 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004537 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004538 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004539
Craig Topper2617dcc2014-04-15 06:32:26 +00004540 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 if (!FunctionName.empty()) {
4542 // If this was a definition of a forward reference, remove the definition
4543 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004544 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 if (FRVI != ForwardRefVals.end()) {
4546 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004547 if (!Fn)
4548 return Error(FRVI->second.second, "invalid forward reference to "
4549 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004550 if (Fn->getType() != PFT)
4551 return Error(FRVI->second.second, "invalid forward reference to "
4552 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004553
Chris Lattnerac161bf2009-01-02 07:01:27 +00004554 ForwardRefVals.erase(FRVI);
4555 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004556 // Reject redefinitions.
4557 return Error(NameLoc, "invalid redefinition of function '" +
4558 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004559 } else if (M->getNamedValue(FunctionName)) {
4560 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004561 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004562
Dan Gohman399d6ae2009-08-29 23:37:49 +00004563 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004564 // If this is a definition of a forward referenced function, make sure the
4565 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004566 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004567 if (I != ForwardRefValIDs.end()) {
4568 Fn = cast<Function>(I->second.first);
4569 if (Fn->getType() != PFT)
4570 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004571 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 ForwardRefValIDs.erase(I);
4573 }
4574 }
4575
Craig Topper2617dcc2014-04-15 06:32:26 +00004576 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004577 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4578 else // Move the forward-reference to the correct spot in the module.
4579 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4580
4581 if (FunctionName.empty())
4582 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004583
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4585 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004586 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004587 Fn->setCallingConv(CC);
4588 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004589 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590 Fn->setAlignment(Alignment);
4591 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004592 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004593 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004594 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004595 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004596 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004597 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004598
Chris Lattnerac161bf2009-01-02 07:01:27 +00004599 // Add all of the arguments we parsed to the function.
4600 Function::arg_iterator ArgIt = Fn->arg_begin();
4601 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4602 // If the argument has a name, insert it into the argument symbol table.
4603 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004604
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 // Set the name, if it conflicted, it will be auto-renamed.
4606 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004607
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004608 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4610 ArgList[i].Name + "'");
4611 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004612
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004613 if (isDefine)
4614 return false;
4615
Robin Morisset039781e2014-08-29 21:53:01 +00004616 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004617 ValID ID;
4618 if (FunctionName.empty()) {
4619 ID.Kind = ValID::t_GlobalID;
4620 ID.UIntVal = NumberedVals.size() - 1;
4621 } else {
4622 ID.Kind = ValID::t_GlobalName;
4623 ID.StrVal = FunctionName;
4624 }
4625 auto Blocks = ForwardRefBlockAddresses.find(ID);
4626 if (Blocks != ForwardRefBlockAddresses.end())
4627 return Error(Blocks->first.Loc,
4628 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629 return false;
4630}
4631
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004632bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4633 ValID ID;
4634 if (FunctionNumber == -1) {
4635 ID.Kind = ValID::t_GlobalName;
4636 ID.StrVal = F.getName();
4637 } else {
4638 ID.Kind = ValID::t_GlobalID;
4639 ID.UIntVal = FunctionNumber;
4640 }
4641
4642 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4643 if (Blocks == P.ForwardRefBlockAddresses.end())
4644 return false;
4645
4646 for (const auto &I : Blocks->second) {
4647 const ValID &BBID = I.first;
4648 GlobalValue *GV = I.second;
4649
4650 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4651 "Expected local id or name");
4652 BasicBlock *BB;
4653 if (BBID.Kind == ValID::t_LocalName)
4654 BB = GetBB(BBID.StrVal, BBID.Loc);
4655 else
4656 BB = GetBB(BBID.UIntVal, BBID.Loc);
4657 if (!BB)
4658 return P.Error(BBID.Loc, "referenced value is not a basic block");
4659
4660 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4661 GV->eraseFromParent();
4662 }
4663
4664 P.ForwardRefBlockAddresses.erase(Blocks);
4665 return false;
4666}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004667
4668/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004669/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004670bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004671 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 return TokError("expected '{' in function body");
4673 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004674
Chris Lattner3432c622009-10-28 03:39:23 +00004675 int FunctionNumber = -1;
4676 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004677
Chris Lattner3432c622009-10-28 03:39:23 +00004678 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004679
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004680 // Resolve block addresses and allow basic blocks to be forward-declared
4681 // within this function.
4682 if (PFS.resolveForwardRefBlockAddresses())
4683 return true;
4684 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4685
Chris Lattnerbbddd962010-01-09 19:20:07 +00004686 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004687 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004688 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004689
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004690 while (Lex.getKind() != lltok::rbrace &&
4691 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004692 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004693
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004694 while (Lex.getKind() != lltok::rbrace)
4695 if (ParseUseListOrder(&PFS))
4696 return true;
4697
Chris Lattnerac161bf2009-01-02 07:01:27 +00004698 // Eat the }.
4699 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004700
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004702 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004703}
4704
4705/// ParseBasicBlock
4706/// ::= LabelStr? Instruction*
4707bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4708 // If this basic block starts out with a name, remember it.
4709 std::string Name;
4710 LocTy NameLoc = Lex.getLoc();
4711 if (Lex.getKind() == lltok::LabelStr) {
4712 Name = Lex.getStrVal();
4713 Lex.Lex();
4714 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004715
Chris Lattnerac161bf2009-01-02 07:01:27 +00004716 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004717 if (!BB)
4718 return Error(NameLoc,
4719 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004720
Chris Lattnerac161bf2009-01-02 07:01:27 +00004721 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004722
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 // Parse the instructions in this block until we get a terminator.
4724 Instruction *Inst;
4725 do {
4726 // This instruction may have three possibilities for a name: a) none
4727 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4728 LocTy NameLoc = Lex.getLoc();
4729 int NameID = -1;
4730 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004731
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 if (Lex.getKind() == lltok::LocalVarID) {
4733 NameID = Lex.getUIntVal();
4734 Lex.Lex();
4735 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4736 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004737 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004738 NameStr = Lex.getStrVal();
4739 Lex.Lex();
4740 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4741 return true;
4742 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004743
Chris Lattner77b89dc2009-12-30 05:23:43 +00004744 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004745 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004746 case InstError: return true;
4747 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004748 BB->getInstList().push_back(Inst);
4749
Chris Lattner77b89dc2009-12-30 05:23:43 +00004750 // With a normal result, we check to see if the instruction is followed by
4751 // a comma and metadata.
4752 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004753 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004754 return true;
4755 break;
4756 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004757 BB->getInstList().push_back(Inst);
4758
Chris Lattner77b89dc2009-12-30 05:23:43 +00004759 // If the instruction parser ate an extra comma at the end of it, it
4760 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004761 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004762 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004763 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004764 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004765
Chris Lattnerac161bf2009-01-02 07:01:27 +00004766 // Set the name on the instruction.
4767 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4768 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004769
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770 return false;
4771}
4772
4773//===----------------------------------------------------------------------===//
4774// Instruction Parsing.
4775//===----------------------------------------------------------------------===//
4776
4777/// ParseInstruction - Parse one of the many different instructions.
4778///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004779int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4780 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 lltok::Kind Token = Lex.getKind();
4782 if (Token == lltok::Eof)
4783 return TokError("found end of file when expecting more instructions");
4784 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004785 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004786 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004787
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 switch (Token) {
4789 default: return Error(Loc, "expected instruction opcode");
4790 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004791 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004792 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4793 case lltok::kw_br: return ParseBr(Inst, PFS);
4794 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004795 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004797 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004798 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4799 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004800 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4801 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004802 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803 // Binary Operators.
4804 case lltok::kw_add:
4805 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004806 case lltok::kw_mul:
4807 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004808 bool NUW = EatIfPresent(lltok::kw_nuw);
4809 bool NSW = EatIfPresent(lltok::kw_nsw);
4810 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004811
Chris Lattnera676c0f2011-02-07 16:40:21 +00004812 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004813
Chris Lattnera676c0f2011-02-07 16:40:21 +00004814 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4815 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4816 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004817 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004818 case lltok::kw_fadd:
4819 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004820 case lltok::kw_fmul:
4821 case lltok::kw_fdiv:
4822 case lltok::kw_frem: {
4823 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4824 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4825 if (Res != 0)
4826 return Res;
4827 if (FMF.any())
4828 Inst->setFastMathFlags(FMF);
4829 return 0;
4830 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004831
Chris Lattner35315d02011-02-06 21:44:57 +00004832 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004833 case lltok::kw_udiv:
4834 case lltok::kw_lshr:
4835 case lltok::kw_ashr: {
4836 bool Exact = EatIfPresent(lltok::kw_exact);
4837
4838 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4839 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4840 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004841 }
4842
Chris Lattnerac161bf2009-01-02 07:01:27 +00004843 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004844 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004845 case lltok::kw_and:
4846 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004847 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004848 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4849 case lltok::kw_fcmp: {
4850 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4851 int Res = ParseCompare(Inst, PFS, KeywordVal);
4852 if (Res != 0)
4853 return Res;
4854 if (FMF.any())
4855 Inst->setFastMathFlags(FMF);
4856 return 0;
4857 }
4858
Chris Lattnerac161bf2009-01-02 07:01:27 +00004859 // Casts.
4860 case lltok::kw_trunc:
4861 case lltok::kw_zext:
4862 case lltok::kw_sext:
4863 case lltok::kw_fptrunc:
4864 case lltok::kw_fpext:
4865 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004866 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 case lltok::kw_uitofp:
4868 case lltok::kw_sitofp:
4869 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004870 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004871 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004872 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004873 // Other.
4874 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004875 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004876 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4877 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4878 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4879 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004880 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004881 // Call.
4882 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4883 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4884 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004885 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004886 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004887 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004888 case lltok::kw_load: return ParseLoad(Inst, PFS);
4889 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004890 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4891 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004892 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004893 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4894 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4895 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4896 }
4897}
4898
4899/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4900bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004901 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004902 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004903 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004904 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4905 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4906 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4907 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4908 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4909 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4910 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4911 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4912 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4913 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4914 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4915 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4916 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4917 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4918 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4919 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4920 }
4921 } else {
4922 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004923 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4925 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4926 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4927 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4928 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4929 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4930 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4931 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4932 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4933 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4934 }
4935 }
4936 Lex.Lex();
4937 return false;
4938}
4939
4940//===----------------------------------------------------------------------===//
4941// Terminator Instructions.
4942//===----------------------------------------------------------------------===//
4943
4944/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004945/// ::= 'ret' void (',' !dbg, !1)*
4946/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004947bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004948 PerFunctionState &PFS) {
4949 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004950 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004951 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004952
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004953 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004954
Chris Lattnerfdd87902009-10-05 05:54:46 +00004955 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004956 if (!ResType->isVoidTy())
4957 return Error(TypeLoc, "value doesn't match function result type '" +
4958 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004959
Owen Anderson55f1c092009-08-13 21:58:54 +00004960 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961 return false;
4962 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004963
Chris Lattnerac161bf2009-01-02 07:01:27 +00004964 Value *RV;
4965 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004966
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004967 if (ResType != RV->getType())
4968 return Error(TypeLoc, "value doesn't match function result type '" +
4969 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004970
Owen Anderson55f1c092009-08-13 21:58:54 +00004971 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004972 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004973}
4974
4975
4976/// ParseBr
4977/// ::= 'br' TypeAndValue
4978/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4979bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4980 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004981 Value *Op0;
4982 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004983 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004984
Chris Lattnerac161bf2009-01-02 07:01:27 +00004985 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4986 Inst = BranchInst::Create(BB);
4987 return false;
4988 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004989
Owen Anderson55f1c092009-08-13 21:58:54 +00004990 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004991 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004992
Chris Lattnerac161bf2009-01-02 07:01:27 +00004993 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004994 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004996 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004997 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004998
Chris Lattner3ed871f2009-10-27 19:13:16 +00004999 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005000 return false;
5001}
5002
5003/// ParseSwitch
5004/// Instruction
5005/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5006/// JumpTable
5007/// ::= (TypeAndValue ',' TypeAndValue)*
5008bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5009 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005010 Value *Cond;
5011 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005012 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5013 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005014 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005015 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5016 return true;
5017
Duncan Sands19d0b472010-02-16 11:11:14 +00005018 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005019 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005020
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 // Parse the jump table pairs.
5022 SmallPtrSet<Value*, 32> SeenCases;
5023 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5024 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005025 Value *Constant;
5026 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005027
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5029 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005030 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005031 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005032
David Blaikie70573dc2014-11-19 07:49:26 +00005033 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005034 return Error(CondLoc, "duplicate case value in switch");
5035 if (!isa<ConstantInt>(Constant))
5036 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005037
Chris Lattner3ed871f2009-10-27 19:13:16 +00005038 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005040
Chris Lattnerac161bf2009-01-02 07:01:27 +00005041 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005042
Chris Lattner3ed871f2009-10-27 19:13:16 +00005043 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005044 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5045 SI->addCase(Table[i].first, Table[i].second);
5046 Inst = SI;
5047 return false;
5048}
5049
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005050/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005051/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005052/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5053bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005054 LocTy AddrLoc;
5055 Value *Address;
5056 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005057 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5058 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005059 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005060
Duncan Sands19d0b472010-02-16 11:11:14 +00005061 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005062 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005063
Chris Lattner3ed871f2009-10-27 19:13:16 +00005064 // Parse the destination list.
5065 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005066
Chris Lattner3ed871f2009-10-27 19:13:16 +00005067 if (Lex.getKind() != lltok::rsquare) {
5068 BasicBlock *DestBB;
5069 if (ParseTypeAndBasicBlock(DestBB, PFS))
5070 return true;
5071 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005072
Chris Lattner3ed871f2009-10-27 19:13:16 +00005073 while (EatIfPresent(lltok::comma)) {
5074 if (ParseTypeAndBasicBlock(DestBB, PFS))
5075 return true;
5076 DestList.push_back(DestBB);
5077 }
5078 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005079
Chris Lattner3ed871f2009-10-27 19:13:16 +00005080 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5081 return true;
5082
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005083 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005084 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5085 IBI->addDestination(DestList[i]);
5086 Inst = IBI;
5087 return false;
5088}
5089
5090
Chris Lattnerac161bf2009-01-02 07:01:27 +00005091/// ParseInvoke
5092/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5093/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5094bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5095 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005096 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005097 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005098 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005099 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005100 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 LocTy RetTypeLoc;
5102 ValID CalleeID;
5103 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005104 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005105
Chris Lattner3ed871f2009-10-27 19:13:16 +00005106 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005107 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005108 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005109 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005110 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5111 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005112 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005114 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005115 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005116 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005117 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005118
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 // If RetType is a non-function pointer type, then this is the short syntax
5120 // for the call, which means that RetType is just the return type. Infer the
5121 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005122 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5123 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005124 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005125 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005126 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5127 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005128
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 if (!FunctionType::isValidReturnType(RetType))
5130 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Owen Anderson4056ca92009-07-29 22:17:13 +00005132 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005133 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005134
David Blaikie41ba2b42015-07-27 23:32:19 +00005135 CalleeID.FTy = Ty;
5136
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 // Look up the callee.
5138 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005139 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5140 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005141
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005142 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005143 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005144 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005145 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5146 AttributeSet::ReturnIndex,
5147 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005148
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005150
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 // Loop through FunctionType's arguments and ensure they are specified
5152 // correctly. Also, gather any parameter attributes.
5153 FunctionType::param_iterator I = Ty->param_begin();
5154 FunctionType::param_iterator E = Ty->param_end();
5155 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005156 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005157 if (I != E) {
5158 ExpectedTy = *I++;
5159 } else if (!Ty->isVarArg()) {
5160 return Error(ArgList[i].Loc, "too many arguments specified");
5161 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005162
Chris Lattnerac161bf2009-01-02 07:01:27 +00005163 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5164 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005165 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005167 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5168 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005169 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5170 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005171 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005172
Chris Lattnerac161bf2009-01-02 07:01:27 +00005173 if (I != E)
5174 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005175
David Majnemer8d22abd2015-02-23 00:01:32 +00005176 if (FnAttrs.hasAttributes()) {
5177 if (FnAttrs.hasAlignmentAttr())
5178 return Error(CallLoc, "invoke instructions may not have an alignment");
5179
Bill Wendlingf5075a42013-01-27 02:24:02 +00005180 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5181 AttributeSet::FunctionIndex,
5182 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005184
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005185 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005186 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005187
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005188 InvokeInst *II =
5189 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 II->setCallingConv(CC);
5191 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005192 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005193 Inst = II;
5194 return false;
5195}
5196
Bill Wendlingf891bf82011-07-31 06:30:59 +00005197/// ParseResume
5198/// ::= 'resume' TypeAndValue
5199bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5200 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005201 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5202 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005203
Bill Wendlingf891bf82011-07-31 06:30:59 +00005204 ResumeInst *RI = ResumeInst::Create(Exn);
5205 Inst = RI;
5206 return false;
5207}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208
David Majnemer654e1302015-07-31 17:58:14 +00005209bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5210 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005211 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005212 return true;
5213
5214 while (Lex.getKind() != lltok::rsquare) {
5215 // If this isn't the first argument, we need a comma.
5216 if (!Args.empty() &&
5217 ParseToken(lltok::comma, "expected ',' in argument list"))
5218 return true;
5219
5220 // Parse the argument.
5221 LocTy ArgLoc;
5222 Type *ArgTy = nullptr;
5223 if (ParseType(ArgTy, ArgLoc))
5224 return true;
5225
5226 Value *V;
5227 if (ArgTy->isMetadataTy()) {
5228 if (ParseMetadataAsValue(V, PFS))
5229 return true;
5230 } else {
5231 if (ParseValue(ArgTy, V, PFS))
5232 return true;
5233 }
5234 Args.push_back(V);
5235 }
5236
5237 Lex.Lex(); // Lex the ']'.
5238 return false;
5239}
5240
5241/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005242/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005243bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005244 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005245
David Majnemer8a1c45d2015-12-12 05:38:55 +00005246 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5247 return true;
5248
5249 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005250 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005251
5252 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5253 return true;
5254
5255 BasicBlock *UnwindBB = nullptr;
5256 if (Lex.getKind() == lltok::kw_to) {
5257 Lex.Lex();
5258 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5259 return true;
5260 } else {
5261 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5262 return true;
5263 }
5264 }
5265
David Majnemer8a1c45d2015-12-12 05:38:55 +00005266 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005267 return false;
5268}
5269
5270/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005271/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005272bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005273 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005274
David Majnemer8a1c45d2015-12-12 05:38:55 +00005275 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5276 return true;
5277
5278 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005279 return true;
5280
David Majnemer0bc0eef2015-08-15 02:46:08 +00005281 BasicBlock *BB;
5282 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5283 ParseTypeAndBasicBlock(BB, PFS))
5284 return true;
5285
David Majnemer8a1c45d2015-12-12 05:38:55 +00005286 Inst = CatchReturnInst::Create(CatchPad, BB);
5287 return false;
5288}
5289
5290/// ParseCatchSwitch
5291/// ::= 'catchswitch' within Parent
5292bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5293 Value *ParentPad;
5294 LocTy BBLoc;
5295
5296 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5297 return true;
5298
5299 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5300 Lex.getKind() != lltok::LocalVarID)
5301 return TokError("expected scope value for catchswitch");
5302
5303 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5304 return true;
5305
5306 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5307 return true;
5308
5309 SmallVector<BasicBlock *, 32> Table;
5310 do {
5311 BasicBlock *DestBB;
5312 if (ParseTypeAndBasicBlock(DestBB, PFS))
5313 return true;
5314 Table.push_back(DestBB);
5315 } while (EatIfPresent(lltok::comma));
5316
5317 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5318 return true;
5319
5320 if (ParseToken(lltok::kw_unwind,
5321 "expected 'unwind' after catchswitch scope"))
5322 return true;
5323
5324 BasicBlock *UnwindBB = nullptr;
5325 if (EatIfPresent(lltok::kw_to)) {
5326 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5327 return true;
5328 } else {
5329 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5330 return true;
5331 }
5332
5333 auto *CatchSwitch =
5334 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5335 for (BasicBlock *DestBB : Table)
5336 CatchSwitch->addHandler(DestBB);
5337 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005338 return false;
5339}
5340
5341/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005342/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005343bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005344 Value *CatchSwitch = nullptr;
5345
5346 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5347 return true;
5348
5349 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5350 return TokError("expected scope value for catchpad");
5351
5352 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5353 return true;
5354
David Majnemer654e1302015-07-31 17:58:14 +00005355 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005356 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005357 return true;
5358
David Majnemer8a1c45d2015-12-12 05:38:55 +00005359 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005360 return false;
5361}
5362
David Majnemer654e1302015-07-31 17:58:14 +00005363/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005364/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005365bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005366 Value *ParentPad = nullptr;
5367
5368 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5369 return true;
5370
5371 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5372 Lex.getKind() != lltok::LocalVarID)
5373 return TokError("expected scope value for cleanuppad");
5374
5375 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5376 return true;
5377
David Majnemer654e1302015-07-31 17:58:14 +00005378 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005379 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005380 return true;
5381
David Majnemer8a1c45d2015-12-12 05:38:55 +00005382 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005383 return false;
5384}
5385
Chris Lattnerac161bf2009-01-02 07:01:27 +00005386//===----------------------------------------------------------------------===//
5387// Binary Operators.
5388//===----------------------------------------------------------------------===//
5389
5390/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005391/// ::= ArithmeticOps TypeAndValue ',' Value
5392///
5393/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5394/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005395bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005396 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005397 LocTy Loc; Value *LHS, *RHS;
5398 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5399 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5400 ParseValue(LHS->getType(), RHS, PFS))
5401 return true;
5402
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005403 bool Valid;
5404 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005405 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005406 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005407 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5408 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005409 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005410 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5411 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005412 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005413
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005414 if (!Valid)
5415 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005416
Chris Lattnerac161bf2009-01-02 07:01:27 +00005417 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5418 return false;
5419}
5420
5421/// ParseLogical
5422/// ::= ArithmeticOps TypeAndValue ',' Value {
5423bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5424 unsigned Opc) {
5425 LocTy Loc; Value *LHS, *RHS;
5426 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5427 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5428 ParseValue(LHS->getType(), RHS, PFS))
5429 return true;
5430
Duncan Sands9dff9be2010-02-15 16:12:20 +00005431 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005432 return Error(Loc,"instruction requires integer or integer vector operands");
5433
5434 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5435 return false;
5436}
5437
5438
5439/// ParseCompare
5440/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5441/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005442bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5443 unsigned Opc) {
5444 // Parse the integer/fp comparison predicate.
5445 LocTy Loc;
5446 unsigned Pred;
5447 Value *LHS, *RHS;
5448 if (ParseCmpPredicate(Pred, Opc) ||
5449 ParseTypeAndValue(LHS, Loc, PFS) ||
5450 ParseToken(lltok::comma, "expected ',' after compare value") ||
5451 ParseValue(LHS->getType(), RHS, PFS))
5452 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005453
Chris Lattnerac161bf2009-01-02 07:01:27 +00005454 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005455 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005456 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005457 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005458 } else {
5459 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005460 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005461 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005462 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005463 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005464 }
5465 return false;
5466}
5467
5468//===----------------------------------------------------------------------===//
5469// Other Instructions.
5470//===----------------------------------------------------------------------===//
5471
5472
5473/// ParseCast
5474/// ::= CastOpc TypeAndValue 'to' Type
5475bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5476 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005477 LocTy Loc;
5478 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005479 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005480 if (ParseTypeAndValue(Op, Loc, PFS) ||
5481 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5482 ParseType(DestTy))
5483 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005484
Chris Lattner89d856e2009-03-01 00:53:13 +00005485 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5486 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005487 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005488 getTypeString(Op->getType()) + "' to '" +
5489 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005490 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005491 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5492 return false;
5493}
5494
5495/// ParseSelect
5496/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5497bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5498 LocTy Loc;
5499 Value *Op0, *Op1, *Op2;
5500 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5501 ParseToken(lltok::comma, "expected ',' after select condition") ||
5502 ParseTypeAndValue(Op1, PFS) ||
5503 ParseToken(lltok::comma, "expected ',' after select value") ||
5504 ParseTypeAndValue(Op2, PFS))
5505 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005506
Chris Lattnerac161bf2009-01-02 07:01:27 +00005507 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5508 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005509
Chris Lattnerac161bf2009-01-02 07:01:27 +00005510 Inst = SelectInst::Create(Op0, Op1, Op2);
5511 return false;
5512}
5513
Chris Lattnerb55ab542009-01-05 08:18:44 +00005514/// ParseVA_Arg
5515/// ::= 'va_arg' TypeAndValue ',' Type
5516bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005517 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005518 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005519 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005520 if (ParseTypeAndValue(Op, PFS) ||
5521 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005522 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005523 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005524
Chris Lattnerb55ab542009-01-05 08:18:44 +00005525 if (!EltTy->isFirstClassType())
5526 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005527
5528 Inst = new VAArgInst(Op, EltTy);
5529 return false;
5530}
5531
5532/// ParseExtractElement
5533/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5534bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5535 LocTy Loc;
5536 Value *Op0, *Op1;
5537 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5538 ParseToken(lltok::comma, "expected ',' after extract value") ||
5539 ParseTypeAndValue(Op1, PFS))
5540 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005541
Chris Lattnerac161bf2009-01-02 07:01:27 +00005542 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5543 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005544
Eric Christopherc9742252009-07-25 02:28:41 +00005545 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005546 return false;
5547}
5548
5549/// ParseInsertElement
5550/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5551bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5552 LocTy Loc;
5553 Value *Op0, *Op1, *Op2;
5554 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5555 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5556 ParseTypeAndValue(Op1, PFS) ||
5557 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5558 ParseTypeAndValue(Op2, PFS))
5559 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005560
Chris Lattnerac161bf2009-01-02 07:01:27 +00005561 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005562 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005563
Chris Lattnerac161bf2009-01-02 07:01:27 +00005564 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5565 return false;
5566}
5567
5568/// ParseShuffleVector
5569/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5570bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5571 LocTy Loc;
5572 Value *Op0, *Op1, *Op2;
5573 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5574 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5575 ParseTypeAndValue(Op1, PFS) ||
5576 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5577 ParseTypeAndValue(Op2, PFS))
5578 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005579
Chris Lattnerac161bf2009-01-02 07:01:27 +00005580 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005581 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005582
Chris Lattnerac161bf2009-01-02 07:01:27 +00005583 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5584 return false;
5585}
5586
5587/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005588/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005589int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005590 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005591 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005592
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005593 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005594 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5595 ParseValue(Ty, Op0, PFS) ||
5596 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005597 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005598 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5599 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005600
Chris Lattnerf4f03422009-12-30 05:27:33 +00005601 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005602 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5603 while (1) {
5604 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005605
Chris Lattner3822f632009-01-02 08:05:26 +00005606 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005607 break;
5608
Chris Lattnerf4f03422009-12-30 05:27:33 +00005609 if (Lex.getKind() == lltok::MetadataVar) {
5610 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005611 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005612 }
Devang Patel8f842d32009-10-16 18:45:49 +00005613
Chris Lattner3822f632009-01-02 08:05:26 +00005614 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005615 ParseValue(Ty, Op0, PFS) ||
5616 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005617 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005618 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5619 return true;
5620 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005621
Chris Lattnerac161bf2009-01-02 07:01:27 +00005622 if (!Ty->isFirstClassType())
5623 return Error(TypeLoc, "phi node must have first class type");
5624
Jay Foad52131342011-03-30 11:28:46 +00005625 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005626 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5627 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5628 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005629 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005630}
5631
Bill Wendlingfae14752011-08-12 20:24:12 +00005632/// ParseLandingPad
5633/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5634/// Clause
5635/// ::= 'catch' TypeAndValue
5636/// ::= 'filter'
5637/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5638bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005639 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005640
David Majnemer7fddecc2015-06-17 20:52:32 +00005641 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005642 return true;
5643
David Majnemer7fddecc2015-06-17 20:52:32 +00005644 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005645 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5646
5647 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5648 LandingPadInst::ClauseType CT;
5649 if (EatIfPresent(lltok::kw_catch))
5650 CT = LandingPadInst::Catch;
5651 else if (EatIfPresent(lltok::kw_filter))
5652 CT = LandingPadInst::Filter;
5653 else
5654 return TokError("expected 'catch' or 'filter' clause type");
5655
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005656 Value *V;
5657 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005658 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005659 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005660
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005661 // A 'catch' type expects a non-array constant. A filter clause expects an
5662 // array constant.
5663 if (CT == LandingPadInst::Catch) {
5664 if (isa<ArrayType>(V->getType()))
5665 Error(VLoc, "'catch' clause has an invalid type");
5666 } else {
5667 if (!isa<ArrayType>(V->getType()))
5668 Error(VLoc, "'filter' clause has an invalid type");
5669 }
5670
Owen Andersonf8f259d2015-03-09 07:13:42 +00005671 Constant *CV = dyn_cast<Constant>(V);
5672 if (!CV)
5673 return Error(VLoc, "clause argument must be a constant");
5674 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005675 }
5676
Owen Andersonf8f259d2015-03-09 07:13:42 +00005677 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005678 return false;
5679}
5680
Chris Lattnerac161bf2009-01-02 07:01:27 +00005681/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005682/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5683/// OptionalAttrs Type Value ParameterList OptionalAttrs
5684/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5685/// OptionalAttrs Type Value ParameterList OptionalAttrs
5686/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5687/// OptionalAttrs Type Value ParameterList OptionalAttrs
5688/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5689/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005690bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005691 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005692 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005693 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005694 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005695 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005696 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697 LocTy RetTypeLoc;
5698 ValID CalleeID;
5699 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005700 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005701 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005702
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005703 if (TCK != CallInst::TCK_None &&
5704 ParseToken(lltok::kw_call,
5705 "expected 'tail call', 'musttail call', or 'notail call'"))
5706 return true;
5707
5708 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5709
5710 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005711 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005713 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5714 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005715 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5716 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005718
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005719 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5720 return Error(CallLoc, "fast-math-flags specified for call without "
5721 "floating-point scalar or vector return type");
5722
Chris Lattnerac161bf2009-01-02 07:01:27 +00005723 // If RetType is a non-function pointer type, then this is the short syntax
5724 // for the call, which means that RetType is just the return type. Infer the
5725 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005726 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5727 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005728 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005729 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005730 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5731 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005732
Chris Lattnerac161bf2009-01-02 07:01:27 +00005733 if (!FunctionType::isValidReturnType(RetType))
5734 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005735
Owen Anderson4056ca92009-07-29 22:17:13 +00005736 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005738
David Blaikie41ba2b42015-07-27 23:32:19 +00005739 CalleeID.FTy = Ty;
5740
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 // Look up the callee.
5742 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005743 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5744 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005745
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005746 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005747 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005748 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005749 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5750 AttributeSet::ReturnIndex,
5751 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005752
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005754
Chris Lattnerac161bf2009-01-02 07:01:27 +00005755 // Loop through FunctionType's arguments and ensure they are specified
5756 // correctly. Also, gather any parameter attributes.
5757 FunctionType::param_iterator I = Ty->param_begin();
5758 FunctionType::param_iterator E = Ty->param_end();
5759 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005760 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005761 if (I != E) {
5762 ExpectedTy = *I++;
5763 } else if (!Ty->isVarArg()) {
5764 return Error(ArgList[i].Loc, "too many arguments specified");
5765 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005766
Chris Lattnerac161bf2009-01-02 07:01:27 +00005767 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5768 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005769 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005770 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005771 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5772 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005773 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5774 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005775 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005776
Chris Lattnerac161bf2009-01-02 07:01:27 +00005777 if (I != E)
5778 return Error(CallLoc, "not enough parameters specified for call");
5779
David Majnemer8d22abd2015-02-23 00:01:32 +00005780 if (FnAttrs.hasAttributes()) {
5781 if (FnAttrs.hasAlignmentAttr())
5782 return Error(CallLoc, "call instructions may not have an alignment");
5783
Bill Wendlingf5075a42013-01-27 02:24:02 +00005784 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5785 AttributeSet::FunctionIndex,
5786 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005787 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005789 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005790 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005791
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005792 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005793 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005794 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005795 if (FMF.any())
5796 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005797 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005798 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005799 Inst = CI;
5800 return false;
5801}
5802
5803//===----------------------------------------------------------------------===//
5804// Memory Instructions.
5805//===----------------------------------------------------------------------===//
5806
5807/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005808/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5809/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005810int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005811 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005812 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005814 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005815
5816 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005817 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005818
David Majnemera3b0eb22015-02-16 08:38:03 +00005819 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005820
David Majnemera3b0eb22015-02-16 08:38:03 +00005821 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5822 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005823
Chris Lattnerb2f39502009-12-30 05:44:30 +00005824 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005825 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005826 if (Lex.getKind() == lltok::kw_align) {
5827 if (ParseOptionalAlignment(Alignment)) return true;
5828 } else if (Lex.getKind() == lltok::MetadataVar) {
5829 AteExtraComma = true;
5830 } else {
5831 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5832 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5833 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005834 }
5835 }
5836
Dan Gohman2140a742010-05-28 01:14:11 +00005837 if (Size && !Size->getType()->isIntegerTy())
5838 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005839
Reid Kleckner436c42e2014-01-17 23:58:17 +00005840 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5841 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005842 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005843 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005844 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005845}
5846
5847/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005848/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005849/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005850/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005851int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005853 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005854 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005855 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005856 AtomicOrdering Ordering = NotAtomic;
5857 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005858
5859 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005860 isAtomic = true;
5861 Lex.Lex();
5862 }
5863
Chris Lattnerbc639292011-11-27 06:56:53 +00005864 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005865 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005866 isVolatile = true;
5867 Lex.Lex();
5868 }
5869
David Blaikie15d9a4c2015-04-06 20:59:48 +00005870 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005871 LocTy ExplicitTypeLoc = Lex.getLoc();
5872 if (ParseType(Ty) ||
5873 ParseToken(lltok::comma, "expected comma after load's type") ||
5874 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005875 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005876 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5877 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005878
David Blaikie15d9a4c2015-04-06 20:59:48 +00005879 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005881 if (isAtomic && !Alignment)
5882 return Error(Loc, "atomic load must have explicit non-zero alignment");
5883 if (Ordering == Release || Ordering == AcquireRelease)
5884 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005885
David Blaikiea79ac142015-02-27 21:17:42 +00005886 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5887 return Error(ExplicitTypeLoc,
5888 "explicit pointee type doesn't match operand's pointee type");
5889
David Blaikie15d9a4c2015-04-06 20:59:48 +00005890 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005891 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005892}
5893
5894/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005895
5896/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5897/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005898/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005899int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005900 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005901 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005902 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005903 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005904 AtomicOrdering Ordering = NotAtomic;
5905 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005906
5907 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005908 isAtomic = true;
5909 Lex.Lex();
5910 }
5911
Chris Lattnerbc639292011-11-27 06:56:53 +00005912 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005913 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005914 isVolatile = true;
5915 Lex.Lex();
5916 }
5917
Chris Lattnerac161bf2009-01-02 07:01:27 +00005918 if (ParseTypeAndValue(Val, Loc, PFS) ||
5919 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005920 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005921 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005922 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005923 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005924
Duncan Sands19d0b472010-02-16 11:11:14 +00005925 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005926 return Error(PtrLoc, "store operand must be a pointer");
5927 if (!Val->getType()->isFirstClassType())
5928 return Error(Loc, "store operand must be a first class value");
5929 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5930 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005931 if (isAtomic && !Alignment)
5932 return Error(Loc, "atomic store must have explicit non-zero alignment");
5933 if (Ordering == Acquire || Ordering == AcquireRelease)
5934 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005935
Eli Friedman59b66882011-08-09 23:02:53 +00005936 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005937 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005938}
5939
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005940/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005941/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5942/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005943int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005944 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5945 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005946 AtomicOrdering SuccessOrdering = NotAtomic;
5947 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005948 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005949 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005950 bool isWeak = false;
5951
5952 if (EatIfPresent(lltok::kw_weak))
5953 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005954
5955 if (EatIfPresent(lltok::kw_volatile))
5956 isVolatile = true;
5957
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005958 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5959 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5960 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5961 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5962 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005963 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5964 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005965 return true;
5966
Tim Northovere94a5182014-03-11 10:48:52 +00005967 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005968 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005969 if (SuccessOrdering < FailureOrdering)
5970 return TokError("cmpxchg must be at least as ordered on success as failure");
5971 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5972 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005973 if (!Ptr->getType()->isPointerTy())
5974 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5975 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5976 return Error(CmpLoc, "compare value and pointer type do not match");
5977 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5978 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00005979 if (!New->getType()->isFirstClassType())
5980 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00005981 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5982 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005983 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005984 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005985 Inst = CXI;
5986 return AteExtraComma ? InstExtraComma : InstNormal;
5987}
5988
5989/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005990/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5991/// 'singlethread'? AtomicOrdering
5992int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005993 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5994 bool AteExtraComma = false;
5995 AtomicOrdering Ordering = NotAtomic;
5996 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005997 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005998 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005999
6000 if (EatIfPresent(lltok::kw_volatile))
6001 isVolatile = true;
6002
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006003 switch (Lex.getKind()) {
6004 default: return TokError("expected binary operation in atomicrmw");
6005 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6006 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6007 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6008 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6009 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6010 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6011 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6012 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6013 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6014 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6015 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6016 }
6017 Lex.Lex(); // Eat the operation.
6018
6019 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6020 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6021 ParseTypeAndValue(Val, ValLoc, PFS) ||
6022 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6023 return true;
6024
6025 if (Ordering == Unordered)
6026 return TokError("atomicrmw cannot be unordered");
6027 if (!Ptr->getType()->isPointerTy())
6028 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6029 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6030 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6031 if (!Val->getType()->isIntegerTy())
6032 return Error(ValLoc, "atomicrmw operand must be an integer");
6033 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6034 if (Size < 8 || (Size & (Size - 1)))
6035 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6036 " integer");
6037
6038 AtomicRMWInst *RMWI =
6039 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6040 RMWI->setVolatile(isVolatile);
6041 Inst = RMWI;
6042 return AteExtraComma ? InstExtraComma : InstNormal;
6043}
6044
Eli Friedmanfee02c62011-07-25 23:16:38 +00006045/// ParseFence
6046/// ::= 'fence' 'singlethread'? AtomicOrdering
6047int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6048 AtomicOrdering Ordering = NotAtomic;
6049 SynchronizationScope Scope = CrossThread;
6050 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6051 return true;
6052
6053 if (Ordering == Unordered)
6054 return TokError("fence cannot be unordered");
6055 if (Ordering == Monotonic)
6056 return TokError("fence cannot be monotonic");
6057
6058 Inst = new FenceInst(Context, Ordering, Scope);
6059 return InstNormal;
6060}
6061
Chris Lattnerac161bf2009-01-02 07:01:27 +00006062/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006063/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006064int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006065 Value *Ptr = nullptr;
6066 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006067 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006068
Dan Gohman16cbbe42009-07-29 15:58:36 +00006069 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006070
David Blaikie79e6c742015-02-27 19:29:02 +00006071 Type *Ty = nullptr;
6072 LocTy ExplicitTypeLoc = Lex.getLoc();
6073 if (ParseType(Ty) ||
6074 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6075 ParseTypeAndValue(Ptr, Loc, PFS))
6076 return true;
6077
Eli Benderskyd9806682013-04-22 17:03:42 +00006078 Type *BaseType = Ptr->getType();
6079 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6080 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006081 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006082
David Blaikie8d757942015-03-09 23:08:44 +00006083 if (Ty != BasePointerType->getElementType())
6084 return Error(ExplicitTypeLoc,
6085 "explicit pointee type doesn't match operand's pointee type");
6086
Chris Lattnerac161bf2009-01-02 07:01:27 +00006087 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006088 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006089 // GEP returns a vector of pointers if at least one of parameters is a vector.
6090 // All vector parameters should have the same vector width.
6091 unsigned GEPWidth = BaseType->isVectorTy() ?
6092 BaseType->getVectorNumElements() : 0;
6093
Chris Lattner3822f632009-01-02 08:05:26 +00006094 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006095 if (Lex.getKind() == lltok::MetadataVar) {
6096 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006097 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006098 }
Chris Lattner3822f632009-01-02 08:05:26 +00006099 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006100 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006101 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006102
Nadav Rotem3924cb02011-12-05 06:29:09 +00006103 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006104 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6105 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006106 return Error(EltLoc,
6107 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006108 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006109 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006110 Indices.push_back(Val);
6111 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006112
Craig Toppere3dcce92015-08-01 22:20:21 +00006113 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006114 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006115 return Error(Loc, "base element of getelementptr must be sized");
6116
David Blaikied33bad32015-04-17 22:32:13 +00006117 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006118 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006119 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006120 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006121 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006122 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006123}
6124
6125/// ParseExtractValue
6126/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006127int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006128 Value *Val; LocTy Loc;
6129 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006130 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006131 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006132 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006133 return true;
6134
Chris Lattner392be582010-02-12 20:49:41 +00006135 if (!Val->getType()->isAggregateType())
6136 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006137
Jay Foad57aa6362011-07-13 10:26:04 +00006138 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006139 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006140 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006141 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006142}
6143
6144/// ParseInsertValue
6145/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006146int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006147 Value *Val0, *Val1; LocTy Loc0, Loc1;
6148 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006149 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006150 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6151 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6152 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006153 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006154 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006155
Chris Lattner392be582010-02-12 20:49:41 +00006156 if (!Val0->getType()->isAggregateType())
6157 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006158
David Majnemer30074532015-02-11 07:43:58 +00006159 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6160 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006161 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006162 if (IndexedType != Val1->getType())
6163 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6164 getTypeString(Val1->getType()) + "' instead of '" +
6165 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006166 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006167 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006168}
Nick Lewycky49f89192009-04-04 07:22:01 +00006169
6170//===----------------------------------------------------------------------===//
6171// Embedded metadata.
6172//===----------------------------------------------------------------------===//
6173
6174/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006175/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006176/// Element
6177/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006178bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006179 if (ParseToken(lltok::lbrace, "expected '{' here"))
6180 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006181
Dan Gohman1e0213a2010-07-13 19:33:27 +00006182 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006183 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006184 return false;
6185
Nick Lewycky49f89192009-04-04 07:22:01 +00006186 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006187 // Null is a special case since it is typeless.
6188 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006189 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006190 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006191 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006192
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006193 Metadata *MD;
6194 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006195 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006196 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006197 } while (EatIfPresent(lltok::comma));
6198
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006199 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006200}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006201
6202//===----------------------------------------------------------------------===//
6203// Use-list order directives.
6204//===----------------------------------------------------------------------===//
6205bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6206 SMLoc Loc) {
6207 if (V->use_empty())
6208 return Error(Loc, "value has no uses");
6209
6210 unsigned NumUses = 0;
6211 SmallDenseMap<const Use *, unsigned, 16> Order;
6212 for (const Use &U : V->uses()) {
6213 if (++NumUses > Indexes.size())
6214 break;
6215 Order[&U] = Indexes[NumUses - 1];
6216 }
6217 if (NumUses < 2)
6218 return Error(Loc, "value only has one use");
6219 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6220 return Error(Loc, "wrong number of indexes, expected " +
6221 Twine(std::distance(V->use_begin(), V->use_end())));
6222
6223 V->sortUseList([&](const Use &L, const Use &R) {
6224 return Order.lookup(&L) < Order.lookup(&R);
6225 });
6226 return false;
6227}
6228
6229/// ParseUseListOrderIndexes
6230/// ::= '{' uint32 (',' uint32)+ '}'
6231bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6232 SMLoc Loc = Lex.getLoc();
6233 if (ParseToken(lltok::lbrace, "expected '{' here"))
6234 return true;
6235 if (Lex.getKind() == lltok::rbrace)
6236 return Lex.Error("expected non-empty list of uselistorder indexes");
6237
6238 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6239 // indexes should be distinct numbers in the range [0, size-1], and should
6240 // not be in order.
6241 unsigned Offset = 0;
6242 unsigned Max = 0;
6243 bool IsOrdered = true;
6244 assert(Indexes.empty() && "Expected empty order vector");
6245 do {
6246 unsigned Index;
6247 if (ParseUInt32(Index))
6248 return true;
6249
6250 // Update consistency checks.
6251 Offset += Index - Indexes.size();
6252 Max = std::max(Max, Index);
6253 IsOrdered &= Index == Indexes.size();
6254
6255 Indexes.push_back(Index);
6256 } while (EatIfPresent(lltok::comma));
6257
6258 if (ParseToken(lltok::rbrace, "expected '}' here"))
6259 return true;
6260
6261 if (Indexes.size() < 2)
6262 return Error(Loc, "expected >= 2 uselistorder indexes");
6263 if (Offset != 0 || Max >= Indexes.size())
6264 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6265 if (IsOrdered)
6266 return Error(Loc, "expected uselistorder indexes to change the order");
6267
6268 return false;
6269}
6270
6271/// ParseUseListOrder
6272/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6273bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6274 SMLoc Loc = Lex.getLoc();
6275 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6276 return true;
6277
6278 Value *V;
6279 SmallVector<unsigned, 16> Indexes;
6280 if (ParseTypeAndValue(V, PFS) ||
6281 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6282 ParseUseListOrderIndexes(Indexes))
6283 return true;
6284
6285 return sortUseListOrder(V, Indexes, Loc);
6286}
6287
6288/// ParseUseListOrderBB
6289/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6290bool LLParser::ParseUseListOrderBB() {
6291 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6292 SMLoc Loc = Lex.getLoc();
6293 Lex.Lex();
6294
6295 ValID Fn, Label;
6296 SmallVector<unsigned, 16> Indexes;
6297 if (ParseValID(Fn) ||
6298 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6299 ParseValID(Label) ||
6300 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6301 ParseUseListOrderIndexes(Indexes))
6302 return true;
6303
6304 // Check the function.
6305 GlobalValue *GV;
6306 if (Fn.Kind == ValID::t_GlobalName)
6307 GV = M->getNamedValue(Fn.StrVal);
6308 else if (Fn.Kind == ValID::t_GlobalID)
6309 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6310 else
6311 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6312 if (!GV)
6313 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6314 auto *F = dyn_cast<Function>(GV);
6315 if (!F)
6316 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6317 if (F->isDeclaration())
6318 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6319
6320 // Check the basic block.
6321 if (Label.Kind == ValID::t_LocalID)
6322 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6323 if (Label.Kind != ValID::t_LocalName)
6324 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6325 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6326 if (!V)
6327 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6328 if (!isa<BasicBlock>(V))
6329 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6330
6331 return sortUseListOrder(V, Indexes, Loc);
6332}